summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDongHun Kwak <dh0128.kwak@samsung.com>2021-10-08 09:13:08 +0900
committerDongHun Kwak <dh0128.kwak@samsung.com>2021-10-08 09:13:08 +0900
commit488e9638b71b8b9cdb3055835815d77720eae06b (patch)
treef023cbc75da671dd2b75d3143cde8a066d5a93aa
parentf152fd464ac355590a5bb95451d4cd1ca1079d3c (diff)
downloadcmake-upstream/3.10.0.tar.gz
cmake-upstream/3.10.0.tar.bz2
cmake-upstream/3.10.0.zip
Imported Upstream version 3.10.0upstream/3.10.0
-rw-r--r--.clang-format1
-rw-r--r--.clang-tidy23
-rw-r--r--.gitattributes39
-rw-r--r--.gitignore7
-rw-r--r--.hooks-config10
-rw-r--r--Auxiliary/vim/cmake.vim.in26
-rwxr-xr-xAuxiliary/vim/extract-upper-case.pl21
-rw-r--r--Auxiliary/vim/syntax/cmake.vim54
-rw-r--r--CMakeCPack.cmake18
-rw-r--r--CMakeCPackOptions.cmake.in6
-rw-r--r--CMakeLists.txt112
-rw-r--r--CONTRIBUTING.rst9
-rw-r--r--CTestCustom.cmake.in10
-rw-r--r--CompileFlags.cmake12
-rw-r--r--Copyright.txt2
-rw-r--r--Help/command/add_custom_command.rst10
-rw-r--r--Help/command/cmake_host_system_information.rst41
-rw-r--r--Help/command/cmake_parse_arguments.rst23
-rw-r--r--Help/command/configure_file.rst14
-rw-r--r--Help/command/execute_process.rst9
-rw-r--r--Help/command/file.rst20
-rw-r--r--Help/command/if.rst2
-rw-r--r--Help/command/include_guard.rst46
-rw-r--r--Help/command/string.rst11
-rw-r--r--Help/dev/maint.rst74
-rw-r--r--Help/dev/review.rst77
-rw-r--r--Help/dev/source.rst67
-rw-r--r--Help/envvar/ASM_DIALECT.rst11
-rw-r--r--Help/envvar/ASM_DIALECTFLAGS.rst11
-rw-r--r--Help/envvar/CC.rst9
-rw-r--r--Help/envvar/CFLAGS.rst9
-rw-r--r--Help/envvar/CMAKE_CONFIG_TYPE.rst5
-rw-r--r--Help/envvar/CMAKE_MSVCIDE_RUN_PATH.rst8
-rw-r--r--Help/envvar/CMAKE_OSX_ARCHITECTURES.rst8
-rw-r--r--Help/envvar/CSFLAGS.rst9
-rw-r--r--Help/envvar/CTEST_INTERACTIVE_DEBUG_MODE.rst5
-rw-r--r--Help/envvar/CTEST_OUTPUT_ON_FAILURE.rst7
-rw-r--r--Help/envvar/CTEST_PARALLEL_LEVEL.rst5
-rw-r--r--Help/envvar/CTEST_USE_LAUNCHERS_DEFAULT.rst4
-rw-r--r--Help/envvar/CUDACXX.rst9
-rw-r--r--Help/envvar/CUDAFLAGS.rst9
-rw-r--r--Help/envvar/CUDAHOSTCXX.rst9
-rw-r--r--Help/envvar/CXX.rst9
-rw-r--r--Help/envvar/CXXFLAGS.rst9
-rw-r--r--Help/envvar/DASHBOARD_TEST_FROM_CTEST.rst5
-rw-r--r--Help/envvar/FC.rst10
-rw-r--r--Help/envvar/FFLAGS.rst9
-rw-r--r--Help/envvar/LDFLAGS.rst10
-rw-r--r--Help/envvar/MACOSX_DEPLOYMENT_TARGET.rst8
-rw-r--r--Help/envvar/RC.rst9
-rw-r--r--Help/envvar/RCFLAGS.rst9
-rw-r--r--Help/generator/CodeBlocks.rst6
-rw-r--r--Help/index.rst1
-rw-r--r--Help/manual/cmake-buildsystem.7.rst6
-rw-r--r--Help/manual/cmake-commands.7.rst1
-rw-r--r--Help/manual/cmake-env-variables.7.rst54
-rw-r--r--Help/manual/cmake-language.7.rst18
-rw-r--r--Help/manual/cmake-modules.7.rst3
-rw-r--r--Help/manual/cmake-policies.7.rst9
-rw-r--r--Help/manual/cmake-properties.7.rst10
-rw-r--r--Help/manual/cmake-qt.7.rst35
-rw-r--r--Help/manual/cmake-server.7.rst57
-rw-r--r--Help/manual/cmake-variables.7.rst11
-rw-r--r--Help/manual/cmake.1.rst36
-rw-r--r--Help/manual/ctest.1.rst35
-rw-r--r--Help/module/CPackFreeBSD.rst1
-rw-r--r--Help/module/FindOpenACC.rst1
-rw-r--r--Help/module/FindPatch.rst1
-rw-r--r--Help/policy/CMP0040.rst2
-rw-r--r--Help/policy/CMP0070.rst25
-rw-r--r--Help/policy/CMP0071.rst42
-rw-r--r--Help/prop_dir/LABELS.rst13
-rw-r--r--Help/prop_dir/TEST_INCLUDE_FILE.rst4
-rw-r--r--Help/prop_dir/TEST_INCLUDE_FILES.rst7
-rw-r--r--Help/prop_sf/AUTORCC_OPTIONS.rst13
-rw-r--r--Help/prop_sf/AUTOUIC_OPTIONS.rst19
-rw-r--r--Help/prop_sf/SKIP_AUTOGEN.rst13
-rw-r--r--Help/prop_sf/SKIP_AUTOMOC.rst11
-rw-r--r--Help/prop_sf/SKIP_AUTORCC.rst11
-rw-r--r--Help/prop_sf/SKIP_AUTOUIC.rst16
-rw-r--r--Help/prop_sf/VS_SHADER_OUTPUT_HEADER_FILE.rst5
-rw-r--r--Help/prop_sf/VS_SHADER_VARIABLE_NAME.rst5
-rw-r--r--Help/prop_test/FIXTURES_CLEANUP.rst3
-rw-r--r--Help/prop_test/FIXTURES_REQUIRED.rst6
-rw-r--r--Help/prop_test/FIXTURES_SETUP.rst5
-rw-r--r--Help/prop_test/PROCESSORS.rst9
-rw-r--r--Help/prop_tgt/AUTOMOC.rst34
-rw-r--r--Help/prop_tgt/AUTOMOC_COMPILER_PREDEFINES.rst24
-rw-r--r--Help/prop_tgt/AUTOMOC_DEPEND_FILTERS.rst2
-rw-r--r--Help/prop_tgt/AUTOMOC_MACRO_NAMES.rst32
-rw-r--r--Help/prop_tgt/AUTORCC_OPTIONS.rst9
-rw-r--r--Help/prop_tgt/AUTOUIC.rst3
-rw-r--r--Help/prop_tgt/AUTOUIC_OPTIONS.rst9
-rw-r--r--Help/prop_tgt/CUDA_STANDARD.rst2
-rw-r--r--Help/prop_tgt/CXX_STANDARD.rst3
-rw-r--r--Help/prop_tgt/C_STANDARD.rst3
-rw-r--r--Help/prop_tgt/LANG_COMPILER_LAUNCHER.rst3
-rw-r--r--Help/prop_tgt/LANG_CPPCHECK.rst13
-rw-r--r--Help/prop_tgt/MACOSX_BUNDLE.rst2
-rw-r--r--Help/prop_tgt/NO_SYSTEM_FROM_IMPORTED.rst18
-rw-r--r--Help/prop_tgt/VS_DOTNET_REFERENCEPROP_refname_TAG_tagname.rst14
-rw-r--r--Help/release/3.10.rst257
-rw-r--r--Help/release/index.rst1
-rw-r--r--Help/variable/APPLE.rst5
-rw-r--r--Help/variable/CMAKE_AUTOMOC_COMPILER_PREDEFINES.rst8
-rw-r--r--Help/variable/CMAKE_AUTOMOC_MACRO_NAMES.rst20
-rw-r--r--Help/variable/CMAKE_AUTORCC_OPTIONS.rst11
-rw-r--r--Help/variable/CMAKE_AUTOUIC_OPTIONS.rst11
-rw-r--r--Help/variable/CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES.rst7
-rw-r--r--Help/variable/CMAKE_CUDA_HOST_COMPILER.rst7
-rw-r--r--Help/variable/CMAKE_DIRECTORY_LABELS.rst6
-rw-r--r--Help/variable/CMAKE_FIND_NO_INSTALL_PREFIX.rst24
-rw-r--r--Help/variable/CMAKE_LANG_COMPILER_ARCHITECTURE_ID.rst8
-rw-r--r--Help/variable/CMAKE_LANG_COMPILER_ID.rst2
-rw-r--r--Help/variable/CMAKE_LANG_COMPILER_LAUNCHER.rst2
-rw-r--r--Help/variable/CMAKE_LANG_COMPILER_PREDEFINES_COMMAND.rst8
-rw-r--r--Help/variable/CMAKE_LANG_COMPILER_VERSION_INTERNAL.rst8
-rw-r--r--Help/variable/CMAKE_LANG_CPPCHECK.rst6
-rw-r--r--Help/variable/CMAKE_MSVCIDE_RUN_PATH.rst10
-rw-r--r--Help/variable/CMAKE_SYSTEM_PREFIX_PATH.rst7
-rw-r--r--Help/variable/CTEST_LABELS_FOR_SUBPROJECTS.rst5
-rw-r--r--Help/variable/MSVC_VERSION.rst22
-rw-r--r--Help/variable/UNIX.rst8
-rw-r--r--Help/variable/WIN32.rst4
-rw-r--r--Modules/AutogenInfo.cmake.in14
-rw-r--r--Modules/CMakeASMCompiler.cmake.in3
-rw-r--r--Modules/CMakeCCompiler.cmake.in2
-rw-r--r--Modules/CMakeCCompilerId.c.in3
-rw-r--r--Modules/CMakeCSharpInformation.cmake2
-rw-r--r--Modules/CMakeCXXCompiler.cmake.in2
-rw-r--r--Modules/CMakeCXXCompilerId.cpp.in15
-rw-r--r--Modules/CMakeDetermineASMCompiler.cmake69
-rw-r--r--Modules/CMakeDetermineCCompiler.cmake8
-rw-r--r--Modules/CMakeDetermineCSharpCompiler.cmake2
-rw-r--r--Modules/CMakeDetermineCUDACompiler.cmake30
-rw-r--r--Modules/CMakeDetermineCXXCompiler.cmake11
-rw-r--r--Modules/CMakeDetermineCompilerId.cmake60
-rw-r--r--Modules/CMakeDetermineFortranCompiler.cmake13
-rw-r--r--Modules/CMakeFindDependencyMacro.cmake45
-rw-r--r--Modules/CMakeFortranCompiler.cmake.in1
-rw-r--r--Modules/CMakeFortranCompilerId.F.in7
-rw-r--r--Modules/CMakeGenericSystem.cmake4
-rw-r--r--Modules/CMakeGraphVizOptions.cmake17
-rw-r--r--Modules/CMakePlatformId.h.in22
-rw-r--r--Modules/CMakePushCheckState.cmake2
-rw-r--r--Modules/CMakeTestCCompiler.cmake5
-rw-r--r--Modules/CMakeTestCSharpCompiler.cmake5
-rw-r--r--Modules/CMakeTestCUDACompiler.cmake5
-rw-r--r--Modules/CMakeTestCXXCompiler.cmake5
-rw-r--r--Modules/CMakeTestFortranCompiler.cmake5
-rw-r--r--Modules/CMakeTestSwiftCompiler.cmake5
-rwxr-xr-xModules/CPack.STGZ_Header.sh.in2
-rw-r--r--Modules/CPack.cmake3
-rw-r--r--Modules/CPackComponent.cmake10
-rw-r--r--Modules/CPackDeb.cmake100
-rw-r--r--Modules/CPackFreeBSD.cmake246
-rw-r--r--Modules/CPackIFW.cmake53
-rw-r--r--Modules/CPackRPM.cmake37
-rw-r--r--Modules/CheckCCompilerFlag.cmake50
-rw-r--r--Modules/CheckCSourceCompiles.cmake84
-rw-r--r--Modules/CheckCSourceRuns.cmake83
-rw-r--r--Modules/CheckCXXCompilerFlag.cmake49
-rw-r--r--Modules/CheckCXXSourceCompiles.cmake83
-rw-r--r--Modules/CheckCXXSourceRuns.cmake83
-rw-r--r--Modules/CheckCXXSymbolExists.cmake2
-rw-r--r--Modules/CheckForPthreads.c40
-rw-r--r--Modules/CheckFortranCompilerFlag.cmake51
-rw-r--r--Modules/CheckFortranSourceCompiles.cmake94
-rw-r--r--Modules/CheckSymbolExists.cmake6
-rw-r--r--Modules/CheckTypeSize.c.in6
-rw-r--r--Modules/Compiler/Clang-C.cmake32
-rw-r--r--Modules/Compiler/Clang-CXX.cmake60
-rw-r--r--Modules/Compiler/Clang.cmake6
-rw-r--r--Modules/Compiler/Flang-FindBinUtils.cmake1
-rw-r--r--Modules/Compiler/Flang-Fortran.cmake10
-rw-r--r--Modules/Compiler/GNU-Fortran.cmake2
-rw-r--r--Modules/Compiler/GNU.cmake6
-rw-r--r--Modules/Compiler/IAR-ASM.cmake17
-rw-r--r--Modules/Compiler/IAR-C.cmake42
-rw-r--r--Modules/Compiler/IAR-CXX.cmake52
-rw-r--r--Modules/Compiler/IAR-DetermineCompiler.cmake21
-rw-r--r--Modules/Compiler/IAR-FindBinUtils.cmake54
-rw-r--r--Modules/Compiler/IAR.cmake87
-rw-r--r--Modules/Compiler/MSVC-CXX.cmake47
-rw-r--r--Modules/Compiler/NVIDIA-CUDA.cmake2
-rw-r--r--Modules/Compiler/PGI-Fortran.cmake1
-rw-r--r--Modules/Compiler/PGI.cmake12
-rw-r--r--Modules/CompilerId/Xcode-3.pbxproj.in1
-rw-r--r--Modules/DartConfiguration.tcl.in3
-rw-r--r--Modules/ExternalProject.cmake1224
-rw-r--r--Modules/FindBoost.cmake87
-rw-r--r--Modules/FindCUDA.cmake70
-rw-r--r--Modules/FindCUDA/run_nvcc.cmake11
-rw-r--r--Modules/FindCUDA/select_compute_arch.cmake12
-rw-r--r--Modules/FindCurses.cmake112
-rw-r--r--Modules/FindCygwin.cmake10
-rw-r--r--Modules/FindDoxygen.cmake6
-rw-r--r--Modules/FindEXPAT.cmake35
-rw-r--r--Modules/FindFreetype.cmake71
-rw-r--r--Modules/FindGTest.cmake143
-rw-r--r--Modules/FindGettext.cmake8
-rw-r--r--Modules/FindHDF5.cmake169
-rw-r--r--Modules/FindHTMLHelp.cmake28
-rw-r--r--Modules/FindICU.cmake92
-rw-r--r--Modules/FindIce.cmake332
-rw-r--r--Modules/FindJava.cmake67
-rw-r--r--Modules/FindLibXml2.cmake53
-rw-r--r--Modules/FindMFC.cmake11
-rw-r--r--Modules/FindMPI.cmake1730
-rw-r--r--Modules/FindMPI/fortranparam_mpi.f90.in4
-rw-r--r--Modules/FindMPI/libver_mpi.c19
-rw-r--r--Modules/FindMPI/libver_mpi.f90.in7
-rw-r--r--Modules/FindMPI/mpiver.f90.in10
-rw-r--r--Modules/FindMPI/test_mpi.c37
-rw-r--r--Modules/FindMPI/test_mpi.f90.in6
-rw-r--r--Modules/FindMatlab.cmake19
-rw-r--r--Modules/FindOpenACC.cmake257
-rw-r--r--Modules/FindOpenCL.cmake2
-rw-r--r--Modules/FindOpenGL.cmake376
-rw-r--r--Modules/FindOpenMP.cmake118
-rw-r--r--Modules/FindOpenSSL.cmake2
-rw-r--r--Modules/FindPackageHandleStandardArgs.cmake61
-rw-r--r--Modules/FindPatch.cmake68
-rw-r--r--Modules/FindPkgConfig.cmake7
-rw-r--r--Modules/FindProtobuf.cmake64
-rw-r--r--Modules/FindQt4.cmake14
-rw-r--r--Modules/FindThreads.cmake15
-rw-r--r--Modules/FindXCTest.cmake4
-rw-r--r--Modules/FindXMLRPC.cmake43
-rw-r--r--Modules/FindwxWidgets.cmake38
-rw-r--r--Modules/GNUInstallDirs.cmake5
-rw-r--r--Modules/GetPrerequisites.cmake1
-rw-r--r--Modules/GoogleTest.cmake216
-rw-r--r--Modules/GoogleTestAddTests.cmake100
-rw-r--r--Modules/InstallRequiredSystemLibraries.cmake142
-rw-r--r--Modules/Platform/FreeBSD-Determine-CXX.cmake3
-rw-r--r--Modules/Platform/GHS-MULTI-Initialize.cmake2
-rw-r--r--Modules/Platform/GNUtoMS_lib.bat.in1
-rw-r--r--Modules/Platform/Generic-SDCC-C.cmake2
-rw-r--r--Modules/Platform/Midipix.cmake1
-rw-r--r--Modules/Platform/Windows-Clang-CXX.cmake1
-rw-r--r--Modules/Platform/Windows-Clang.cmake1
-rw-r--r--Modules/Platform/Windows-MSVC.cmake16
-rw-r--r--Modules/Platform/Windows-NMcl.cmake4
-rwxr-xr-xModules/Squish4RunTestCase.bat48
-rw-r--r--Modules/UseSWIG.cmake11
-rw-r--r--README.rst4
-rw-r--r--Source/.gitattributes2
-rw-r--r--Source/CMakeLists.txt68
-rw-r--r--Source/CMakeVersion.cmake4
-rw-r--r--Source/CPack/IFW/cmCPackIFWCommon.cxx4
-rw-r--r--Source/CPack/IFW/cmCPackIFWGenerator.cxx100
-rw-r--r--Source/CPack/IFW/cmCPackIFWGenerator.h30
-rw-r--r--Source/CPack/IFW/cmCPackIFWInstaller.cxx16
-rw-r--r--Source/CPack/IFW/cmCPackIFWPackage.cxx136
-rw-r--r--Source/CPack/IFW/cmCPackIFWPackage.h6
-rw-r--r--Source/CPack/IFW/cmCPackIFWRepository.cxx27
-rw-r--r--Source/CPack/OSXScriptLauncher.cxx8
-rw-r--r--Source/CPack/WiX/cmCPackWIXGenerator.cxx51
-rw-r--r--Source/CPack/WiX/cmWIXAccessControlList.cxx8
-rw-r--r--Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx12
-rw-r--r--Source/CPack/WiX/cmWIXPatch.cxx23
-rw-r--r--Source/CPack/WiX/cmWIXPatchParser.cxx6
-rw-r--r--Source/CPack/WiX/cmWIXRichTextFormatWriter.h2
-rw-r--r--Source/CPack/WiX/cmWIXShortcut.cxx16
-rw-r--r--Source/CPack/WiX/cmWIXSourceWriter.cxx4
-rw-r--r--Source/CPack/cmCPack7zGenerator.h6
-rw-r--r--Source/CPack/cmCPackArchiveGenerator.cxx64
-rw-r--r--Source/CPack/cmCPackArchiveGenerator.h12
-rw-r--r--Source/CPack/cmCPackBundleGenerator.cxx9
-rw-r--r--Source/CPack/cmCPackBundleGenerator.h12
-rw-r--r--Source/CPack/cmCPackComponentGroup.cxx6
-rw-r--r--Source/CPack/cmCPackComponentGroup.h6
-rw-r--r--Source/CPack/cmCPackCygwinBinaryGenerator.h2
-rw-r--r--Source/CPack/cmCPackCygwinSourceGenerator.h2
-rw-r--r--Source/CPack/cmCPackDebGenerator.cxx397
-rw-r--r--Source/CPack/cmCPackDebGenerator.h14
-rw-r--r--Source/CPack/cmCPackDragNDropGenerator.cxx62
-rw-r--r--Source/CPack/cmCPackDragNDropGenerator.h20
-rw-r--r--Source/CPack/cmCPackFreeBSDGenerator.cxx359
-rw-r--r--Source/CPack/cmCPackFreeBSDGenerator.h37
-rw-r--r--Source/CPack/cmCPackGenerator.cxx168
-rw-r--r--Source/CPack/cmCPackGenerator.h6
-rw-r--r--Source/CPack/cmCPackGeneratorFactory.cxx24
-rw-r--r--Source/CPack/cmCPackLog.cxx9
-rw-r--r--Source/CPack/cmCPackNSISGenerator.cxx141
-rw-r--r--Source/CPack/cmCPackNSISGenerator.h20
-rw-r--r--Source/CPack/cmCPackOSXX11Generator.cxx10
-rw-r--r--Source/CPack/cmCPackOSXX11Generator.h12
-rw-r--r--Source/CPack/cmCPackPKGGenerator.cxx6
-rw-r--r--Source/CPack/cmCPackPKGGenerator.h10
-rw-r--r--Source/CPack/cmCPackPackageMakerGenerator.cxx15
-rw-r--r--Source/CPack/cmCPackPackageMakerGenerator.h12
-rw-r--r--Source/CPack/cmCPackProductBuildGenerator.cxx12
-rw-r--r--Source/CPack/cmCPackProductBuildGenerator.h10
-rw-r--r--Source/CPack/cmCPackRPMGenerator.cxx8
-rw-r--r--Source/CPack/cmCPackRPMGenerator.h14
-rw-r--r--Source/CPack/cmCPackSTGZGenerator.cxx6
-rw-r--r--Source/CPack/cmCPackSTGZGenerator.h12
-rw-r--r--Source/CPack/cmCPackTGZGenerator.h6
-rw-r--r--Source/CPack/cmCPackTXZGenerator.h6
-rw-r--r--Source/CPack/cmCPackTarBZip2Generator.h6
-rw-r--r--Source/CPack/cmCPackTarCompressGenerator.h6
-rw-r--r--Source/CPack/cmCPackZIPGenerator.h6
-rw-r--r--Source/CPack/cpack.cxx88
-rw-r--r--Source/CTest/cmCTestBZR.cxx46
-rw-r--r--Source/CTest/cmCTestBZR.h14
-rw-r--r--Source/CTest/cmCTestBatchTestHandler.cxx12
-rw-r--r--Source/CTest/cmCTestBatchTestHandler.h6
-rw-r--r--Source/CTest/cmCTestBuildAndTestHandler.cxx49
-rw-r--r--Source/CTest/cmCTestBuildAndTestHandler.h12
-rw-r--r--Source/CTest/cmCTestBuildCommand.cxx24
-rw-r--r--Source/CTest/cmCTestBuildCommand.h12
-rw-r--r--Source/CTest/cmCTestBuildHandler.cxx143
-rw-r--r--Source/CTest/cmCTestBuildHandler.h8
-rw-r--r--Source/CTest/cmCTestCVS.cxx32
-rw-r--r--Source/CTest/cmCTestCVS.h8
-rw-r--r--Source/CTest/cmCTestCommand.h4
-rw-r--r--Source/CTest/cmCTestConfigureCommand.cxx29
-rw-r--r--Source/CTest/cmCTestConfigureCommand.h8
-rw-r--r--Source/CTest/cmCTestConfigureHandler.cxx1
-rw-r--r--Source/CTest/cmCTestConfigureHandler.h6
-rw-r--r--Source/CTest/cmCTestCoverageCommand.cxx2
-rw-r--r--Source/CTest/cmCTestCoverageCommand.h12
-rw-r--r--Source/CTest/cmCTestCoverageHandler.cxx266
-rw-r--r--Source/CTest/cmCTestCoverageHandler.h12
-rw-r--r--Source/CTest/cmCTestCurl.cxx45
-rw-r--r--Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h6
-rw-r--r--Source/CTest/cmCTestGIT.cxx74
-rw-r--r--Source/CTest/cmCTestGIT.h14
-rw-r--r--Source/CTest/cmCTestGenericHandler.cxx11
-rw-r--r--Source/CTest/cmCTestGlobalVC.cxx19
-rw-r--r--Source/CTest/cmCTestGlobalVC.h6
-rw-r--r--Source/CTest/cmCTestHG.cxx55
-rw-r--r--Source/CTest/cmCTestHG.h14
-rw-r--r--Source/CTest/cmCTestHandlerCommand.cxx11
-rw-r--r--Source/CTest/cmCTestHandlerCommand.h4
-rw-r--r--Source/CTest/cmCTestLaunch.cxx48
-rw-r--r--Source/CTest/cmCTestMemCheckCommand.cxx2
-rw-r--r--Source/CTest/cmCTestMemCheckCommand.h8
-rw-r--r--Source/CTest/cmCTestMemCheckHandler.cxx109
-rw-r--r--Source/CTest/cmCTestMemCheckHandler.h15
-rw-r--r--Source/CTest/cmCTestMultiProcessHandler.cxx170
-rw-r--r--Source/CTest/cmCTestP4.cxx40
-rw-r--r--Source/CTest/cmCTestP4.h14
-rw-r--r--Source/CTest/cmCTestReadCustomFilesCommand.cxx5
-rw-r--r--Source/CTest/cmCTestReadCustomFilesCommand.h6
-rw-r--r--Source/CTest/cmCTestRunScriptCommand.h6
-rw-r--r--Source/CTest/cmCTestRunTest.cxx88
-rw-r--r--Source/CTest/cmCTestSVN.cxx49
-rw-r--r--Source/CTest/cmCTestSVN.h18
-rw-r--r--Source/CTest/cmCTestScriptHandler.cxx77
-rw-r--r--Source/CTest/cmCTestScriptHandler.h8
-rw-r--r--Source/CTest/cmCTestSleepCommand.h6
-rw-r--r--Source/CTest/cmCTestStartCommand.cxx6
-rw-r--r--Source/CTest/cmCTestStartCommand.h6
-rw-r--r--Source/CTest/cmCTestSubmitCommand.cxx4
-rw-r--r--Source/CTest/cmCTestSubmitCommand.h14
-rw-r--r--Source/CTest/cmCTestSubmitHandler.cxx162
-rw-r--r--Source/CTest/cmCTestSubmitHandler.h8
-rw-r--r--Source/CTest/cmCTestTestCommand.cxx8
-rw-r--r--Source/CTest/cmCTestTestCommand.h8
-rw-r--r--Source/CTest/cmCTestTestHandler.cxx626
-rw-r--r--Source/CTest/cmCTestTestHandler.h33
-rw-r--r--Source/CTest/cmCTestUpdateCommand.cxx4
-rw-r--r--Source/CTest/cmCTestUpdateCommand.h8
-rw-r--r--Source/CTest/cmCTestUpdateHandler.cxx23
-rw-r--r--Source/CTest/cmCTestUpdateHandler.h6
-rw-r--r--Source/CTest/cmCTestUploadCommand.cxx2
-rw-r--r--Source/CTest/cmCTestUploadCommand.h12
-rw-r--r--Source/CTest/cmCTestUploadHandler.cxx10
-rw-r--r--Source/CTest/cmCTestUploadHandler.h8
-rw-r--r--Source/CTest/cmCTestVC.cxx10
-rw-r--r--Source/CTest/cmCTestVC.h10
-rw-r--r--Source/CTest/cmParseBlanketJSCoverage.cxx8
-rw-r--r--Source/CTest/cmParseCacheCoverage.cxx12
-rw-r--r--Source/CTest/cmParseCacheCoverage.h4
-rw-r--r--Source/CTest/cmParseCoberturaCoverage.cxx25
-rw-r--r--Source/CTest/cmParseDelphiCoverage.cxx3
-rw-r--r--Source/CTest/cmParseGTMCoverage.cxx6
-rw-r--r--Source/CTest/cmParseGTMCoverage.h4
-rw-r--r--Source/CTest/cmParseJacocoCoverage.cxx23
-rw-r--r--Source/CTest/cmParseMumpsCoverage.cxx16
-rw-r--r--Source/CTest/cmProcess.cxx15
-rw-r--r--Source/CTest/cmProcess.h1
-rw-r--r--Source/Checks/cm_cxx_attribute_fallthrough.cxx2
-rw-r--r--Source/Checks/cm_cxx_auto_ptr.cxx18
-rw-r--r--Source/Checks/cm_cxx_eq_delete.cxx14
-rw-r--r--Source/Checks/cm_cxx_fallthrough.cxx2
-rw-r--r--Source/Checks/cm_cxx_features.cmake11
-rw-r--r--Source/Checks/cm_cxx_gnu_fallthrough.cxx2
-rw-r--r--Source/Checks/cm_cxx_nullptr.cxx14
-rw-r--r--Source/Checks/cm_cxx_override.cxx24
-rw-r--r--Source/Checks/cm_cxx_unordered_map.cxx7
-rw-r--r--Source/Checks/cm_cxx_unordered_set.cxx7
-rw-r--r--Source/CursesDialog/CMakeLists.txt4
-rw-r--r--Source/CursesDialog/ccmake.cxx28
-rw-r--r--Source/CursesDialog/cmCursesBoolWidget.h4
-rw-r--r--Source/CursesDialog/cmCursesCacheEntryComposite.cxx11
-rw-r--r--Source/CursesDialog/cmCursesCacheEntryComposite.h2
-rw-r--r--Source/CursesDialog/cmCursesDummyWidget.h4
-rw-r--r--Source/CursesDialog/cmCursesFilePathWidget.h2
-rw-r--r--Source/CursesDialog/cmCursesForm.cxx4
-rw-r--r--Source/CursesDialog/cmCursesForm.h2
-rw-r--r--Source/CursesDialog/cmCursesLabelWidget.h6
-rw-r--r--Source/CursesDialog/cmCursesLongMessageForm.cxx8
-rw-r--r--Source/CursesDialog/cmCursesLongMessageForm.h10
-rw-r--r--Source/CursesDialog/cmCursesMainForm.cxx87
-rw-r--r--Source/CursesDialog/cmCursesMainForm.h12
-rw-r--r--Source/CursesDialog/cmCursesOptionsWidget.cxx5
-rw-r--r--Source/CursesDialog/cmCursesOptionsWidget.h4
-rw-r--r--Source/CursesDialog/cmCursesPathWidget.h8
-rw-r--r--Source/CursesDialog/cmCursesStandardIncludes.h2
-rw-r--r--Source/CursesDialog/cmCursesStringWidget.cxx6
-rw-r--r--Source/CursesDialog/cmCursesStringWidget.h8
-rw-r--r--Source/CursesDialog/cmCursesWidget.cxx2
-rw-r--r--Source/CursesDialog/cmCursesWidget.h2
-rw-r--r--Source/CursesDialog/form/.gitattributes1
-rw-r--r--Source/CursesDialog/form/CMakeLists.txt17
-rw-r--r--Source/LexerParser/.gitattributes17
-rw-r--r--Source/LexerParser/cmCommandArgumentLexer.cxx671
-rw-r--r--Source/LexerParser/cmCommandArgumentLexer.h441
-rw-r--r--Source/LexerParser/cmCommandArgumentLexer.in.l11
-rw-r--r--Source/LexerParser/cmDependsJavaLexer.cxx767
-rw-r--r--Source/LexerParser/cmDependsJavaLexer.h441
-rw-r--r--Source/LexerParser/cmDependsJavaLexer.in.l11
-rw-r--r--Source/LexerParser/cmExprLexer.cxx670
-rw-r--r--Source/LexerParser/cmExprLexer.h441
-rw-r--r--Source/LexerParser/cmExprLexer.in.l11
-rw-r--r--Source/LexerParser/cmFortranLexer.cxx995
-rw-r--r--Source/LexerParser/cmFortranLexer.h441
-rw-r--r--Source/LexerParser/cmFortranLexer.in.l11
-rw-r--r--Source/LexerParser/cmListFileLexer.c887
-rw-r--r--Source/LexerParser/cmListFileLexer.in.l28
-rw-r--r--Source/QtDialog/CMakeLists.txt8
-rw-r--r--Source/QtDialog/CMakeSetup.cxx23
-rw-r--r--Source/QtDialog/CMakeSetupDialog.cxx6
-rw-r--r--Source/QtDialog/CMakeSetupDialog.h2
-rw-r--r--Source/QtDialog/Compilers.h4
-rw-r--r--Source/QtDialog/FirstConfigure.cxx2
-rw-r--r--Source/QtDialog/QCMake.h4
-rw-r--r--Source/QtDialog/QCMakeCacheView.cxx8
-rw-r--r--Source/QtDialog/QCMakeWidgets.cxx6
-rw-r--r--Source/QtDialog/QCMakeWidgets.h7
-rw-r--r--Source/bindexplib.cxx12
-rw-r--r--Source/bindexplib.h2
-rw-r--r--Source/cmAddCompileOptionsCommand.cxx5
-rw-r--r--Source/cmAddCompileOptionsCommand.h6
-rw-r--r--Source/cmAddCustomCommandCommand.cxx17
-rw-r--r--Source/cmAddCustomCommandCommand.h6
-rw-r--r--Source/cmAddCustomTargetCommand.cxx2
-rw-r--r--Source/cmAddCustomTargetCommand.h6
-rw-r--r--Source/cmAddDefinitionsCommand.cxx5
-rw-r--r--Source/cmAddDefinitionsCommand.h6
-rw-r--r--Source/cmAddDependenciesCommand.h6
-rw-r--r--Source/cmAddExecutableCommand.h6
-rw-r--r--Source/cmAddLibraryCommand.h6
-rw-r--r--Source/cmAddSubDirectoryCommand.h6
-rw-r--r--Source/cmAddTestCommand.h6
-rw-r--r--Source/cmAlgorithms.h24
-rw-r--r--Source/cmArchiveWrite.cxx6
-rw-r--r--Source/cmArchiveWrite.h4
-rw-r--r--Source/cmAuxSourceDirectoryCommand.h6
-rw-r--r--Source/cmBreakCommand.h6
-rw-r--r--Source/cmBuildCommand.h6
-rw-r--r--Source/cmBuildNameCommand.cxx2
-rw-r--r--Source/cmBuildNameCommand.h6
-rw-r--r--Source/cmCLocaleEnvironmentScope.cxx5
-rw-r--r--Source/cmCLocaleEnvironmentScope.h2
-rw-r--r--Source/cmCMakeHostSystemInformationCommand.cxx49
-rw-r--r--Source/cmCMakeHostSystemInformationCommand.h6
-rw-r--r--Source/cmCMakeMinimumRequired.cxx10
-rw-r--r--Source/cmCMakeMinimumRequired.h6
-rw-r--r--Source/cmCMakePolicyCommand.h6
-rw-r--r--Source/cmCPackPropertiesGenerator.cxx15
-rw-r--r--Source/cmCPackPropertiesGenerator.h4
-rw-r--r--Source/cmCPluginAPI.cxx66
-rw-r--r--Source/cmCTest.cxx253
-rw-r--r--Source/cmCTest.h23
-rw-r--r--Source/cmCacheManager.cxx37
-rw-r--r--Source/cmCacheManager.h7
-rw-r--r--Source/cmCallVisualStudioMacro.h2
-rw-r--r--Source/cmCommand.h4
-rw-r--r--Source/cmCommandArgumentParserHelper.cxx18
-rw-r--r--Source/cmCommandArgumentParserHelper.h2
-rw-r--r--Source/cmCommandArgumentsHelper.cxx74
-rw-r--r--Source/cmCommandArgumentsHelper.h28
-rw-r--r--Source/cmCommands.cxx34
-rw-r--r--Source/cmCommonTargetGenerator.cxx47
-rw-r--r--Source/cmCommonTargetGenerator.h4
-rw-r--r--Source/cmComputeComponentGraph.cxx10
-rw-r--r--Source/cmComputeLinkDepends.cxx97
-rw-r--r--Source/cmComputeLinkDepends.h2
-rw-r--r--Source/cmComputeLinkInformation.cxx131
-rw-r--r--Source/cmComputeLinkInformation.h4
-rw-r--r--Source/cmComputeTargetDepends.cxx103
-rw-r--r--Source/cmConditionEvaluator.cxx13
-rw-r--r--Source/cmConfigure.cmake.h.in32
-rw-r--r--Source/cmConfigureFileCommand.h6
-rw-r--r--Source/cmConnection.cxx168
-rw-r--r--Source/cmConnection.h134
-rw-r--r--Source/cmContinueCommand.h6
-rw-r--r--Source/cmCoreTryCompile.cxx60
-rw-r--r--Source/cmCreateTestSourceList.h6
-rw-r--r--Source/cmCryptoHash.cxx34
-rw-r--r--Source/cmCryptoHash.h7
-rw-r--r--Source/cmCurl.h4
-rw-r--r--Source/cmCustomCommand.cxx6
-rw-r--r--Source/cmCustomCommandGenerator.cxx69
-rw-r--r--Source/cmCustomCommandGenerator.h4
-rw-r--r--Source/cmDefinePropertyCommand.h6
-rw-r--r--Source/cmDefinitions.cxx30
-rw-r--r--Source/cmDefinitions.h4
-rw-r--r--Source/cmDepends.cxx20
-rw-r--r--Source/cmDepends.h4
-rw-r--r--Source/cmDependsC.cxx79
-rw-r--r--Source/cmDependsC.h6
-rw-r--r--Source/cmDependsFortran.cxx93
-rw-r--r--Source/cmDependsFortran.h8
-rw-r--r--Source/cmDependsJava.h8
-rw-r--r--Source/cmDependsJavaParserHelper.cxx56
-rw-r--r--Source/cmDisallowedCommand.h15
-rw-r--r--Source/cmDocumentation.cxx57
-rw-r--r--Source/cmDocumentation.h4
-rw-r--r--Source/cmDocumentationFormatter.cxx15
-rw-r--r--Source/cmDynamicLoader.cxx10
-rw-r--r--Source/cmDynamicLoader.h2
-rw-r--r--Source/cmELF.cxx59
-rw-r--r--Source/cmELF.h4
-rw-r--r--Source/cmEnableLanguageCommand.cxx7
-rw-r--r--Source/cmEnableLanguageCommand.h6
-rw-r--r--Source/cmEnableTestingCommand.h6
-rw-r--r--Source/cmExecProgramCommand.cxx22
-rw-r--r--Source/cmExecProgramCommand.h9
-rw-r--r--Source/cmExecuteProcessCommand.cxx71
-rw-r--r--Source/cmExecuteProcessCommand.h6
-rw-r--r--Source/cmExportBuildAndroidMKGenerator.cxx42
-rw-r--r--Source/cmExportBuildAndroidMKGenerator.h27
-rw-r--r--Source/cmExportBuildFileGenerator.cxx45
-rw-r--r--Source/cmExportBuildFileGenerator.h10
-rw-r--r--Source/cmExportCommand.cxx32
-rw-r--r--Source/cmExportCommand.h6
-rw-r--r--Source/cmExportFileGenerator.cxx123
-rw-r--r--Source/cmExportInstallAndroidMKGenerator.cxx5
-rw-r--r--Source/cmExportInstallAndroidMKGenerator.h41
-rw-r--r--Source/cmExportInstallFileGenerator.cxx55
-rw-r--r--Source/cmExportInstallFileGenerator.h12
-rw-r--r--Source/cmExportLibraryDependenciesCommand.cxx56
-rw-r--r--Source/cmExportLibraryDependenciesCommand.h10
-rw-r--r--Source/cmExportSet.cxx5
-rw-r--r--Source/cmExportTryCompileFileGenerator.cxx34
-rw-r--r--Source/cmExportTryCompileFileGenerator.h10
-rw-r--r--Source/cmExprParserHelper.cxx4
-rw-r--r--Source/cmExternalMakefileProjectGenerator.h2
-rw-r--r--Source/cmExtraCodeBlocksGenerator.cxx185
-rw-r--r--Source/cmExtraCodeBlocksGenerator.h4
-rw-r--r--Source/cmExtraCodeLiteGenerator.cxx102
-rw-r--r--Source/cmExtraCodeLiteGenerator.h4
-rw-r--r--Source/cmExtraEclipseCDT4Generator.cxx175
-rw-r--r--Source/cmExtraEclipseCDT4Generator.h8
-rw-r--r--Source/cmExtraKateGenerator.cxx56
-rw-r--r--Source/cmExtraKateGenerator.h4
-rw-r--r--Source/cmExtraSublimeTextGenerator.cxx62
-rw-r--r--Source/cmExtraSublimeTextGenerator.h6
-rw-r--r--Source/cmFLTKWrapUICommand.cxx4
-rw-r--r--Source/cmFLTKWrapUICommand.h10
-rw-r--r--Source/cmFileCommand.cxx214
-rw-r--r--Source/cmFileCommand.h6
-rw-r--r--Source/cmFileLock.cxx2
-rw-r--r--Source/cmFileLock.h2
-rw-r--r--Source/cmFileLockPool.cxx28
-rw-r--r--Source/cmFileLockPool.h2
-rw-r--r--Source/cmFileLockResult.cxx19
-rw-r--r--Source/cmFileMonitor.cxx37
-rw-r--r--Source/cmFileMonitor.h2
-rw-r--r--Source/cmFilePathChecksum.cxx51
-rw-r--r--Source/cmFilePathChecksum.h25
-rw-r--r--Source/cmFileTimeComparison.cxx29
-rw-r--r--Source/cmFindBase.cxx15
-rw-r--r--Source/cmFindCommon.cxx42
-rw-r--r--Source/cmFindCommon.h6
-rw-r--r--Source/cmFindFileCommand.h4
-rw-r--r--Source/cmFindLibraryCommand.cxx74
-rw-r--r--Source/cmFindLibraryCommand.h6
-rw-r--r--Source/cmFindPackageCommand.cxx176
-rw-r--r--Source/cmFindPackageCommand.h6
-rw-r--r--Source/cmFindPathCommand.cxx24
-rw-r--r--Source/cmFindPathCommand.h6
-rw-r--r--Source/cmFindProgramCommand.cxx44
-rw-r--r--Source/cmFindProgramCommand.h6
-rw-r--r--Source/cmForEachCommand.cxx13
-rw-r--r--Source/cmForEachCommand.h12
-rw-r--r--Source/cmFortranParser.h2
-rw-r--r--Source/cmFortranParserImpl.cxx14
-rw-r--r--Source/cmFunctionCommand.cxx12
-rw-r--r--Source/cmFunctionCommand.h12
-rw-r--r--Source/cmGeneratedFileStream.h4
-rw-r--r--Source/cmGeneratorExpression.cxx25
-rw-r--r--Source/cmGeneratorExpression.h23
-rw-r--r--Source/cmGeneratorExpressionContext.h2
-rw-r--r--Source/cmGeneratorExpressionDAGChecker.cxx2
-rw-r--r--Source/cmGeneratorExpressionDAGChecker.h6
-rw-r--r--Source/cmGeneratorExpressionEvaluationFile.cxx110
-rw-r--r--Source/cmGeneratorExpressionEvaluationFile.h21
-rw-r--r--Source/cmGeneratorExpressionEvaluator.cxx12
-rw-r--r--Source/cmGeneratorExpressionEvaluator.h18
-rw-r--r--Source/cmGeneratorExpressionNode.cxx494
-rw-r--r--Source/cmGeneratorExpressionParser.cxx2
-rw-r--r--Source/cmGeneratorTarget.cxx698
-rw-r--r--Source/cmGeneratorTarget.h13
-rw-r--r--Source/cmGetCMakePropertyCommand.cxx2
-rw-r--r--Source/cmGetCMakePropertyCommand.h6
-rw-r--r--Source/cmGetDirectoryPropertyCommand.cxx2
-rw-r--r--Source/cmGetDirectoryPropertyCommand.h6
-rw-r--r--Source/cmGetFilenameComponentCommand.cxx25
-rw-r--r--Source/cmGetFilenameComponentCommand.h6
-rw-r--r--Source/cmGetPropertyCommand.cxx8
-rw-r--r--Source/cmGetPropertyCommand.h6
-rw-r--r--Source/cmGetSourceFilePropertyCommand.cxx2
-rw-r--r--Source/cmGetSourceFilePropertyCommand.h6
-rw-r--r--Source/cmGetTargetPropertyCommand.cxx2
-rw-r--r--Source/cmGetTargetPropertyCommand.h6
-rw-r--r--Source/cmGetTestPropertyCommand.cxx2
-rw-r--r--Source/cmGetTestPropertyCommand.h6
-rw-r--r--Source/cmGhsMultiGpj.h2
-rw-r--r--Source/cmGhsMultiTargetGenerator.cxx6
-rw-r--r--Source/cmGlobalCommonGenerator.h4
-rw-r--r--Source/cmGlobalGenerator.cxx494
-rw-r--r--Source/cmGlobalGenerator.h49
-rw-r--r--Source/cmGlobalGeneratorFactory.h14
-rw-r--r--Source/cmGlobalGhsMultiGenerator.cxx6
-rw-r--r--Source/cmGlobalGhsMultiGenerator.h4
-rw-r--r--Source/cmGlobalKdevelopGenerator.cxx95
-rw-r--r--Source/cmGlobalKdevelopGenerator.h4
-rw-r--r--Source/cmGlobalNMakeMakefileGenerator.h2
-rw-r--r--Source/cmGlobalNinjaGenerator.cxx378
-rw-r--r--Source/cmGlobalNinjaGenerator.h70
-rw-r--r--Source/cmGlobalUnixMakefileGenerator3.cxx176
-rw-r--r--Source/cmGlobalUnixMakefileGenerator3.h54
-rw-r--r--Source/cmGlobalVisualStudio10Generator.cxx39
-rw-r--r--Source/cmGlobalVisualStudio10Generator.h2
-rw-r--r--Source/cmGlobalVisualStudio11Generator.cxx10
-rw-r--r--Source/cmGlobalVisualStudio11Generator.h2
-rw-r--r--Source/cmGlobalVisualStudio12Generator.cxx10
-rw-r--r--Source/cmGlobalVisualStudio12Generator.h4
-rw-r--r--Source/cmGlobalVisualStudio14Generator.cxx17
-rw-r--r--Source/cmGlobalVisualStudio14Generator.h2
-rw-r--r--Source/cmGlobalVisualStudio15Generator.cxx4
-rw-r--r--Source/cmGlobalVisualStudio15Generator.h8
-rw-r--r--Source/cmGlobalVisualStudio7Generator.cxx12
-rw-r--r--Source/cmGlobalVisualStudio7Generator.h4
-rw-r--r--Source/cmGlobalVisualStudio8Generator.cxx16
-rw-r--r--Source/cmGlobalVisualStudio9Generator.cxx10
-rw-r--r--Source/cmGlobalVisualStudioGenerator.cxx20
-rw-r--r--Source/cmGlobalVisualStudioGenerator.h4
-rw-r--r--Source/cmGlobalWatcomWMakeGenerator.h10
-rw-r--r--Source/cmGlobalXCodeGenerator.cxx529
-rw-r--r--Source/cmGlobalXCodeGenerator.h47
-rw-r--r--Source/cmGraphVizWriter.cxx229
-rw-r--r--Source/cmHexFileConverter.cxx13
-rw-r--r--Source/cmHexFileConverter.h2
-rw-r--r--Source/cmIDEOptions.h2
-rw-r--r--Source/cmIfCommand.cxx44
-rw-r--r--Source/cmIfCommand.h14
-rw-r--r--Source/cmIncludeCommand.cxx2
-rw-r--r--Source/cmIncludeCommand.h6
-rw-r--r--Source/cmIncludeDirectoryCommand.cxx2
-rw-r--r--Source/cmIncludeDirectoryCommand.h6
-rw-r--r--Source/cmIncludeExternalMSProjectCommand.cxx5
-rw-r--r--Source/cmIncludeExternalMSProjectCommand.h9
-rw-r--r--Source/cmIncludeGuardCommand.cxx108
-rw-r--r--Source/cmIncludeGuardCommand.h37
-rw-r--r--Source/cmIncludeRegularExpressionCommand.h9
-rw-r--r--Source/cmInstallCommand.cxx114
-rw-r--r--Source/cmInstallCommand.h6
-rw-r--r--Source/cmInstallCommandArguments.cxx38
-rw-r--r--Source/cmInstallDirectoryGenerator.cxx19
-rw-r--r--Source/cmInstallDirectoryGenerator.h10
-rw-r--r--Source/cmInstallExportAndroidMKGenerator.cxx8
-rw-r--r--Source/cmInstallExportGenerator.cxx33
-rw-r--r--Source/cmInstallExportGenerator.h12
-rw-r--r--Source/cmInstallFilesCommand.h10
-rw-r--r--Source/cmInstallFilesGenerator.cxx14
-rw-r--r--Source/cmInstallFilesGenerator.h10
-rw-r--r--Source/cmInstallGenerator.cxx9
-rw-r--r--Source/cmInstallGenerator.h12
-rw-r--r--Source/cmInstallProgramsCommand.h10
-rw-r--r--Source/cmInstallScriptGenerator.cxx2
-rw-r--r--Source/cmInstallScriptGenerator.h6
-rw-r--r--Source/cmInstallTargetGenerator.cxx43
-rw-r--r--Source/cmInstallTargetGenerator.h10
-rw-r--r--Source/cmInstallTargetsCommand.cxx2
-rw-r--r--Source/cmInstallTargetsCommand.h6
-rw-r--r--Source/cmInstalledFile.cxx13
-rw-r--r--Source/cmInstalledFile.h4
-rw-r--r--Source/cmLinkDirectoriesCommand.cxx5
-rw-r--r--Source/cmLinkDirectoriesCommand.h6
-rw-r--r--Source/cmLinkItem.h6
-rw-r--r--Source/cmLinkLibrariesCommand.h6
-rw-r--r--Source/cmLinkLineComputer.cxx28
-rw-r--r--Source/cmLinkLineComputer.h2
-rw-r--r--Source/cmLinkLineDeviceComputer.cxx18
-rw-r--r--Source/cmLinkLineDeviceComputer.h12
-rw-r--r--Source/cmLinkedTree.h4
-rw-r--r--Source/cmListCommand.cxx12
-rw-r--r--Source/cmListCommand.h6
-rw-r--r--Source/cmListFileCache.cxx9
-rw-r--r--Source/cmLoadCacheCommand.cxx25
-rw-r--r--Source/cmLoadCacheCommand.h6
-rw-r--r--Source/cmLoadCommandCommand.cxx40
-rw-r--r--Source/cmLoadCommandCommand.h6
-rw-r--r--Source/cmLocalCommonGenerator.cxx7
-rw-r--r--Source/cmLocalCommonGenerator.h6
-rw-r--r--Source/cmLocalGenerator.cxx364
-rw-r--r--Source/cmLocalGenerator.h15
-rw-r--r--Source/cmLocalGhsMultiGenerator.cxx4
-rw-r--r--Source/cmLocalNinjaGenerator.cxx48
-rw-r--r--Source/cmLocalNinjaGenerator.h18
-rw-r--r--Source/cmLocalUnixMakefileGenerator3.cxx260
-rw-r--r--Source/cmLocalUnixMakefileGenerator3.h32
-rw-r--r--Source/cmLocalVisualStudio10Generator.cxx11
-rw-r--r--Source/cmLocalVisualStudio10Generator.h2
-rw-r--r--Source/cmLocalVisualStudio7Generator.cxx39
-rw-r--r--Source/cmLocalVisualStudio7Generator.h2
-rw-r--r--Source/cmLocalVisualStudioGenerator.cxx16
-rw-r--r--Source/cmLocalVisualStudioGenerator.h10
-rw-r--r--Source/cmLocalXCodeGenerator.cxx22
-rw-r--r--Source/cmLocalXCodeGenerator.h16
-rw-r--r--Source/cmLocale.h4
-rw-r--r--Source/cmMSVC60LinkLineComputer.h5
-rw-r--r--Source/cmMachO.cxx13
-rw-r--r--Source/cmMachO.h2
-rw-r--r--Source/cmMacroCommand.cxx28
-rw-r--r--Source/cmMacroCommand.h12
-rw-r--r--Source/cmMakeDirectoryCommand.h6
-rw-r--r--Source/cmMakefile.cxx417
-rw-r--r--Source/cmMakefile.h110
-rw-r--r--Source/cmMakefileExecutableTargetGenerator.cxx38
-rw-r--r--Source/cmMakefileExecutableTargetGenerator.h6
-rw-r--r--Source/cmMakefileLibraryTargetGenerator.cxx58
-rw-r--r--Source/cmMakefileLibraryTargetGenerator.h6
-rw-r--r--Source/cmMakefileTargetGenerator.cxx250
-rw-r--r--Source/cmMakefileTargetGenerator.h10
-rw-r--r--Source/cmMakefileUtilityTargetGenerator.cxx2
-rw-r--r--Source/cmMakefileUtilityTargetGenerator.h6
-rw-r--r--Source/cmMarkAsAdvancedCommand.cxx2
-rw-r--r--Source/cmMarkAsAdvancedCommand.h6
-rw-r--r--Source/cmMathCommand.h6
-rw-r--r--Source/cmMessageCommand.h6
-rw-r--r--Source/cmNinjaLinkLineComputer.h5
-rw-r--r--Source/cmNinjaNormalTargetGenerator.cxx107
-rw-r--r--Source/cmNinjaNormalTargetGenerator.h6
-rw-r--r--Source/cmNinjaTargetGenerator.cxx129
-rw-r--r--Source/cmNinjaTargetGenerator.h10
-rw-r--r--Source/cmNinjaTypes.h2
-rw-r--r--Source/cmNinjaUtilityTargetGenerator.cxx19
-rw-r--r--Source/cmNinjaUtilityTargetGenerator.h6
-rw-r--r--Source/cmOSXBundleGenerator.cxx11
-rw-r--r--Source/cmOptionCommand.h6
-rw-r--r--Source/cmOrderDirectories.cxx63
-rw-r--r--Source/cmOrderDirectories.h4
-rw-r--r--Source/cmOutputConverter.cxx9
-rw-r--r--Source/cmOutputRequiredFilesCommand.cxx76
-rw-r--r--Source/cmOutputRequiredFilesCommand.h6
-rw-r--r--Source/cmParseArgumentsCommand.cxx88
-rw-r--r--Source/cmParseArgumentsCommand.h6
-rw-r--r--Source/cmPathLabel.cxx6
-rw-r--r--Source/cmPipeConnection.cxx82
-rw-r--r--Source/cmPipeConnection.h28
-rw-r--r--Source/cmPolicies.cxx20
-rw-r--r--Source/cmPolicies.h9
-rw-r--r--Source/cmProcessTools.cxx20
-rw-r--r--Source/cmProcessTools.h10
-rw-r--r--Source/cmProjectCommand.cxx9
-rw-r--r--Source/cmProjectCommand.h6
-rw-r--r--Source/cmProperty.cxx4
-rw-r--r--Source/cmPropertyMap.cxx8
-rw-r--r--Source/cmQTWrapCPPCommand.cxx2
-rw-r--r--Source/cmQTWrapCPPCommand.h6
-rw-r--r--Source/cmQTWrapUICommand.cxx4
-rw-r--r--Source/cmQTWrapUICommand.h6
-rw-r--r--Source/cmQtAutoGen.cxx374
-rw-r--r--Source/cmQtAutoGen.h72
-rw-r--r--Source/cmQtAutoGenDigest.h64
-rw-r--r--Source/cmQtAutoGeneratorCommon.cxx216
-rw-r--r--Source/cmQtAutoGeneratorCommon.h39
-rw-r--r--Source/cmQtAutoGeneratorInitializer.cxx1594
-rw-r--r--Source/cmQtAutoGeneratorInitializer.h14
-rw-r--r--Source/cmQtAutoGenerators.cxx2993
-rw-r--r--Source/cmQtAutoGenerators.h302
-rw-r--r--Source/cmRST.cxx14
-rw-r--r--Source/cmRemoveCommand.cxx8
-rw-r--r--Source/cmRemoveCommand.h6
-rw-r--r--Source/cmRemoveDefinitionsCommand.cxx5
-rw-r--r--Source/cmRemoveDefinitionsCommand.h6
-rw-r--r--Source/cmReturnCommand.h6
-rw-r--r--Source/cmScriptGenerator.cxx28
-rw-r--r--Source/cmScriptGenerator.h2
-rw-r--r--Source/cmSearchPath.cxx57
-rw-r--r--Source/cmSearchPath.h8
-rw-r--r--Source/cmSeparateArgumentsCommand.cxx24
-rw-r--r--Source/cmSeparateArgumentsCommand.h6
-rw-r--r--Source/cmServer.cxx287
-rw-r--r--Source/cmServer.h126
-rw-r--r--Source/cmServerConnection.cxx441
-rw-r--r--Source/cmServerConnection.h106
-rw-r--r--Source/cmServerDictionary.h5
-rw-r--r--Source/cmServerProtocol.cxx184
-rw-r--r--Source/cmServerProtocol.h9
-rw-r--r--Source/cmSetCommand.cxx6
-rw-r--r--Source/cmSetCommand.h6
-rw-r--r--Source/cmSetDirectoryPropertiesCommand.h9
-rw-r--r--Source/cmSetPropertyCommand.cxx47
-rw-r--r--Source/cmSetPropertyCommand.h6
-rw-r--r--Source/cmSetSourceFilesPropertiesCommand.h9
-rw-r--r--Source/cmSetTargetPropertiesCommand.h6
-rw-r--r--Source/cmSetTestsPropertiesCommand.h6
-rw-r--r--Source/cmSiteNameCommand.cxx4
-rw-r--r--Source/cmSiteNameCommand.h6
-rw-r--r--Source/cmSourceFile.cxx45
-rw-r--r--Source/cmSourceFile.h11
-rw-r--r--Source/cmSourceFileLocation.cxx19
-rw-r--r--Source/cmSourceFileLocation.h5
-rw-r--r--Source/cmSourceGroup.cxx6
-rw-r--r--Source/cmSourceGroup.h4
-rw-r--r--Source/cmSourceGroupCommand.cxx55
-rw-r--r--Source/cmSourceGroupCommand.h6
-rw-r--r--Source/cmState.cxx26
-rw-r--r--Source/cmStateDirectory.cxx17
-rw-r--r--Source/cmStateSnapshot.cxx2
-rw-r--r--Source/cmStateSnapshot.h2
-rw-r--r--Source/cmStringCommand.cxx45
-rw-r--r--Source/cmStringCommand.h7
-rw-r--r--Source/cmSubdirCommand.cxx19
-rw-r--r--Source/cmSubdirCommand.h6
-rw-r--r--Source/cmSubdirDependsCommand.h6
-rw-r--r--Source/cmSystemTools.cxx190
-rw-r--r--Source/cmSystemTools.h52
-rw-r--r--Source/cmTarget.cxx245
-rw-r--r--Source/cmTarget.h8
-rw-r--r--Source/cmTargetCompileDefinitionsCommand.cxx9
-rw-r--r--Source/cmTargetCompileDefinitionsCommand.h17
-rw-r--r--Source/cmTargetCompileFeaturesCommand.cxx5
-rw-r--r--Source/cmTargetCompileFeaturesCommand.h14
-rw-r--r--Source/cmTargetCompileOptionsCommand.h14
-rw-r--r--Source/cmTargetIncludeDirectoriesCommand.cxx22
-rw-r--r--Source/cmTargetIncludeDirectoriesCommand.h19
-rw-r--r--Source/cmTargetLinkLibrariesCommand.cxx15
-rw-r--r--Source/cmTargetLinkLibrariesCommand.h6
-rw-r--r--Source/cmTargetPropertyComputer.cxx15
-rw-r--r--Source/cmTargetPropertyComputer.h12
-rw-r--r--Source/cmTargetSourcesCommand.h14
-rw-r--r--Source/cmTestGenerator.cxx24
-rw-r--r--Source/cmTestGenerator.h14
-rw-r--r--Source/cmTimestamp.cxx9
-rw-r--r--Source/cmTryCompileCommand.h6
-rw-r--r--Source/cmTryRunCommand.cxx31
-rw-r--r--Source/cmTryRunCommand.h6
-rw-r--r--Source/cmUnexpectedCommand.h6
-rw-r--r--Source/cmUnsetCommand.cxx2
-rw-r--r--Source/cmUnsetCommand.h6
-rw-r--r--Source/cmUseMangledMesaCommand.cxx5
-rw-r--r--Source/cmUseMangledMesaCommand.h6
-rw-r--r--Source/cmUtilitySourceCommand.cxx4
-rw-r--r--Source/cmUtilitySourceCommand.h6
-rw-r--r--Source/cmVS10CLFlagTable.h3
-rw-r--r--Source/cmVS10CSharpFlagTable.h3
-rw-r--r--Source/cmVS10LinkFlagTable.h13
-rw-r--r--Source/cmVS11CLFlagTable.h3
-rw-r--r--Source/cmVS11CSharpFlagTable.h3
-rw-r--r--Source/cmVS11LinkFlagTable.h13
-rw-r--r--Source/cmVS12CLFlagTable.h3
-rw-r--r--Source/cmVS12CSharpFlagTable.h3
-rw-r--r--Source/cmVS12LinkFlagTable.h13
-rw-r--r--Source/cmVS140CLFlagTable.h3
-rw-r--r--Source/cmVS140CSharpFlagTable.h3
-rw-r--r--Source/cmVS140LinkFlagTable.h13
-rw-r--r--Source/cmVS141CLFlagTable.h4
-rw-r--r--Source/cmVS141CSharpFlagTable.h3
-rw-r--r--Source/cmVS141LinkFlagTable.h14
-rw-r--r--Source/cmVS14LibFlagTable.h1
-rw-r--r--Source/cmVSSetupHelper.cxx62
-rw-r--r--Source/cmVSSetupHelper.h5
-rw-r--r--Source/cmVariableRequiresCommand.h6
-rw-r--r--Source/cmVariableWatch.cxx40
-rw-r--r--Source/cmVariableWatch.h14
-rw-r--r--Source/cmVariableWatchCommand.cxx6
-rw-r--r--Source/cmVariableWatchCommand.h10
-rw-r--r--Source/cmVisualStudio10TargetGenerator.cxx557
-rw-r--r--Source/cmVisualStudio10TargetGenerator.h20
-rw-r--r--Source/cmVisualStudio10ToolsetOptions.h2
-rw-r--r--Source/cmVisualStudioGeneratorOptions.cxx70
-rw-r--r--Source/cmVisualStudioGeneratorOptions.h4
-rw-r--r--Source/cmVisualStudioSlnData.h2
-rw-r--r--Source/cmVisualStudioSlnParser.cxx2
-rw-r--r--Source/cmVisualStudioSlnParser.h2
-rw-r--r--Source/cmVisualStudioWCEPlatformParser.cxx8
-rw-r--r--Source/cmVisualStudioWCEPlatformParser.h2
-rw-r--r--Source/cmWhileCommand.cxx19
-rw-r--r--Source/cmWhileCommand.h14
-rw-r--r--Source/cmWriteFileCommand.h6
-rw-r--r--Source/cmXCode21Object.cxx8
-rw-r--r--Source/cmXCode21Object.h2
-rw-r--r--Source/cmXCodeObject.cxx23
-rw-r--r--Source/cmXCodeObject.h12
-rw-r--r--Source/cmXCodeScheme.cxx71
-rw-r--r--Source/cmXCodeScheme.h25
-rw-r--r--Source/cmXMLParser.cxx14
-rw-r--r--Source/cmXMLWriter.h4
-rw-r--r--Source/cm_auto_ptr.hxx220
-rw-r--r--Source/cm_codecvt.hxx14
-rw-r--r--Source/cm_sys_stat.h5
-rw-r--r--Source/cm_unordered_map.hxx25
-rw-r--r--Source/cm_unordered_set.hxx25
-rw-r--r--Source/cmake.cxx234
-rw-r--r--Source/cmake.h17
-rw-r--r--Source/cmakemain.cxx74
-rw-r--r--Source/cmakexbuild.cxx4
-rw-r--r--Source/cmcmd.cxx692
-rw-r--r--Source/cmcmd.h6
-rw-r--r--Source/ctest.cxx14
-rw-r--r--Source/kwsys/.gitattributes13
-rw-r--r--Source/kwsys/CMakeLists.txt160
-rw-r--r--Source/kwsys/Directory.cxx4
-rw-r--r--Source/kwsys/ProcessUNIX.c3
-rw-r--r--Source/kwsys/RegularExpression.cxx5
-rw-r--r--Source/kwsys/SystemTools.cxx184
-rw-r--r--Source/kwsys/SystemTools.hxx.in25
-rw-r--r--Source/kwsys/kwsysPlatformTestsCXX.cxx6
-rw-r--r--Source/kwsys/testDirectory.cxx79
-rw-r--r--Source/kwsys/testIOS.cxx139
-rw-r--r--Source/kwsys/testSystemTools.cxx32
-rw-r--r--Tests/AliasTarget/CMakeLists.txt7
-rw-r--r--Tests/CMakeLib/run_compile_commands.cxx14
-rw-r--r--Tests/CMakeLib/testUTF8.cxx5
-rw-r--r--Tests/CMakeLib/testVisualStudioSlnParser_data/.gitattributes1
-rw-r--r--Tests/CMakeLib/testXMLSafe.cxx4
-rw-r--r--Tests/CMakeLists.txt128
-rw-r--r--Tests/CMakeServerLib/CMakeLists.txt17
-rw-r--r--Tests/CMakeServerLib/testServerBuffering.cpp86
-rw-r--r--Tests/CMakeTests/.gitattributes1
-rw-r--r--Tests/CMakeTests/CMakeHostSystemInformationTest.cmake.in19
-rw-r--r--Tests/CMakeTests/PushCheckStateTest.cmake.in22
-rw-r--r--Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend1.cmake2
-rw-r--r--Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend2.cmake2
-rw-r--r--Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description1.cmake2
-rw-r--r--Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description2.cmake2
-rw-r--r--Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake2
-rw-r--r--Tests/CPackComponentsDEB/RunCPackVerifyResult-components-shlibdeps1.cmake2
-rw-r--r--Tests/CPackComponentsDEB/RunCPackVerifyResult-components-source.cmake2
-rw-r--r--Tests/CPackComponentsDEB/RunCPackVerifyResult-compression.cmake2
-rw-r--r--Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake2
-rw-r--r--Tests/CompileFeatures/.gitattributes2
-rw-r--r--Tests/CompileFeatures/CMakeLists.txt8
-rw-r--r--Tests/CompileFeatures/cxx_digit_separators.cpp3
-rw-r--r--Tests/CompileFeatures/cxx_raw_string_literals.cpp2
-rw-r--r--Tests/CompileFeatures/cxx_variadic_templates.cpp18
-rw-r--r--Tests/CompileFeatures/default_dialect.cpp23
-rw-r--r--Tests/CompileFeatures/genex_test.cpp12
-rw-r--r--Tests/Complex/CMakeLists.txt9
-rw-r--r--Tests/Complex/Executable/complex.cxx22
-rw-r--r--Tests/Complex/VarTests.cmake2
-rw-r--r--Tests/Complex/cmTestConfigure.h.in4
-rw-r--r--Tests/ComplexOneConfig/CMakeLists.txt9
-rw-r--r--Tests/ComplexOneConfig/Executable/complex.cxx22
-rw-r--r--Tests/ComplexOneConfig/VarTests.cmake2
-rw-r--r--Tests/ComplexOneConfig/cmTestConfigure.h.in4
-rw-r--r--Tests/Cuda/.clang-format9
-rw-r--r--Tests/Cuda/Complex/CMakeLists.txt5
-rw-r--r--Tests/Cuda/ObjectLibrary/CMakeLists.txt6
-rw-r--r--Tests/Cuda/WithC/CMakeLists.txt5
-rw-r--r--Tests/CudaOnly/.clang-format9
-rw-r--r--Tests/CudaOnly/ExportPTX/CMakeLists.txt5
-rw-r--r--Tests/CudaOnly/ResolveDeviceSymbols/CMakeLists.txt5
-rw-r--r--Tests/CudaOnly/SeparateCompilation/CMakeLists.txt7
-rw-r--r--Tests/CudaOnly/WithDefs/CMakeLists.txt13
-rw-r--r--Tests/FindEXPAT/CMakeLists.txt10
-rw-r--r--Tests/FindEXPAT/Test/CMakeLists.txt16
-rw-r--r--Tests/FindEXPAT/Test/main.c21
-rw-r--r--Tests/FindFreetype/CMakeLists.txt10
-rw-r--r--Tests/FindFreetype/Test/CMakeLists.txt16
-rw-r--r--Tests/FindFreetype/Test/main.c34
-rw-r--r--Tests/FindGTest/Test/main.cxx2
-rw-r--r--Tests/FindMPI/Test/CMakeLists.txt5
-rw-r--r--Tests/FindOpenGL/CMakeLists.txt7
-rw-r--r--Tests/FindOpenGL/Test/CMakeLists.txt58
-rw-r--r--Tests/FindPatch/CMakeLists.txt8
-rw-r--r--Tests/FindPatch/Test/CMakeLists.txt77
-rw-r--r--Tests/FindProtobuf/Test/CMakeLists.txt20
-rw-r--r--Tests/FindProtobuf/Test/main-desc.cxx57
-rw-r--r--Tests/FindProtobuf/Test/main-generate.cxx8
-rw-r--r--Tests/FindProtobuf/Test/msgs/example.proto6
-rw-r--r--Tests/FindProtobuf/Test/msgs/example_desc.proto10
-rw-r--r--Tests/GeneratorExpression/CMakeLists.txt4
-rw-r--r--Tests/GeneratorExpression/echo.c3
-rw-r--r--Tests/GeneratorExpression/srcgenex.c12
-rw-r--r--Tests/InterfaceLibrary/CMakeLists.txt1
-rw-r--r--Tests/LoadCommand/CMakeLists.txt7
-rw-r--r--Tests/LoadCommandOneConfig/CMakeLists.txt7
-rw-r--r--Tests/MFC/CMakeLists.txt.in5
-rw-r--r--Tests/MFC/mfc1/.gitattributes6
-rw-r--r--Tests/Module/CheckIPOSupported-C/CMakeLists.txt5
-rw-r--r--Tests/Module/CheckIPOSupported-CXX/CMakeLists.txt5
-rw-r--r--Tests/Module/CheckIPOSupported-Fortran/CMakeLists.txt5
-rw-r--r--Tests/Module/ExternalData/MD5/.gitattributes1
-rw-r--r--Tests/Module/ExternalData/SHA1/.gitattributes1
-rw-r--r--Tests/Module/ExternalData/SHA224/.gitattributes1
-rw-r--r--Tests/Module/ExternalData/SHA256/.gitattributes1
-rw-r--r--Tests/Module/ExternalData/SHA3_256/.gitattributes1
-rw-r--r--Tests/MumpsCoverage/.gitattributes2
-rw-r--r--Tests/MumpsCoverage/ZZCOVTST.cmcov2
-rw-r--r--Tests/Plugin/CMakeLists.txt7
-rw-r--r--Tests/PositionIndependentTargets/.gitattributes2
-rw-r--r--Tests/Qt4Targets/CMakeLists.txt10
-rw-r--r--Tests/QtAutoUicInterface/CMakeLists.txt5
-rw-r--r--Tests/QtAutogen/CMakeLists.txt330
-rw-r--r--Tests/QtAutogen/complex/CMakeLists.txt2
-rw-r--r--Tests/QtAutogen/mocCMP0071/CMakeLists.txt4
-rw-r--r--Tests/QtAutogen/mocCMP0071/NEW/CMakeLists.txt16
-rw-r--r--Tests/QtAutogen/mocCMP0071/OLD/CMakeLists.txt18
-rw-r--r--Tests/QtAutogen/mocCMP0071/Obj.cpp20
-rw-r--r--Tests/QtAutogen/mocCMP0071/Obj.hpp19
-rw-r--r--Tests/QtAutogen/mocCMP0071/Obj_p.h14
-rw-r--r--Tests/QtAutogen/mocCMP0071/main.cpp7
-rw-r--r--Tests/QtAutogen/mocDepends/CMakeLists.txt2
-rw-r--r--Tests/QtAutogen/mocInclude/EObjA.cpp43
-rw-r--r--Tests/QtAutogen/mocInclude/EObjA.hpp19
-rw-r--r--Tests/QtAutogen/mocInclude/EObjAExtra.cpp20
-rw-r--r--Tests/QtAutogen/mocInclude/EObjAExtra.hpp18
-rw-r--r--Tests/QtAutogen/mocInclude/EObjAExtra_p.hpp12
-rw-r--r--Tests/QtAutogen/mocInclude/EObjA_p.hpp12
-rw-r--r--Tests/QtAutogen/mocInclude/EObjB.cpp44
-rw-r--r--Tests/QtAutogen/mocInclude/EObjB.hpp19
-rw-r--r--Tests/QtAutogen/mocInclude/EObjB_p.hpp12
-rw-r--r--Tests/QtAutogen/mocInclude/LObjA.cpp39
-rw-r--r--Tests/QtAutogen/mocInclude/LObjA.hpp19
-rw-r--r--Tests/QtAutogen/mocInclude/LObjA_p.h12
-rw-r--r--Tests/QtAutogen/mocInclude/LObjB.cpp40
-rw-r--r--Tests/QtAutogen/mocInclude/LObjB.hpp19
-rw-r--r--Tests/QtAutogen/mocInclude/LObjB_p.h12
-rw-r--r--Tests/QtAutogen/mocInclude/ObjA.cpp24
-rw-r--r--Tests/QtAutogen/mocInclude/ObjA.hpp10
-rw-r--r--Tests/QtAutogen/mocInclude/ObjA_p.h12
-rw-r--r--Tests/QtAutogen/mocInclude/ObjB.cpp23
-rw-r--r--Tests/QtAutogen/mocInclude/ObjB.hpp14
-rw-r--r--Tests/QtAutogen/mocInclude/ObjB_p.h12
-rw-r--r--Tests/QtAutogen/mocInclude/ObjC.cpp26
-rw-r--r--Tests/QtAutogen/mocInclude/ObjC.hpp13
-rw-r--r--Tests/QtAutogen/mocInclude/ObjD.cpp26
-rw-r--r--Tests/QtAutogen/mocInclude/ObjD.hpp13
-rw-r--r--Tests/QtAutogen/mocInclude/SObjA.cpp11
-rw-r--r--Tests/QtAutogen/mocInclude/SObjA.hpp15
-rw-r--r--Tests/QtAutogen/mocInclude/SObjB.cpp.in11
-rw-r--r--Tests/QtAutogen/mocInclude/SObjB.hpp.in15
-rw-r--r--Tests/QtAutogen/mocInclude/SObjC.cpp35
-rw-r--r--Tests/QtAutogen/mocInclude/SObjC.hpp15
-rw-r--r--Tests/QtAutogen/mocInclude/SObjCExtra.cpp31
-rw-r--r--Tests/QtAutogen/mocInclude/SObjCExtra.hpp15
-rw-r--r--Tests/QtAutogen/mocInclude/SObjCExtra.moc.in4
-rw-r--r--Tests/QtAutogen/mocInclude/shared.cmake71
-rw-r--r--Tests/QtAutogen/mocInclude/subA/SubObjA.cpp27
-rw-r--r--Tests/QtAutogen/mocInclude/subA/SubObjA.hpp16
-rw-r--r--Tests/QtAutogen/mocInclude/subB/SubObjB.cpp27
-rw-r--r--Tests/QtAutogen/mocInclude/subB/SubObjB.hpp16
-rw-r--r--Tests/QtAutogen/mocInclude/subC/SubObjC.cpp27
-rw-r--r--Tests/QtAutogen/mocInclude/subC/SubObjC.hpp16
-rw-r--r--Tests/QtAutogen/mocInclude/subExtra/EObjBExtra.cpp20
-rw-r--r--Tests/QtAutogen/mocInclude/subExtra/EObjBExtra.hpp18
-rw-r--r--Tests/QtAutogen/mocInclude/subExtra/EObjBExtra_p.hpp12
-rw-r--r--Tests/QtAutogen/mocInclude/subGlobal/GObj.cpp41
-rw-r--r--Tests/QtAutogen/mocInclude/subGlobal/GObj.hpp17
-rw-r--r--Tests/QtAutogen/mocInclude/subGlobal/GObj_p.hpp15
-rw-r--r--Tests/QtAutogen/mocIncludeRelaxed/CMakeLists.txt23
-rw-r--r--Tests/QtAutogen/mocIncludeRelaxed/RMain.cpp12
-rw-r--r--Tests/QtAutogen/mocIncludeRelaxed/RObjA.cpp12
-rw-r--r--Tests/QtAutogen/mocIncludeRelaxed/RObjA.hpp14
-rw-r--r--Tests/QtAutogen/mocIncludeRelaxed/RObjB.cpp22
-rw-r--r--Tests/QtAutogen/mocIncludeRelaxed/RObjB.hpp14
-rw-r--r--Tests/QtAutogen/mocIncludeRelaxed/RObjBExtra.hpp14
-rw-r--r--Tests/QtAutogen/mocIncludeRelaxed/RObjC.cpp30
-rw-r--r--Tests/QtAutogen/mocIncludeRelaxed/RObjC.hpp14
-rw-r--r--Tests/QtAutogen/mocIncludeRelaxed/main.cpp18
-rw-r--r--Tests/QtAutogen/mocIncludeStrict/CMakeLists.txt16
-rw-r--r--Tests/QtAutogen/mocIncludeStrict/main.cpp18
-rw-r--r--Tests/QtAutogen/mocMacroName/CMakeLists.txt8
-rw-r--r--Tests/QtAutogen/mocMacroName/CustomMacros.hpp8
-rw-r--r--Tests/QtAutogen/mocMacroName/Gadget.cpp6
-rw-r--r--Tests/QtAutogen/mocMacroName/Gadget.hpp15
-rw-r--r--Tests/QtAutogen/mocMacroName/Object.cpp9
-rw-r--r--Tests/QtAutogen/mocMacroName/Object.hpp19
-rw-r--r--Tests/QtAutogen/mocMacroName/Object1Aliased.cpp9
-rw-r--r--Tests/QtAutogen/mocMacroName/Object1Aliased.hpp20
-rw-r--r--Tests/QtAutogen/mocMacroName/Object2Aliased.cpp9
-rw-r--r--Tests/QtAutogen/mocMacroName/Object2Aliased.hpp20
-rw-r--r--Tests/QtAutogen/mocMacroName/main.cpp13
-rw-r--r--Tests/QtAutogen/mocOnlySource/StyleA.cpp5
-rw-r--r--Tests/QtAutogen/mocOnlySource/StyleA.hpp15
-rw-r--r--Tests/QtAutogen/mocOnlySource/StyleB.cpp5
-rw-r--r--Tests/QtAutogen/mocOnlySource/StyleB.hpp16
-rw-r--r--Tests/QtAutogen/mocOnlySource/main.cpp9
-rw-r--r--Tests/QtAutogen/mocPlugin/StyleE.hpp17
-rw-r--r--Tests/QtAutogen/mocPlugin/jsonIn/StyleB.json1
-rw-r--r--Tests/QtAutogen/objectLibrary/CMakeLists.txt14
-rw-r--r--Tests/QtAutogen/objectLibrary/a/CMakeLists.txt2
-rw-r--r--Tests/QtAutogen/objectLibrary/a/classa.cpp7
-rw-r--r--Tests/QtAutogen/objectLibrary/a/classa.h23
-rw-r--r--Tests/QtAutogen/objectLibrary/b/classb.cpp7
-rw-r--r--Tests/QtAutogen/objectLibrary/b/classb.h23
-rw-r--r--Tests/QtAutogen/objectLibrary/main.cpp13
-rw-r--r--Tests/QtAutogen/rccDepends/CMakeLists.txt35
-rw-r--r--Tests/QtAutogen/rccDepends/res/input1.txt.in1
-rw-r--r--Tests/QtAutogen/rccDepends/res/input2.txt.in1
-rw-r--r--Tests/QtAutogen/rccDepends/res1a.qrc.in5
-rw-r--r--Tests/QtAutogen/rccDepends/res1b.qrc.in6
-rw-r--r--Tests/QtAutogen/rccDepends/res2a.qrc.in5
-rw-r--r--Tests/QtAutogen/rccDepends/res2b.qrc.in6
-rw-r--r--Tests/QtAutogen/sameName/CMakeLists.txt5
-rw-r--r--Tests/QtAutogen/sameName/aaa/bbb/item.cpp12
-rw-r--r--Tests/QtAutogen/sameName/aaa/item.cpp14
-rw-r--r--Tests/QtAutogen/sameName/aaa/item.hpp2
-rw-r--r--Tests/QtAutogen/sameName/aaa/view.ui24
-rw-r--r--Tests/QtAutogen/sameName/bbb/aaa/item.cpp12
-rw-r--r--Tests/QtAutogen/sameName/bbb/item.cpp15
-rw-r--r--Tests/QtAutogen/sameName/bbb/item.hpp1
-rw-r--r--Tests/QtAutogen/sameName/bbb/view.ui24
-rw-r--r--Tests/QtAutogen/sameName/ccc/item.cpp20
-rw-r--r--Tests/QtAutogen/sameName/ccc/item.hpp2
-rw-r--r--Tests/QtAutogen/sameName/ccc/view.ui24
-rw-r--r--Tests/QtAutogen/sameName/item.cpp15
-rw-r--r--Tests/QtAutogen/sameName/item.hpp2
-rw-r--r--Tests/QtAutogen/sameName/view.ui24
-rw-r--r--Tests/QtAutogen/skipMoc.cpp6
-rw-r--r--Tests/QtAutogen/skipSource/qItemC.cpp12
-rw-r--r--Tests/QtAutogen/skipSource/qItemD.cpp17
-rw-r--r--Tests/QtAutogen/skipSource/qItemD.hpp13
-rw-r--r--Tests/QtAutogen/staticLibraryCycle/CMakeLists.txt17
-rw-r--r--Tests/QtAutogen/staticLibraryCycle/a.cpp7
-rw-r--r--Tests/QtAutogen/staticLibraryCycle/a.h13
-rw-r--r--Tests/QtAutogen/staticLibraryCycle/b.cpp7
-rw-r--r--Tests/QtAutogen/staticLibraryCycle/b.h13
-rw-r--r--Tests/QtAutogen/staticLibraryCycle/c.cpp7
-rw-r--r--Tests/QtAutogen/staticLibraryCycle/c.h13
-rw-r--r--Tests/QtAutogen/staticLibraryCycle/main.cpp8
-rw-r--r--Tests/QtAutogenRerun/CMakeLists.txt52
-rw-r--r--Tests/QtAutogenRerun/defines_test/CMakeLists.txt4
-rw-r--r--Tests/QtAutogenRerun/defines_test/defines_test.cpp38
-rw-r--r--Tests/QtAutogenRerun/dummy.cpp5
-rw-r--r--Tests/QtAutogenRerun/mocPlugin.cmake96
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/CMakeLists.txt (renamed from Tests/QtAutogen/mocPlugin/CMakeLists.txt)6
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleA.cpp (renamed from Tests/QtAutogen/mocPlugin/StyleA.cpp)0
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleA.hpp (renamed from Tests/QtAutogen/mocPlugin/StyleA.hpp)4
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleA.json (renamed from Tests/QtAutogen/mocPlugin/StyleA.json)0
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleA_Custom.json (renamed from Tests/QtAutogen/mocPlugin/StyleA_Custom.json)0
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleB.cpp (renamed from Tests/QtAutogen/mocPlugin/StyleB.cpp)0
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleB.hpp (renamed from Tests/QtAutogen/mocPlugin/StyleB.hpp)4
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleC.cpp (renamed from Tests/QtAutogen/mocPlugin/StyleC.cpp)0
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleC.hpp (renamed from Tests/QtAutogen/mocPlugin/StyleC.hpp)2
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleD.cpp (renamed from Tests/QtAutogen/mocPlugin/StyleD.cpp)0
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleD.hpp (renamed from Tests/QtAutogen/mocPlugin/StyleD.hpp)2
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleE.cpp (renamed from Tests/QtAutogen/mocPlugin/StyleE.cpp)3
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleE.hpp10
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/StyleEInclude.hpp17
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/UtilityMacros.hpp (renamed from Tests/QtAutogen/mocPlugin/StyleCommon.hpp)4
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleB.json1
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleB_Custom.json (renamed from Tests/QtAutogen/mocPlugin/jsonIn/StyleB_Custom.json)0
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleC.json (renamed from Tests/QtAutogen/mocPlugin/jsonIn/StyleC.json)0
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleD.json (renamed from Tests/QtAutogen/mocPlugin/jsonIn/StyleD.json)0
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleE.json1
-rw-r--r--Tests/QtAutogenRerun/mocPlugin/main.cpp (renamed from Tests/QtAutogen/mocPlugin/main.cpp)0
-rw-r--r--Tests/QtAutogenRerun/mocRerun.cmake60
-rw-r--r--Tests/QtAutogenRerun/mocRerun/CMakeLists.txt (renamed from Tests/QtAutogen/mocRerun/CMakeLists.txt)14
-rw-r--r--Tests/QtAutogenRerun/mocRerun/input.txt (renamed from Tests/QtAutogen/mocRerun/input.txt)0
-rw-r--r--Tests/QtAutogenRerun/mocRerun/main.cpp.in (renamed from Tests/QtAutogen/mocRerun/main.cpp.in)0
-rw-r--r--Tests/QtAutogenRerun/mocRerun/res1.qrc (renamed from Tests/QtAutogen/mocRerun/res1.qrc)0
-rw-r--r--Tests/QtAutogenRerun/mocRerun/test1a.h.in (renamed from Tests/QtAutogen/mocRerun/test1a.h.in)0
-rw-r--r--Tests/QtAutogenRerun/mocRerun/test1b.h.in (renamed from Tests/QtAutogen/mocRerun/test1b.h.in)0
-rw-r--r--Tests/QtAutogenRerun/rccDepends.cmake131
-rw-r--r--Tests/QtAutogenRerun/rccDepends/CMakeLists.txt41
-rw-r--r--Tests/QtAutogenRerun/rccDepends/main.cpp (renamed from Tests/QtAutogen/rccDepends/main.cpp)0
-rw-r--r--Tests/QtAutogenRerun/rccDepends/resGen/input.txt.in1
-rw-r--r--Tests/QtAutogenRerun/rccDepends/resGen/inputAdded.txt.in1
-rw-r--r--Tests/QtAutogenRerun/rccDepends/resGenA.qrc.in5
-rw-r--r--Tests/QtAutogenRerun/rccDepends/resGenB.qrc.in6
-rw-r--r--Tests/QtAutogenRerun/rccDepends/resPlain/input.txt.in1
-rw-r--r--Tests/QtAutogenRerun/rccDepends/resPlain/inputAdded.txt.in1
-rw-r--r--Tests/QtAutogenRerun/rccDepends/resPlainA.qrc.in5
-rw-r--r--Tests/QtAutogenRerun/rccDepends/resPlainB.qrc.in6
-rw-r--r--Tests/README39
-rw-r--r--Tests/README.rst31
-rw-r--r--Tests/RunCMake/BuildDepends/C-Exe-Manifest.cmake2
-rw-r--r--Tests/RunCMake/BuildDepends/C-Exe.cmake2
-rw-r--r--Tests/RunCMake/BuildDepends/Custom-Always.cmake2
-rw-r--r--Tests/RunCMake/BuildDepends/Custom-Symbolic-and-Byproduct.cmake2
-rw-r--r--Tests/RunCMake/BuildDepends/MakeCustomIncludes.cmake2
-rw-r--r--Tests/RunCMake/BuildDepends/MakeInProjectOnly.cmake2
-rw-r--r--Tests/RunCMake/BuildDepends/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/CMP0040/CMP0040-WARN-missing-target-stderr.txt6
-rw-r--r--Tests/RunCMake/CMakeLists.txt71
-rw-r--r--Tests/RunCMake/CPack/CMakeLists.txt4
-rw-r--r--Tests/RunCMake/CPack/DEB/Helpers.cmake2
-rw-r--r--Tests/RunCMake/CPack/README.txt5
-rw-r--r--Tests/RunCMake/CPack/RPM/Helpers.cmake3
-rw-r--r--Tests/RunCMake/CPack/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/CPack/VerifyResult.cmake4
-rw-r--r--Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/ExpectedFiles.cmake3
-rw-r--r--Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/test.cmake11
-rw-r--r--Tests/RunCMake/CPack/tests/DEB_PACKAGE_VERSION_BACK_COMPATIBILITY/ExpectedFiles.cmake2
-rw-r--r--Tests/RunCMake/CPack/tests/DEB_PACKAGE_VERSION_BACK_COMPATIBILITY/VerifyResult.cmake11
-rw-r--r--Tests/RunCMake/CPack/tests/DEB_PACKAGE_VERSION_BACK_COMPATIBILITY/test.cmake7
-rw-r--r--Tests/RunCMake/CPack/tests/DIST/VerifyResult.cmake5
-rw-r--r--Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake5
-rw-r--r--Tests/RunCMake/CPack/tests/VERSION/ExpectedFiles.cmake3
-rw-r--r--Tests/RunCMake/CPack/tests/VERSION/VerifyResult.cmake17
-rw-r--r--Tests/RunCMake/CPack/tests/VERSION/test.cmake14
-rw-r--r--Tests/RunCMake/CPackInstallProperties/FilenameGenex.cmake2
-rw-r--r--Tests/RunCMake/CPackInstallProperties/PerConfigValue.cmake2
-rw-r--r--Tests/RunCMake/CPackInstallProperties/ValueGenex.cmake2
-rw-r--r--Tests/RunCMake/CSharpCustomCommand/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/CSharpCustomCommand/CommandWithOutput-check.cmake21
-rw-r--r--Tests/RunCMake/CSharpCustomCommand/CommandWithOutput.cmake13
-rw-r--r--Tests/RunCMake/CSharpCustomCommand/RunCMakeTest.cmake34
-rw-r--r--Tests/RunCMake/CSharpCustomCommand/dummy.cs0
-rw-r--r--Tests/RunCMake/CSharpCustomCommand/test.cs.in8
-rw-r--r--Tests/RunCMake/CTestCommandLine/LabelCount-stdout.txt4
-rw-r--r--Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-result.txt (renamed from Tests/RunCMake/CommandLine/E___run_iwyu-bad-iwyu-result.txt)0
-rw-r--r--Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-stderr.txt (renamed from Tests/RunCMake/CommandLine/E___run_iwyu-bad-iwyu-stderr.txt)0
-rw-r--r--Tests/RunCMake/CommandLine/E___run_co_compile-no----result.txt (renamed from Tests/RunCMake/CommandLine/E___run_iwyu-no----result.txt)0
-rw-r--r--Tests/RunCMake/CommandLine/E___run_co_compile-no----stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-result.txt (renamed from Tests/RunCMake/CommandLine/E___run_iwyu-no-cc-result.txt)0
-rw-r--r--Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-result.txt (renamed from Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-result.txt)0
-rw-r--r--Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-stderr.txt6
-rw-r--r--Tests/RunCMake/CommandLine/E___run_iwyu-no----stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E___run_iwyu-no-cc-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_md5sum-dir-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_md5sum-dir-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_md5sum-mixed-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_md5sum-mixed-stderr.txt2
-rw-r--r--Tests/RunCMake/CommandLine/E_md5sum-mixed-stdout.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_md5sum-no-file-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_md5sum-no-file-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_md5sum-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_md5sum-stdout.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha1sum-dir-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha1sum-dir-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha1sum-no-file-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha1sum-no-file-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha1sum-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha1sum-stdout.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha224sum-dir-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha224sum-dir-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha224sum-no-file-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha224sum-no-file-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha224sum-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha224sum-stdout.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha256sum-dir-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha256sum-dir-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha256sum-no-file-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha256sum-no-file-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha256sum-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha256sum-stdout.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha384sum-dir-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha384sum-dir-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha384sum-no-file-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha384sum-no-file-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha384sum-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha384sum-stdout.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha512sum-dir-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha512sum-dir-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha512sum-no-file-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha512sum-no-file-stderr.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha512sum-result.txt1
-rw-r--r--Tests/RunCMake/CommandLine/E_sha512sum-stdout.txt1
-rw-r--r--Tests/RunCMake/CommandLine/RunCMakeTest.cmake32
-rw-r--r--Tests/RunCMake/CommandLine/cmake_depends/.gitattributes2
-rw-r--r--Tests/RunCMake/CompilerLauncher/CUDA-Build-stdout.txt1
-rw-r--r--Tests/RunCMake/CompilerLauncher/CUDA-launch-Build-stdout.txt1
-rw-r--r--Tests/RunCMake/CompilerLauncher/CUDA-launch.cmake3
-rw-r--r--Tests/RunCMake/CompilerLauncher/CUDA.cmake4
-rw-r--r--Tests/RunCMake/CompilerLauncher/RunCMakeTest.cmake15
-rw-r--r--Tests/RunCMake/CompilerLauncher/main.cu4
-rw-r--r--Tests/RunCMake/Cppcheck/C-Build-stdout.txt1
-rw-r--r--Tests/RunCMake/Cppcheck/C-bad-Build-result.txt1
-rw-r--r--Tests/RunCMake/Cppcheck/C-bad-Build-stdout.txt2
-rw-r--r--Tests/RunCMake/Cppcheck/C-bad.cmake3
-rw-r--r--Tests/RunCMake/Cppcheck/C-launch-Build-stdout.txt1
-rw-r--r--Tests/RunCMake/Cppcheck/C-launch.cmake3
-rw-r--r--Tests/RunCMake/Cppcheck/C.cmake4
-rw-r--r--Tests/RunCMake/Cppcheck/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/Cppcheck/CXX-Build-stdout.txt1
-rw-r--r--Tests/RunCMake/Cppcheck/CXX-launch-Build-stdout.txt1
-rw-r--r--Tests/RunCMake/Cppcheck/CXX-launch.cmake3
-rw-r--r--Tests/RunCMake/Cppcheck/CXX.cmake3
-rw-r--r--Tests/RunCMake/Cppcheck/RunCMakeTest.cmake23
-rw-r--r--Tests/RunCMake/Cppcheck/main.c4
-rw-r--r--Tests/RunCMake/Cppcheck/main.cxx4
-rw-r--r--Tests/RunCMake/ExternalProject/MultiCommand-build-stdout.txt15
-rw-r--r--Tests/RunCMake/ExternalProject/MultiCommand.cmake30
-rw-r--r--Tests/RunCMake/ExternalProject/NoOptions-stderr.txt4
-rw-r--r--Tests/RunCMake/ExternalProject/RunCMakeTest.cmake10
-rw-r--r--Tests/RunCMake/ExternalProject/SourceEmpty-stderr.txt4
-rw-r--r--Tests/RunCMake/ExternalProject/SourceMissing-stderr.txt4
-rw-r--r--Tests/RunCMake/FPHSA/FindPseudoNoVersionVar.cmake6
-rw-r--r--Tests/RunCMake/FPHSA/RunCMakeTest.cmake13
-rw-r--r--Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable-stdout.txt2
-rw-r--r--Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable.cmake1
-rw-r--r--Tests/RunCMake/FPHSA/any_version_find_0-stdout.txt2
-rw-r--r--Tests/RunCMake/FPHSA/any_version_find_0.cmake1
-rw-r--r--Tests/RunCMake/File_Generate/CMP0070-NEW-check.cmake13
-rw-r--r--Tests/RunCMake/File_Generate/CMP0070-NEW.cmake2
-rw-r--r--Tests/RunCMake/File_Generate/CMP0070-OLD-check.cmake13
-rw-r--r--Tests/RunCMake/File_Generate/CMP0070-OLD.cmake3
-rw-r--r--Tests/RunCMake/File_Generate/CMP0070-WARN-check.cmake13
-rw-r--r--Tests/RunCMake/File_Generate/CMP0070-WARN-stderr.txt27
-rw-r--r--Tests/RunCMake/File_Generate/CMP0070-WARN.cmake2
-rw-r--r--Tests/RunCMake/File_Generate/COMPILE_LANGUAGE-genex.cmake2
-rw-r--r--Tests/RunCMake/File_Generate/ReRunCMake.cmake2
-rw-r--r--Tests/RunCMake/File_Generate/RunCMakeTest.cmake4
-rw-r--r--Tests/RunCMake/File_Generate/WriteIfDifferent.cmake2
-rw-r--r--Tests/RunCMake/File_Generate/relative-input-NEW.txt1
-rw-r--r--Tests/RunCMake/FindBoost/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage-stdout.txt3
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage.cmake2
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage/BoostConfig.cmake0
-rw-r--r--Tests/RunCMake/FindBoost/CMakePackage/BoostConfigVersion.cmake7
-rw-r--r--Tests/RunCMake/FindBoost/RunCMakeTest.cmake3
-rwxr-xr-xTests/RunCMake/FindPkgConfig/dummy-pkg-config.bat54
-rw-r--r--Tests/RunCMake/Framework/FrameworkLayout.cmake2
-rw-r--r--Tests/RunCMake/Framework/FrameworkTypeSTATIC-build-stdout.txt4
-rw-r--r--Tests/RunCMake/Framework/ios.cmake12
-rw-r--r--Tests/RunCMake/GenerateExportHeader/GEH.cmake7
-rw-r--r--Tests/RunCMake/GenerateExportHeader/reference/.gitattributes2
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_custom_command-stderr.txt4
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_custom_target-stderr.txt4
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_executable-stderr.txt4
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_library-stderr.txt4
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_test-stderr.txt4
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-install-stderr.txt4
-rw-r--r--Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-target_sources-stderr.txt4
-rw-r--r--Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-SOURCES.cmake4
-rw-r--r--Tests/RunCMake/GetPrerequisites/RunCMakeTest.cmake3
-rw-r--r--Tests/RunCMake/GetPrerequisites/TargetMissing-stderr.txt3
-rw-r--r--Tests/RunCMake/GetPrerequisites/TargetMissing.cmake4
-rw-r--r--Tests/RunCMake/GoogleTest/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest-test-stdout.txt25
-rw-r--r--Tests/RunCMake/GoogleTest/GoogleTest.cmake15
-rw-r--r--Tests/RunCMake/GoogleTest/RunCMakeTest.cmake26
-rw-r--r--Tests/RunCMake/GoogleTest/fake_gtest.cpp41
-rw-r--r--Tests/RunCMake/MultiLint/C-Build-stdout.txt8
-rw-r--r--Tests/RunCMake/MultiLint/C-launch-Build-stdout.txt8
-rw-r--r--Tests/RunCMake/MultiLint/C-launch.cmake3
-rw-r--r--Tests/RunCMake/MultiLint/C.cmake6
-rw-r--r--Tests/RunCMake/MultiLint/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/MultiLint/CXX-Build-stdout.txt8
-rw-r--r--Tests/RunCMake/MultiLint/CXX-launch-Build-stdout.txt8
-rw-r--r--Tests/RunCMake/MultiLint/CXX-launch.cmake3
-rw-r--r--Tests/RunCMake/MultiLint/CXX.cmake6
-rw-r--r--Tests/RunCMake/MultiLint/RunCMakeTest.cmake27
-rw-r--r--Tests/RunCMake/MultiLint/main.c4
-rw-r--r--Tests/RunCMake/MultiLint/main.cxx4
-rw-r--r--Tests/RunCMake/README.rst4
-rw-r--r--Tests/RunCMake/Syntax/.gitattributes3
-rw-r--r--Tests/RunCMake/Syntax/NullTerminatedArgument-result.txt1
-rw-r--r--Tests/RunCMake/Syntax/NullTerminatedArgument-stderr.txt5
-rw-r--r--Tests/RunCMake/Syntax/NullTerminatedArgument.cmakebin0 -> 106 bytes
-rw-r--r--Tests/RunCMake/Syntax/RunCMakeTest.cmake1
-rw-r--r--Tests/RunCMake/TargetObjects/NoTarget.cmake4
-rw-r--r--Tests/RunCMake/TargetObjects/NotObjlibTarget.cmake2
-rw-r--r--Tests/RunCMake/VS10Project/RunCMakeTest.cmake1
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpCustomTags-check.cmake31
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpCustomTags.cmake26
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpReferenceProps-check.cmake49
-rw-r--r--Tests/RunCMake/VS10Project/VsCSharpReferenceProps.cmake19
-rw-r--r--Tests/RunCMake/XcodeProject/RunCMakeTest.cmake21
-rw-r--r--Tests/RunCMake/add_custom_command/RemoveEmptyCommands-check.cmake63
-rw-r--r--Tests/RunCMake/add_custom_command/RemoveEmptyCommands.cmake22
-rw-r--r--Tests/RunCMake/add_custom_command/RunCMakeTest.cmake4
-rw-r--r--Tests/RunCMake/add_executable/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/add_executable/NoSources-result.txt1
-rw-r--r--Tests/RunCMake/add_executable/NoSources-stderr.txt4
-rw-r--r--Tests/RunCMake/add_executable/NoSources.cmake1
-rw-r--r--Tests/RunCMake/add_executable/NoSourcesButLinkObjects-result.txt1
-rw-r--r--Tests/RunCMake/add_executable/NoSourcesButLinkObjects-stderr.txt11
-rw-r--r--Tests/RunCMake/add_executable/NoSourcesButLinkObjects.cmake5
-rw-r--r--Tests/RunCMake/add_executable/OnlyObjectSources-result.txt1
-rw-r--r--Tests/RunCMake/add_executable/OnlyObjectSources-stderr.txt11
-rw-r--r--Tests/RunCMake/add_executable/OnlyObjectSources.cmake5
-rw-r--r--Tests/RunCMake/add_executable/RunCMakeTest.cmake5
-rw-r--r--Tests/RunCMake/add_executable/test.cpp0
-rw-r--r--Tests/RunCMake/add_library/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/add_library/INTERFACEwithNoSources.cmake1
-rw-r--r--Tests/RunCMake/add_library/INTERFACEwithNoSourcesButLinkObjects.cmake5
-rw-r--r--Tests/RunCMake/add_library/INTERFACEwithOnlyObjectSources.cmake5
-rw-r--r--Tests/RunCMake/add_library/MODULEwithNoSources-result.txt1
-rw-r--r--Tests/RunCMake/add_library/MODULEwithNoSources-stderr.txt3
-rw-r--r--Tests/RunCMake/add_library/MODULEwithNoSources.cmake1
-rw-r--r--Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-result.txt1
-rw-r--r--Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-stderr.txt3
-rw-r--r--Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects.cmake5
-rw-r--r--Tests/RunCMake/add_library/MODULEwithOnlyObjectSources-stderr.txt1
-rw-r--r--Tests/RunCMake/add_library/MODULEwithOnlyObjectSources.cmake5
-rw-r--r--Tests/RunCMake/add_library/OBJECTwithNoSources-result.txt1
-rw-r--r--Tests/RunCMake/add_library/OBJECTwithNoSources-stderr.txt2
-rw-r--r--Tests/RunCMake/add_library/OBJECTwithNoSources.cmake1
-rw-r--r--Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-result.txt1
-rw-r--r--Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-stderr.txt6
-rw-r--r--Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects.cmake5
-rw-r--r--Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-result.txt1
-rw-r--r--Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-stderr.txt17
-rw-r--r--Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources.cmake5
-rw-r--r--Tests/RunCMake/add_library/RunCMakeTest.cmake24
-rw-r--r--Tests/RunCMake/add_library/SHAREDwithNoSources-result.txt1
-rw-r--r--Tests/RunCMake/add_library/SHAREDwithNoSources-stderr.txt3
-rw-r--r--Tests/RunCMake/add_library/SHAREDwithNoSources.cmake1
-rw-r--r--Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-result.txt1
-rw-r--r--Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-stderr.txt3
-rw-r--r--Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects.cmake5
-rw-r--r--Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources-stderr.txt1
-rw-r--r--Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources.cmake5
-rw-r--r--Tests/RunCMake/add_library/STATICwithNoSources-result.txt1
-rw-r--r--Tests/RunCMake/add_library/STATICwithNoSources-stderr.txt3
-rw-r--r--Tests/RunCMake/add_library/STATICwithNoSources.cmake1
-rw-r--r--Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-result.txt1
-rw-r--r--Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-stderr.txt3
-rw-r--r--Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects.cmake5
-rw-r--r--Tests/RunCMake/add_library/STATICwithOnlyObjectSources-stderr.txt1
-rw-r--r--Tests/RunCMake/add_library/STATICwithOnlyObjectSources.cmake5
-rw-r--r--Tests/RunCMake/add_library/UNKNOWNwithNoSources.cmake1
-rw-r--r--Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-result.txt1
-rw-r--r--Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-stderr.txt5
-rw-r--r--Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects.cmake5
-rw-r--r--Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-result.txt1
-rw-r--r--Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-stderr.txt4
-rw-r--r--Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources.cmake5
-rw-r--r--Tests/RunCMake/add_library/test.cpp0
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/CMakeLists.txt.in5
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/CTestConfig.cmake.in2
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/CTestConfigCTestScript-check.cmake36
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/CTestConfigCTestScript-stdout.txt10
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariable-check.cmake36
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariable-stdout.txt10
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-check.cmake34
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-result.txt1
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-stderr.txt1
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-stdout.txt9
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-result.txt1
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-stderr.txt1
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-stdout.txt6
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-result.txt1
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-stderr.txt1
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-stdout.txt9
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-result.txt1
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-stderr.txt1
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-stdout.txt6
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-result.txt1
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-stderr.txt1
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-stdout.txt6
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/MyExperimentalFeature/CMakeLists.txt33
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/MyExperimentalFeature/experimental.c16
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/MyProductionCode/CMakeLists.txt12
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/MyProductionCode/production.c16
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/MyThirdPartyDependency/CMakeLists.txt7
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/MyThirdPartyDependency/src/CMakeLists.txt10
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/MyThirdPartyDependency/src/thirdparty.c14
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/RunCMakeTest.cmake185
-rw-r--r--Tests/RunCMake/ctest_labels_for_subprojects/test.cmake.in21
-rwxr-xr-xTests/RunCMake/ctest_skipped_test/skip.bat2
-rw-r--r--Tests/RunCMake/execute_process/ExitValues-stdout.txt14
-rw-r--r--Tests/RunCMake/execute_process/ExitValues.cmake120
-rw-r--r--Tests/RunCMake/execute_process/RunCMakeTest.cmake4
-rw-r--r--Tests/RunCMake/exit_code.c30
-rw-r--r--Tests/RunCMake/get_filename_component/KnownComponents.cmake11
-rw-r--r--Tests/RunCMake/get_property/source_properties-stderr.txt8
-rw-r--r--Tests/RunCMake/get_property/source_properties.cmake10
-rw-r--r--Tests/RunCMake/include_guard/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/include_guard/DirectoryScope.cmake19
-rw-r--r--Tests/RunCMake/include_guard/GlobalScope.cmake11
-rw-r--r--Tests/RunCMake/include_guard/InvalidArgumentsNumber-result.txt1
-rw-r--r--Tests/RunCMake/include_guard/InvalidArgumentsNumber-stderr.txt5
-rw-r--r--Tests/RunCMake/include_guard/InvalidArgumentsNumber.cmake1
-rw-r--r--Tests/RunCMake/include_guard/InvalidScope-result.txt1
-rw-r--r--Tests/RunCMake/include_guard/InvalidScope-stderr.txt4
-rw-r--r--Tests/RunCMake/include_guard/InvalidScope.cmake1
-rw-r--r--Tests/RunCMake/include_guard/RunCMakeTest.cmake7
-rw-r--r--Tests/RunCMake/include_guard/Scripts/DirScript.cmake12
-rw-r--r--Tests/RunCMake/include_guard/Scripts/GlobScript.cmake12
-rw-r--r--Tests/RunCMake/include_guard/Scripts/VarScript.cmake12
-rw-r--r--Tests/RunCMake/include_guard/VariableScope.cmake24
-rw-r--r--Tests/RunCMake/include_guard/global_script_dir/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/include_guard/sub_dir_script1/CMakeLists.txt9
-rw-r--r--Tests/RunCMake/include_guard/sub_dir_script1/sub_dir_script3/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/include_guard/sub_dir_script2/CMakeLists.txt1
-rw-r--r--Tests/RunCMake/pseudo_cppcheck.c32
-rw-r--r--Tests/RunCMake/string/Prepend.cmake58
-rw-r--r--Tests/RunCMake/string/PrependNoArgs-result.txt1
-rw-r--r--Tests/RunCMake/string/PrependNoArgs-stderr.txt4
-rw-r--r--Tests/RunCMake/string/PrependNoArgs.cmake1
-rw-r--r--Tests/RunCMake/string/RegexMultiMatchClear-stderr.txt12
-rw-r--r--Tests/RunCMake/string/RegexMultiMatchClear.cmake20
-rw-r--r--Tests/RunCMake/string/RunCMakeTest.cmake4
-rw-r--r--Tests/RunCMake/string/Timestamp-stderr.txt2
-rw-r--r--Tests/RunCMake/string/Timestamp.cmake2
-rw-r--r--Tests/RunCMake/target_link_libraries/RunCMakeTest.cmake1
-rw-r--r--Tests/RunCMake/target_link_libraries/UNKNOWN-IMPORTED-GLOBAL.cmake4
-rw-r--r--Tests/RunCMake/test_include_dirs/CMakeLists.txt3
-rw-r--r--Tests/RunCMake/test_include_dirs/RunCMakeTest.cmake17
-rw-r--r--Tests/RunCMake/test_include_dirs/TID-test-stdout.txt17
-rw-r--r--Tests/RunCMake/test_include_dirs/TID.cmake29
-rw-r--r--Tests/RunCMake/test_include_dirs/add-tests.cmake8
-rw-r--r--Tests/RunCMake/test_include_dirs/dummy.cpp4
-rw-r--r--Tests/RunCMake/variable_watch/ModifyWatchInCallback.cmake17
-rw-r--r--Tests/RunCMake/variable_watch/RunCMakeTest.cmake1
-rw-r--r--Tests/SameName/CMakeLists.txt7
-rw-r--r--Tests/SameName/Exe1/CMakeLists.txt11
-rw-r--r--Tests/SameName/Exe1/conly.c11
-rw-r--r--Tests/SameName/Lib1/CMakeLists.txt1
-rw-r--r--Tests/SameName/Lib1/libc1.c4
-rw-r--r--Tests/SameName/Lib1/libc1.h1
-rw-r--r--Tests/Server/CMakeLists.txt3
-rw-r--r--Tests/Server/cmakelib.py39
-rw-r--r--Tests/Server/server-test.py27
-rw-r--r--Tests/Server/tc_cache.json24
-rw-r--r--Tests/Server/tc_handshake.json4
-rw-r--r--Tests/SimpleExclude/CMakeLists.txt11
-rw-r--r--Tests/SimpleExclude/dirC/CMakeLists.txt3
-rw-r--r--Tests/SimpleExclude/dirC/dirA/CMakeLists.txt10
-rw-r--r--Tests/SimpleExclude/dirC/dirA/t1.c8
-rw-r--r--Tests/SimpleExclude/dirC/dirA/t2.c7
-rw-r--r--Tests/SimpleExclude/dirC/dirA/t3.c7
-rw-r--r--Tests/SimpleExclude/dirC/dirA/t4.c17
-rw-r--r--Tests/SimpleExclude/dirC/dirA/t5.c7
-rw-r--r--Tests/SimpleExclude/dirC/dirB/CMakeLists.txt5
-rw-r--r--Tests/SimpleExclude/dirC/dirB/t6.c8
-rw-r--r--Tests/SimpleExclude/dirC/dirB/t7.c15
-rw-r--r--Tests/SimpleExclude/dirD/CMakeLists.txt7
-rw-r--r--Tests/SimpleExclude/dirD/t8.c7
-rw-r--r--Tests/SimpleExclude/dirD/t9.c24
-rw-r--r--Tests/SimpleExclude/run.cmake.in13
-rw-r--r--Tests/SimpleInstall/scripts/.gitattributes1
-rw-r--r--Tests/SimpleInstallS2/scripts/.gitattributes1
-rw-r--r--Tests/TargetName/scripts/.gitattributes1
-rw-r--r--Tests/VSGNUFortran/runtest.cmake.in2
-rw-r--r--Tests/VSResource/CMakeLists.txt7
-rw-r--r--Tests/VSWinStorePhone/CMakeLists.txt6
-rw-r--r--Tests/XCTest/CMakeLists.txt2
-rw-r--r--Tests/bootstrap.bat.in4
-rw-r--r--Utilities/.gitattributes7
-rw-r--r--Utilities/Doxygen/CMakeLists.txt2
-rw-r--r--Utilities/GitSetup/.gitattributes6
-rw-r--r--Utilities/IWYU/mapping.imp27
-rw-r--r--Utilities/KWIML/.gitattributes1
-rw-r--r--Utilities/Release/linux64_release.cmake1
-rw-r--r--Utilities/Release/osx_release.cmake1
-rw-r--r--Utilities/Release/upload_release.cmake2
-rw-r--r--Utilities/Release/win32_release.cmake1
-rw-r--r--Utilities/Release/win64_release.cmake1
-rw-r--r--Utilities/Scripts/BoostScanDeps.cmake39
-rwxr-xr-xUtilities/Scripts/clang-format.bash8
-rwxr-xr-xUtilities/Scripts/regenerate-lexers.bash33
-rwxr-xr-xUtilities/Scripts/update-curl.bash12
-rwxr-xr-xUtilities/Scripts/update-jsoncpp.bash33
-rwxr-xr-xUtilities/Scripts/update-libarchive.bash2
-rw-r--r--Utilities/Sphinx/.gitignore1
-rw-r--r--Utilities/Sphinx/CMakeLists.txt2
-rw-r--r--Utilities/cmbzip2/dlltest.dsp93
-rw-r--r--Utilities/cmbzip2/libbz2.dsp130
-rw-r--r--Utilities/cmcurl/.gitattributes1
-rw-r--r--Utilities/cmcurl/CMake/Macros.cmake29
-rw-r--r--Utilities/cmcurl/CMake/OtherTests.cmake12
-rw-r--r--Utilities/cmcurl/CMake/cmake_uninstall.cmake.in26
-rw-r--r--Utilities/cmcurl/CMakeLists.txt189
-rw-r--r--Utilities/cmcurl/include/curl/curl.h247
-rw-r--r--Utilities/cmcurl/include/curl/curlbuild.h.cmake218
-rw-r--r--Utilities/cmcurl/include/curl/curlrules.h239
-rw-r--r--Utilities/cmcurl/include/curl/curlver.h8
-rw-r--r--Utilities/cmcurl/include/curl/multi.h2
-rw-r--r--Utilities/cmcurl/include/curl/system.h615
-rw-r--r--Utilities/cmcurl/include/curl/typecheck-gcc.h21
-rw-r--r--Utilities/cmcurl/lib/CMakeLists.txt11
-rw-r--r--Utilities/cmcurl/lib/Makefile.inc5
-rw-r--r--Utilities/cmcurl/lib/asyn-ares.c8
-rw-r--r--Utilities/cmcurl/lib/asyn-thread.c55
-rw-r--r--Utilities/cmcurl/lib/conncache.h2
-rw-r--r--Utilities/cmcurl/lib/connect.c82
-rw-r--r--Utilities/cmcurl/lib/connect.h4
-rw-r--r--Utilities/cmcurl/lib/content_encoding.c6
-rw-r--r--Utilities/cmcurl/lib/cookie.c146
-rw-r--r--Utilities/cmcurl/lib/cookie.h11
-rw-r--r--Utilities/cmcurl/lib/curl_addrinfo.c6
-rw-r--r--Utilities/cmcurl/lib/curl_config.h.cmake12
-rw-r--r--Utilities/cmcurl/lib/curl_fnmatch.c12
-rw-r--r--Utilities/cmcurl/lib/curl_ntlm_core.c92
-rw-r--r--Utilities/cmcurl/lib/curl_ntlm_core.h14
-rw-r--r--Utilities/cmcurl/lib/curl_ntlm_wb.c26
-rw-r--r--Utilities/cmcurl/lib/curl_rtmp.c8
-rw-r--r--Utilities/cmcurl/lib/curl_sasl.c6
-rw-r--r--Utilities/cmcurl/lib/curl_setup.h42
-rw-r--r--Utilities/cmcurl/lib/curl_setup_once.h14
-rw-r--r--Utilities/cmcurl/lib/curl_threads.c15
-rw-r--r--Utilities/cmcurl/lib/dict.c15
-rw-r--r--Utilities/cmcurl/lib/dotdot.c30
-rw-r--r--Utilities/cmcurl/lib/easy.c26
-rw-r--r--Utilities/cmcurl/lib/escape.c26
-rw-r--r--Utilities/cmcurl/lib/file.c42
-rw-r--r--Utilities/cmcurl/lib/formdata.c887
-rw-r--r--Utilities/cmcurl/lib/formdata.h54
-rw-r--r--Utilities/cmcurl/lib/ftp.c278
-rw-r--r--Utilities/cmcurl/lib/ftp.h4
-rw-r--r--Utilities/cmcurl/lib/ftplistparser.c38
-rw-r--r--Utilities/cmcurl/lib/getinfo.c87
-rw-r--r--Utilities/cmcurl/lib/gopher.c11
-rw-r--r--Utilities/cmcurl/lib/hash.c4
-rw-r--r--Utilities/cmcurl/lib/hostcheck.c14
-rw-r--r--Utilities/cmcurl/lib/hostip.c12
-rw-r--r--Utilities/cmcurl/lib/hostip4.c4
-rw-r--r--Utilities/cmcurl/lib/hostip6.c4
-rw-r--r--Utilities/cmcurl/lib/http.c444
-rw-r--r--Utilities/cmcurl/lib/http.h17
-rw-r--r--Utilities/cmcurl/lib/http2.c65
-rw-r--r--Utilities/cmcurl/lib/http2.h7
-rw-r--r--Utilities/cmcurl/lib/http_chunks.c26
-rw-r--r--Utilities/cmcurl/lib/http_ntlm.c13
-rw-r--r--Utilities/cmcurl/lib/http_proxy.c278
-rw-r--r--Utilities/cmcurl/lib/http_proxy.h10
-rw-r--r--Utilities/cmcurl/lib/if2ip.c16
-rw-r--r--Utilities/cmcurl/lib/if2ip.h5
-rw-r--r--Utilities/cmcurl/lib/imap.c195
-rw-r--r--Utilities/cmcurl/lib/imap.h3
-rw-r--r--Utilities/cmcurl/lib/inet_ntop.c14
-rw-r--r--Utilities/cmcurl/lib/inet_pton.c6
-rw-r--r--Utilities/cmcurl/lib/inet_pton.h5
-rw-r--r--Utilities/cmcurl/lib/krb5.c2
-rw-r--r--Utilities/cmcurl/lib/ldap.c9
-rw-r--r--Utilities/cmcurl/lib/memdebug.c23
-rw-r--r--Utilities/cmcurl/lib/mime.c1860
-rw-r--r--Utilities/cmcurl/lib/mime.h135
-rw-r--r--Utilities/cmcurl/lib/mprintf.c38
-rw-r--r--Utilities/cmcurl/lib/multi.c139
-rw-r--r--Utilities/cmcurl/lib/multihandle.h2
-rw-r--r--Utilities/cmcurl/lib/netrc.c44
-rw-r--r--Utilities/cmcurl/lib/non-ascii.c104
-rw-r--r--Utilities/cmcurl/lib/non-ascii.h4
-rw-r--r--Utilities/cmcurl/lib/openldap.c14
-rw-r--r--Utilities/cmcurl/lib/parsedate.c74
-rw-r--r--Utilities/cmcurl/lib/pingpong.c28
-rw-r--r--Utilities/cmcurl/lib/pingpong.h2
-rw-r--r--Utilities/cmcurl/lib/pipeline.c37
-rw-r--r--Utilities/cmcurl/lib/pop3.c79
-rw-r--r--Utilities/cmcurl/lib/progress.c132
-rw-r--r--Utilities/cmcurl/lib/progress.h8
-rw-r--r--Utilities/cmcurl/lib/rand.c2
-rw-r--r--Utilities/cmcurl/lib/rtsp.c43
-rw-r--r--Utilities/cmcurl/lib/rtsp.h2
-rw-r--r--Utilities/cmcurl/lib/security.c4
-rw-r--r--Utilities/cmcurl/lib/select.c10
-rw-r--r--Utilities/cmcurl/lib/select.h5
-rw-r--r--Utilities/cmcurl/lib/sendf.c20
-rw-r--r--Utilities/cmcurl/lib/smb.c31
-rw-r--r--Utilities/cmcurl/lib/smtp.c118
-rw-r--r--Utilities/cmcurl/lib/socks.c88
-rw-r--r--Utilities/cmcurl/lib/socks_gssapi.c59
-rw-r--r--Utilities/cmcurl/lib/socks_sspi.c24
-rw-r--r--Utilities/cmcurl/lib/speedcheck.c4
-rw-r--r--Utilities/cmcurl/lib/speedcheck.h4
-rw-r--r--Utilities/cmcurl/lib/splay.c26
-rw-r--r--Utilities/cmcurl/lib/splay.h17
-rw-r--r--Utilities/cmcurl/lib/ssh.c58
-rw-r--r--Utilities/cmcurl/lib/strcase.c11
-rw-r--r--Utilities/cmcurl/lib/strdup.c6
-rw-r--r--Utilities/cmcurl/lib/strerror.c57
-rw-r--r--Utilities/cmcurl/lib/strtoofft.c67
-rw-r--r--Utilities/cmcurl/lib/strtoofft.h37
-rw-r--r--Utilities/cmcurl/lib/telnet.c48
-rw-r--r--Utilities/cmcurl/lib/tftp.c69
-rw-r--r--Utilities/cmcurl/lib/timeval.c71
-rw-r--r--Utilities/cmcurl/lib/timeval.h19
-rw-r--r--Utilities/cmcurl/lib/transfer.c215
-rw-r--r--Utilities/cmcurl/lib/transfer.h5
-rw-r--r--Utilities/cmcurl/lib/url.c339
-rw-r--r--Utilities/cmcurl/lib/urldata.h293
-rw-r--r--Utilities/cmcurl/lib/vauth/digest_sspi.c45
-rw-r--r--Utilities/cmcurl/lib/vauth/ntlm.c16
-rw-r--r--Utilities/cmcurl/lib/vauth/ntlm_sspi.c9
-rw-r--r--Utilities/cmcurl/lib/vauth/spnego_gssapi.c4
-rw-r--r--Utilities/cmcurl/lib/vauth/vauth.h5
-rw-r--r--Utilities/cmcurl/lib/version.c8
-rw-r--r--Utilities/cmcurl/lib/vtls/axtls.c190
-rw-r--r--Utilities/cmcurl/lib/vtls/axtls.h39
-rw-r--r--Utilities/cmcurl/lib/vtls/cyassl.c223
-rw-r--r--Utilities/cmcurl/lib/vtls/cyassl.h63
-rw-r--r--Utilities/cmcurl/lib/vtls/darwinssl.c469
-rw-r--r--Utilities/cmcurl/lib/vtls/darwinssl.h70
-rw-r--r--Utilities/cmcurl/lib/vtls/gskit.c191
-rw-r--r--Utilities/cmcurl/lib/vtls/gskit.h38
-rw-r--r--Utilities/cmcurl/lib/vtls/gtls.c233
-rw-r--r--Utilities/cmcurl/lib/vtls/gtls.h64
-rw-r--r--Utilities/cmcurl/lib/vtls/mbedtls.c237
-rw-r--r--Utilities/cmcurl/lib/vtls/mbedtls.h52
-rw-r--r--Utilities/cmcurl/lib/vtls/nss.c237
-rw-r--r--Utilities/cmcurl/lib/vtls/nssg.h71
-rw-r--r--Utilities/cmcurl/lib/vtls/openssl.c627
-rw-r--r--Utilities/cmcurl/lib/vtls/openssl.h91
-rw-r--r--Utilities/cmcurl/lib/vtls/polarssl.c198
-rw-r--r--Utilities/cmcurl/lib/vtls/polarssl.h52
-rw-r--r--Utilities/cmcurl/lib/vtls/polarssl_threadlock.c4
-rw-r--r--Utilities/cmcurl/lib/vtls/schannel.c532
-rw-r--r--Utilities/cmcurl/lib/vtls/schannel.h89
-rw-r--r--Utilities/cmcurl/lib/vtls/vtls.c501
-rw-r--r--Utilities/cmcurl/lib/vtls/vtls.h82
-rw-r--r--Utilities/cmcurl/lib/warnless.c32
-rw-r--r--Utilities/cmexpat/.gitattributes1
-rw-r--r--Utilities/cmjsoncpp/.gitattributes1
-rw-r--r--Utilities/cmjsoncpp/CMakeLists.txt2
-rw-r--r--Utilities/cmjsoncpp/LICENSE8
-rw-r--r--Utilities/cmjsoncpp/include/json/allocator.h102
-rw-r--r--Utilities/cmjsoncpp/include/json/assertions.h41
-rw-r--r--Utilities/cmjsoncpp/include/json/config.h136
-rw-r--r--Utilities/cmjsoncpp/include/json/features.h10
-rw-r--r--Utilities/cmjsoncpp/include/json/forwards.h8
-rw-r--r--Utilities/cmjsoncpp/include/json/json.h2
-rw-r--r--Utilities/cmjsoncpp/include/json/reader.h181
-rw-r--r--Utilities/cmjsoncpp/include/json/value.h723
-rw-r--r--Utilities/cmjsoncpp/include/json/version.h16
-rw-r--r--Utilities/cmjsoncpp/include/json/writer.h205
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_batchallocator.h121
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_internalarray.inl360
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_internalmap.inl473
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_reader.cpp1434
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_tool.h44
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_value.cpp892
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_valueiterator.inl138
-rw-r--r--Utilities/cmjsoncpp/src/lib_json/json_writer.cpp823
-rw-r--r--Utilities/cmlibarchive/.gitattributes1
-rw-r--r--Utilities/cmlibarchive/CMakeLists.txt409
-rw-r--r--Utilities/cmlibarchive/build/cmake/config.h.in92
-rw-r--r--Utilities/cmlibarchive/build/version2
-rw-r--r--Utilities/cmlibarchive/libarchive/CMakeLists.txt15
-rw-r--r--Utilities/cmlibarchive/libarchive/archive.h4
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_check_magic.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_disk_acl_darwin.c559
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_disk_acl_freebsd.c700
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_disk_acl_linux.c743
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_disk_acl_sunos.c821
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_entry.32
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_entry.c31
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_entry.h2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_entry_acl.310
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_entry_paths.312
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_entry_perms.34
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_entry_sparse.c4
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_getdate.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_openssl_hmac_private.h2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_pack_dev.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_platform.h37
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_platform_acl.h49
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_platform_xattr.h41
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_random.c3
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read.c3
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_disk.372
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_disk_entry_from_file.c1285
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_disk_private.h9
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_format.36
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_open.34
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_filter_lz4.c6
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_cab.c156
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_cpio.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_iso9660.c5
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_lha.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_mtree.c180
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_tar.c18
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_warc.c9
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c39
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_string.c3
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_string_sprintf.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_util.c88
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_version_details.c133
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_add_filter.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_add_filter_by_name.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_add_filter_lz4.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_add_filter_program.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_data.324
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_disk.3185
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_disk_acl.c654
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c296
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_disk_private.h6
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_finish_entry.35
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_format.31
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format_by_name.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format_filter_by_ext.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format_pax.c17
-rw-r--r--Utilities/cmlibarchive/libarchive/archive_write_set_format_warc.c2
-rw-r--r--Utilities/cmlibarchive/libarchive/config_freebsd.h351
-rw-r--r--Utilities/cmlibarchive/libarchive/libarchive_changes.31
-rw-r--r--Utilities/cmlibarchive/libarchive/mtree.52
-rw-r--r--Utilities/cmlibarchive/libarchive/xxhash.c12
-rw-r--r--Utilities/cmliblzma/.gitattributes1
-rw-r--r--Utilities/cmlibrhash/.gitattributes1
-rw-r--r--Utilities/cmlibuv/.gitattributes1
-rw-r--r--Utilities/cmlibuv/include/uv-unix.h16
-rw-r--r--Utilities/cmlibuv/src/unix/cmake-bootstrap.c139
-rw-r--r--Utilities/cmlibuv/src/unix/fs.c2
-rw-r--r--Utilities/cmlibuv/src/unix/internal.h14
-rw-r--r--Utilities/cmlibuv/src/unix/pipe.c2
-rw-r--r--Utilities/cmlibuv/src/unix/posix-hrtime.c25
-rw-r--r--Utilities/cmlibuv/src/unix/stream.c10
-rw-r--r--Utilities/cmlibuv/src/uv-common.c2
-rw-r--r--Utilities/cmvssetup/.gitattributes1
-rwxr-xr-xbootstrap357
1811 files changed, 47926 insertions, 30408 deletions
diff --git a/.clang-format b/.clang-format
index a8bde417d..88bfbd335 100644
--- a/.clang-format
+++ b/.clang-format
@@ -5,5 +5,4 @@ AlignOperands: false
AlwaysBreakAfterReturnType: None
AlwaysBreakAfterDefinitionReturnType: None
ColumnLimit: 79
-Standard: Cpp03
...
diff --git a/.clang-tidy b/.clang-tidy
index a9d121aa0..8d79b0c5d 100644
--- a/.clang-tidy
+++ b/.clang-tidy
@@ -1,16 +1,24 @@
---
Checks: "-*,\
+google-readability-casting,\
misc-*,\
-misc-incorrect-roundings,\
-misc-macro-parentheses,\
-misc-misplaced-widening-cast,\
-misc-static-assert,\
-modernize-make-shared,\
-modernize-make-unique,\
-modernize-redundant-void-arg,\
-modernize-use-bool-literals,\
-modernize-use-nullptr,\
-modernize-use-override,\
+modernize-*,\
+-modernize-deprecated-headers,\
+-modernize-pass-by-value,\
+-modernize-raw-string-literal,\
+-modernize-return-braced-init-list,\
+-modernize-use-auto,\
+-modernize-use-default-member-init,\
+-modernize-use-emplace,\
+-modernize-use-equals-default,\
+-modernize-use-equals-delete,\
+-modernize-use-noexcept,\
+-modernize-use-transparent-functors,\
+-modernize-use-using,\
performance-*,\
-performance-inefficient-string-concatenation,\
readability-*,\
@@ -24,7 +32,4 @@ readability-*,\
-readability-simplify-boolean-expr,\
"
HeaderFilterRegex: 'Source/cm[^/]*\.(h|hxx|cxx)$'
-CheckOptions:
- - key: modernize-use-nullptr.NullMacros
- value: 'CM_NULLPTR'
...
diff --git a/.gitattributes b/.gitattributes
deleted file mode 100644
index 38291609e..000000000
--- a/.gitattributes
+++ /dev/null
@@ -1,39 +0,0 @@
-.gitattributes export-ignore
-.hooks* export-ignore
-
-# Custom attribute to mark sources as using our C code style.
-[attr]our-c-style whitespace=tab-in-indent format.clang-format
-
-# Custom attribute to mark sources as generated.
-# Do not perform whitespace checks. Do not format.
-[attr]generated whitespace=-tab-in-indent,-indent-with-non-tab -format.clang-format
-
-bootstrap crlf=input
-configure crlf=input
-*.[1-9] crlf=input
-*.sh crlf=input
-*.sh.in crlf=input
-
-*.bat -crlf
-*.bat.in -crlf
-*.dsp -crlf
-*.dsw -crlf
-*.pfx -crlf
-*.png -crlf
-*.sln -crlf
-*.vcproj -crlf
-
-*.c our-c-style
-*.cc our-c-style
-*.cpp our-c-style
-*.cu our-c-style
-*.cxx our-c-style
-*.h our-c-style
-*.hh our-c-style
-*.hpp our-c-style
-*.hxx our-c-style
-*.notcu our-c-style
-
-*.cmake whitespace=tab-in-indent
-*.rst whitespace=tab-in-indent conflict-marker-size=79
-*.txt whitespace=tab-in-indent
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index 5d1732d17..000000000
--- a/.gitignore
+++ /dev/null
@@ -1,7 +0,0 @@
-# Exclude MacOS Finder files.
-.DS_Store
-
-*.user*
-
-*.pyc
-Testing
diff --git a/.hooks-config b/.hooks-config
deleted file mode 100644
index 064371c12..000000000
--- a/.hooks-config
+++ /dev/null
@@ -1,10 +0,0 @@
-# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
-# file Copyright.txt or https://cmake.org/licensing for details.
-
-# Loaded by .git/hooks/(pre-commit|commit-msg|prepare-commit-msg)
-# during git commit after local hooks have been installed.
-
-[hooks "chain"]
- pre-commit = Utilities/Git/pre-commit
- commit-msg = Utilities/Git/commit-msg
- prepare-commit-msg = Utilities/Git/prepare-commit-msg
diff --git a/Auxiliary/vim/cmake.vim.in b/Auxiliary/vim/cmake.vim.in
index 389d9e46e..2461e0bdb 100644
--- a/Auxiliary/vim/cmake.vim.in
+++ b/Auxiliary/vim/cmake.vim.in
@@ -1,10 +1,13 @@
" vim: set nowrap:
" Vim syntax file
+" Program: CMake - Cross-Platform Makefile Generator
+" Version: @VERSION@
" Language: CMake
-" Author: Andy Cedilnik <andy.cedilnik@kitware.com>, Nicholas Hutchinson <nshutchinson@gmail.com>, Patrick Boettcher <patrick.boettcher@posteo.de>
-" Maintainer: Karthik Krishnan <karthik.krishnan@kitware.com>
-" Last Change: $Date$
-" Version: $Revision$
+" Author: Andy Cedilnik <andy.cedilnik@kitware.com>,
+" Nicholas Hutchinson <nshutchinson@gmail.com>,
+" Patrick Boettcher <patrick.boettcher@posteo.de>
+" Maintainer: Dimitri Merejkowsky <d.merej@gmail.com>
+" Former Maintainer: Karthik Krishnan <karthik.krishnan@kitware.com>
"
" Licence: The CMake license applies to this file. See
" https://cmake.org/licensing
@@ -13,8 +16,10 @@
if exists("b:current_syntax")
finish
endif
+let s:keepcpo= &cpo
+set cpo&vim
-syn region cmakeComment start="#" end="$" contains=cmakeTodo,@Spell
+syn region cmakeComment start="#" end="$" contains=cmakeTodo,cmakeLuaComment,@Spell
syn region cmakeLuaComment start="\[\z(=*\)\[" end="\]\z1\]" contains=cmakeTodo,@Spell
syn match cmakeEscaped /\(\\\\\|\\"\|\\n\|\\t\)/ contained
@@ -22,18 +27,18 @@ syn region cmakeRegistry start="\[" end="]" contained oneline contains=cmakeTodo
syn region cmakeGeneratorExpression start="$<" end=">" contained oneline contains=cmakeVariableValue,cmakeProperty,cmakeGeneratorExpressions,cmakeTodo
-syn region cmakeString start='"' end='"' contained contains=cmakeTodo,cmakeVariableValue
+syn region cmakeString start='"' end='"' contained contains=cmakeTodo,cmakeVariableValue,cmakeEscaped
syn region cmakeVariableValue start="${" end="}" contained oneline contains=cmakeVariable,cmakeTodo
syn region cmakeEnvironment start="$ENV{" end="}" contained oneline contains=cmakeTodo
-syn region cmakeArguments start="(" end=")" contains=ALLBUT,cmakeArguments,cmakeTodo
+syn region cmakeArguments start="(" end=")" contains=ALLBUT,cmakeCommand,cmakeCommandConditional,cmakeCommandRepeat,cmakeCommandDeprecated,cmakeArguments,cmakeTodo
syn case match
syn keyword cmakeProperty contained
- \ ABSTRACT ADDITIONAL_MAKE_CLEAN_FILES ADVANCED ALIASED_TARGET ALLOW_DUPLICATE_CUSTOM_TARGETS ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID_API ANDROID_API_MIN ANDROID_ARCH ANDROID_ASSETS_DIRECTORIES ANDROID_GUI ANDROID_JAR_DEPENDENCIES ANDROID_JAR_DIRECTORIES ANDROID_JAVA_SOURCE_DIR ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID_NATIVE_LIB_DIRECTORIES ANDROID_PROCESS_MAX ANDROID_PROGUARD ANDROID_PROGUARD_CONFIG_PATH ANDROID_SECURE_PROPS_PATH ANDROID_SKIP_ANT_STEP ANDROID_STL_TYPE ARCHIVE_OUTPUT_DIRECTORY ARCHIVE_OUTPUT_DIRECTORY_DEBUG ARCHIVE_OUTPUT_DIRECTORY_RELEASE ARCHIVE_OUTPUT_NAME ARCHIVE_OUTPUT_NAME_DEBUG ARCHIVE_OUTPUT_NAME_RELEASE ATTACHED_FILES ATTACHED_FILES_ON_FAIL AUTOGEN_TARGETS_FOLDER AUTOGEN_TARGET_DEPENDS AUTOMOC AUTOMOC_MOC_OPTIONS AUTOMOC_TARGETS_FOLDER AUTORCC AUTORCC_OPTIONS AUTOUIC AUTOUIC_OPTIONS BINARY_DIR BUILD_WITH_INSTALL_RPATH BUNDLE BUNDLE_EXTENSION CACHE_VARIABLES CLEAN_NO_CUSTOM CMAKE_CONFIGURE_DEPENDS CMAKE_CXX_KNOWN_FEATURES CMAKE_C_KNOWN_FEATURES COMPATIBLE_INTERFACE_BOOL COMPATIBLE_INTERFACE_NUMBER_MAX COMPATIBLE_INTERFACE_NUMBER_MIN COMPATIBLE_INTERFACE_STRING COMPILE_DEFINITIONS COMPILE_DEFINITIONS_DEBUG COMPILE_DEFINITIONS_RELEASE COMPILE_FEATURES COMPILE_FLAGS COMPILE_OPTIONS COMPILE_PDB_NAME COMPILE_PDB_NAME_DEBUG COMPILE_PDB_NAME_RELEASE COMPILE_PDB_OUTPUT_DIRECTORY COMPILE_PDB_OUTPUT_DIRECTORY_DEBUG COMPILE_PDB_OUTPUT_DIRECTORY_RELEASE COST CPACK_DESKTOP_SHORTCUTS CPACK_NEVER_OVERWRITE CPACK_PERMANENT CPACK_STARTUP_SHORTCUTS CPACK_START_MENU_SHORTCUTS CPACK_WIX_ACL CROSSCOMPILING_EMULATOR CXX_EXTENSIONS CXX_STANDARD CXX_STANDARD_REQUIRED C_EXTENSIONS C_STANDARD C_STANDARD_REQUIRED DEBUG_CONFIGURATIONS DEBUG_POSTFIX DEFINE_SYMBOL DEFINITIONS DEPENDS DISABLED_FEATURES ECLIPSE_EXTRA_NATURES ENABLED_FEATURES ENABLED_LANGUAGES ENABLE_EXPORTS ENVIRONMENT EXCLUDE_FROM_ALL EXCLUDE_FROM_DEFAULT_BUILD EXCLUDE_FROM_DEFAULT_BUILD_DEBUG EXCLUDE_FROM_DEFAULT_BUILD_RELEASE EXPORT_NAME EXTERNAL_OBJECT EchoString FAIL_REGULAR_EXPRESSION FIND_LIBRARY_USE_LIB64_PATHS FIND_LIBRARY_USE_OPENBSD_VERSIONING FOLDER FRAMEWORK FRAMEWORK_VERSION Fortran_FORMAT Fortran_MODULE_DIRECTORY GENERATED GENERATOR_FILE_NAME GLOBAL_DEPENDS_DEBUG_MODE GLOBAL_DEPENDS_NO_CYCLES GNUtoMS HAS_CXX HEADER_FILE_ONLY HELPSTRING IMPLICIT_DEPENDS_INCLUDE_TRANSFORM IMPORTED IMPORTED_CONFIGURATIONS IMPORTED_IMPLIB IMPORTED_IMPLIB_DEBUG IMPORTED_IMPLIB_RELEASE IMPORTED_LINK_DEPENDENT_LIBRARIES IMPORTED_LINK_DEPENDENT_LIBRARIES_DEBUG IMPORTED_LINK_DEPENDENT_LIBRARIES_RELEASE IMPORTED_LINK_INTERFACE_LANGUAGES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE IMPORTED_LINK_INTERFACE_LIBRARIES IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG IMPORTED_LINK_INTERFACE_LIBRARIES_RELEASE IMPORTED_LINK_INTERFACE_MULTIPLICITY IMPORTED_LINK_INTERFACE_MULTIPLICITY_DEBUG IMPORTED_LINK_INTERFACE_MULTIPLICITY_RELEASE IMPORTED_LOCATION IMPORTED_LOCATION_DEBUG IMPORTED_LOCATION_RELEASE IMPORTED_NO_SONAME IMPORTED_NO_SONAME_DEBUG IMPORTED_NO_SONAME_RELEASE IMPORTED_SONAME IMPORTED_SONAME_DEBUG IMPORTED_SONAME_RELEASE IMPORT_PREFIX IMPORT_SUFFIX INCLUDE_DIRECTORIES INCLUDE_REGULAR_EXPRESSION INSTALL_NAME_DIR INSTALL_RPATH INSTALL_RPATH_USE_LINK_PATH INTERFACE_AUTOUIC_OPTIONS INTERFACE_COMPILE_DEFINITIONS INTERFACE_COMPILE_FEATURES INTERFACE_COMPILE_OPTIONS INTERFACE_INCLUDE_DIRECTORIES INTERFACE_LINK_LIBRARIES INTERFACE_POSITION_INDEPENDENT_CODE INTERFACE_SOURCES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES INTERPROCEDURAL_OPTIMIZATION INTERPROCEDURAL_OPTIMIZATION_DEBUG INTERPROCEDURAL_OPTIMIZATION_RELEASE IN_TRY_COMPILE JOB_POOLS JOB_POOL_COMPILE JOB_POOL_LINK KEEP_EXTENSION LABELS LANGUAGE LIBRARY_OUTPUT_DIRECTORY LIBRARY_OUTPUT_DIRECTORY_DEBUG LIBRARY_OUTPUT_DIRECTORY_RELEASE LIBRARY_OUTPUT_NAME LIBRARY_OUTPUT_NAME_DEBUG LIBRARY_OUTPUT_NAME_RELEASE LINKER_LANGUAGE LINK_DEPENDS LINK_DEPENDS_NO_SHARED LINK_DIRECTORIES LINK_FLAGS LINK_FLAGS_DEBUG LINK_FLAGS_RELEASE LINK_INTERFACE_LIBRARIES LINK_INTERFACE_LIBRARIES_DEBUG LINK_INTERFACE_LIBRARIES_RELEASE LINK_INTERFACE_MULTIPLICITY LINK_INTERFACE_MULTIPLICITY_DEBUG LINK_INTERFACE_MULTIPLICITY_RELEASE LINK_LIBRARIES LINK_SEARCH_END_STATIC LINK_SEARCH_START_STATIC LISTFILE_STACK LOCATION LOCATION_DEBUG LOCATION_RELEASE MACOSX_BUNDLE MACOSX_BUNDLE_INFO_PLIST MACOSX_FRAMEWORK_INFO_PLIST MACOSX_PACKAGE_LOCATION MACOSX_RPATH MACROS MAP_IMPORTED_CONFIG_DEBUG MAP_IMPORTED_CONFIG_RELEASE MEASUREMENT MODIFIED NAME NO_SONAME NO_SYSTEM_FROM_IMPORTED OBJECT_DEPENDS OBJECT_OUTPUTS OSX_ARCHITECTURES OSX_ARCHITECTURES_DEBUG OSX_ARCHITECTURES_RELEASE OUTPUT_NAME OUTPUT_NAME_DEBUG OUTPUT_NAME_RELEASE PACKAGES_FOUND PACKAGES_NOT_FOUND PARENT_DIRECTORY PASS_REGULAR_EXPRESSION PDB_NAME PDB_NAME_DEBUG PDB_NAME_RELEASE PDB_OUTPUT_DIRECTORY PDB_OUTPUT_DIRECTORY_DEBUG PDB_OUTPUT_DIRECTORY_RELEASE POSITION_INDEPENDENT_CODE POST_INSTALL_SCRIPT PREDEFINED_TARGETS_FOLDER PREFIX PRE_INSTALL_SCRIPT PRIVATE_HEADER PROCESSORS PROJECT_LABEL PUBLIC_HEADER REPORT_UNDEFINED_PROPERTIES REQUIRED_FILES RESOURCE RESOURCE_LOCK RULE_LAUNCH_COMPILE RULE_LAUNCH_CUSTOM RULE_LAUNCH_LINK RULE_MESSAGES RUNTIME_OUTPUT_DIRECTORY RUNTIME_OUTPUT_DIRECTORY_DEBUG RUNTIME_OUTPUT_DIRECTORY_RELEASE RUNTIME_OUTPUT_NAME RUNTIME_OUTPUT_NAME_DEBUG RUNTIME_OUTPUT_NAME_RELEASE RUN_SERIAL SKIP_BUILD_RPATH SKIP_RETURN_CODE SOURCES SOURCE_DIR SOVERSION STATIC_LIBRARY_FLAGS STATIC_LIBRARY_FLAGS_DEBUG STATIC_LIBRARY_FLAGS_RELEASE STRINGS SUFFIX SYMBOLIC TARGET_ARCHIVES_MAY_BE_SHARED_LIBS TARGET_MESSAGES TARGET_SUPPORTS_SHARED_LIBS TEST_INCLUDE_FILE TIMEOUT TYPE USE_FOLDERS VALUE VARIABLES VERSION VISIBILITY_INLINES_HIDDEN VS_DEPLOYMENT_CONTENT VS_DEPLOYMENT_LOCATION VS_DESKTOP_EXTENSIONS_VERSION VS_DOTNET_REFERENCES VS_DOTNET_TARGET_FRAMEWORK_VERSION VS_GLOBAL_KEYWORD VS_GLOBAL_PROJECT_TYPES VS_GLOBAL_ROOTNAMESPACE VS_IOT_EXTENSIONS_VERSION VS_IOT_STARTUP_TASK VS_KEYWORD VS_MOBILE_EXTENSIONS_VERSION VS_SCC_AUXPATH VS_SCC_LOCALPATH VS_SCC_PROJECTNAME VS_SCC_PROVIDER VS_SHADER_ENTRYPOINT VS_SHADER_FLAGS VS_SHADER_MODEL VS_SHADER_TYPE VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION VS_WINRT_COMPONENT VS_WINRT_EXTENSIONS VS_WINRT_REFERENCES VS_XAML_TYPE WILL_FAIL WIN32_EXECUTABLE WINDOWS_EXPORT_ALL_SYMBOLS WORKING_DIRECTORY WRAP_EXCLUDE XCODE_EXPLICIT_FILE_TYPE XCODE_LAST_KNOWN_FILE_TYPE XCTEST
+@PROPERTIES@
syn keyword cmakeVariable contained
@VARIABLE_LIST@
@@ -91,3 +96,8 @@ hi def link cmakeVariable Identifier
@KEYWORDS_HIGHLIGHT@
let b:current_syntax = "cmake"
+
+let &cpo = s:keepcpo
+unlet s:keepcpo
+
+"EOF"
diff --git a/Auxiliary/vim/extract-upper-case.pl b/Auxiliary/vim/extract-upper-case.pl
index ea77cbb5c..9e3c439bb 100755
--- a/Auxiliary/vim/extract-upper-case.pl
+++ b/Auxiliary/vim/extract-upper-case.pl
@@ -29,8 +29,8 @@ push @modules, "ExternalProject";
# variables
open(CMAKE, "$cmake --help-variable-list|") or die "could not run cmake";
while (<CMAKE>) {
+ next if /\</; # skip if containing < or >
chomp;
- next if /\</; # skip VARIABLES which contained <>-"templates"
push @variables, $_;
}
close(CMAKE);
@@ -70,11 +70,24 @@ my @generator_expr = extract_upper("$cmake --help-manual cmake-generator-express
# properties
open(CMAKE, "$cmake --help-property-list|");
while (<CMAKE>) {
+ next if /\</; # skip if containing < or >
chomp;
push @properties, $_;
}
close(CMAKE);
+# transform all properties in a hash
+my %properties = map { $_ => 1 } @properties;
+
+# version
+open(CMAKE, "$cmake --version|");
+my $version = 'unknown';
+while (<CMAKE>) {
+ chomp;
+ $version = $_ if /cmake version/;
+}
+close(CMAKE);
+
# generate cmake.vim
open(IN, "<cmake.vim.in") or die "could not read cmake.vim.in";
open(OUT, ">syntax/cmake.vim") or die "could not write to syntax/cmake.vim";
@@ -102,6 +115,8 @@ while(<IN>)
print OUT " " x 12 , "\\ ", join(" ", sort keys %loop), "\n";
} elsif ($1 eq "DEPRECATED") {
print OUT " " x 12 , "\\ ", join(" ", sort keys %deprecated), "\n";
+ } elsif ($1 eq "PROPERTIES") {
+ print OUT " " x 12 , "\\ ", join(" ", sort keys %properties), "\n";
} elsif ($1 eq "KEYWORDS") {
foreach my $k (sort keys %keywords) {
print OUT "syn keyword cmakeKW$k contained\n";
@@ -111,6 +126,9 @@ while(<IN>)
}
} elsif ($1 eq "KEYWORDS_HIGHLIGHT") {
print OUT join("\n", @keyword_hi), "\n";
+ } elsif ($1 eq "VERSION") {
+ $_ =~ s/\@VERSION\@/$version/;
+ print OUT $_;
} else {
print "ERROR do not know how to replace $1\n";
}
@@ -128,7 +146,6 @@ sub extract_upper
open(KW, $input);
while (<KW>) {
-
foreach my $w (m/\b([A-Z_]{2,})\b/g) {
next
if exists $variables{$w} or # skip if it is a variable
diff --git a/Auxiliary/vim/syntax/cmake.vim b/Auxiliary/vim/syntax/cmake.vim
index a191c1872..5f9af05be 100644
--- a/Auxiliary/vim/syntax/cmake.vim
+++ b/Auxiliary/vim/syntax/cmake.vim
@@ -1,10 +1,13 @@
" vim: set nowrap:
" Vim syntax file
+" Program: CMake - Cross-Platform Makefile Generator
+" Version: cmake version 3.9.20170830-ge0713
" Language: CMake
-" Author: Andy Cedilnik <andy.cedilnik@kitware.com>, Nicholas Hutchinson <nshutchinson@gmail.com>, Patrick Boettcher <patrick.boettcher@posteo.de>
-" Maintainer: Karthik Krishnan <karthik.krishnan@kitware.com>
-" Last Change: $Date$
-" Version: $Revision$
+" Author: Andy Cedilnik <andy.cedilnik@kitware.com>,
+" Nicholas Hutchinson <nshutchinson@gmail.com>,
+" Patrick Boettcher <patrick.boettcher@posteo.de>
+" Maintainer: Dimitri Merejkowsky <d.merej@gmail.com>
+" Former Maintainer: Karthik Krishnan <karthik.krishnan@kitware.com>
"
" Licence: The CMake license applies to this file. See
" https://cmake.org/licensing
@@ -13,8 +16,10 @@
if exists("b:current_syntax")
finish
endif
+let s:keepcpo= &cpo
+set cpo&vim
-syn region cmakeComment start="#" end="$" contains=cmakeTodo,@Spell
+syn region cmakeComment start="#" end="$" contains=cmakeTodo,cmakeLuaComment,@Spell
syn region cmakeLuaComment start="\[\z(=*\)\[" end="\]\z1\]" contains=cmakeTodo,@Spell
syn match cmakeEscaped /\(\\\\\|\\"\|\\n\|\\t\)/ contained
@@ -22,27 +27,27 @@ syn region cmakeRegistry start="\[" end="]" contained oneline contains=cmakeTodo
syn region cmakeGeneratorExpression start="$<" end=">" contained oneline contains=cmakeVariableValue,cmakeProperty,cmakeGeneratorExpressions,cmakeTodo
-syn region cmakeString start='"' end='"' contained contains=cmakeTodo,cmakeVariableValue
+syn region cmakeString start='"' end='"' contained contains=cmakeTodo,cmakeVariableValue,cmakeEscaped
syn region cmakeVariableValue start="${" end="}" contained oneline contains=cmakeVariable,cmakeTodo
syn region cmakeEnvironment start="$ENV{" end="}" contained oneline contains=cmakeTodo
-syn region cmakeArguments start="(" end=")" contains=ALLBUT,cmakeArguments,cmakeTodo
+syn region cmakeArguments start="(" end=")" contains=ALLBUT,cmakeCommand,cmakeCommandConditional,cmakeCommandRepeat,cmakeCommandDeprecated,cmakeArguments,cmakeTodo
syn case match
syn keyword cmakeProperty contained
- \ ABSTRACT ADDITIONAL_MAKE_CLEAN_FILES ADVANCED ALIASED_TARGET ALLOW_DUPLICATE_CUSTOM_TARGETS ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID_API ANDROID_API_MIN ANDROID_ARCH ANDROID_ASSETS_DIRECTORIES ANDROID_GUI ANDROID_JAR_DEPENDENCIES ANDROID_JAR_DIRECTORIES ANDROID_JAVA_SOURCE_DIR ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID_NATIVE_LIB_DIRECTORIES ANDROID_PROCESS_MAX ANDROID_PROGUARD ANDROID_PROGUARD_CONFIG_PATH ANDROID_SECURE_PROPS_PATH ANDROID_SKIP_ANT_STEP ANDROID_STL_TYPE ARCHIVE_OUTPUT_DIRECTORY ARCHIVE_OUTPUT_DIRECTORY_DEBUG ARCHIVE_OUTPUT_DIRECTORY_RELEASE ARCHIVE_OUTPUT_NAME ARCHIVE_OUTPUT_NAME_DEBUG ARCHIVE_OUTPUT_NAME_RELEASE ATTACHED_FILES ATTACHED_FILES_ON_FAIL AUTOGEN_TARGETS_FOLDER AUTOGEN_TARGET_DEPENDS AUTOMOC AUTOMOC_MOC_OPTIONS AUTOMOC_TARGETS_FOLDER AUTORCC AUTORCC_OPTIONS AUTOUIC AUTOUIC_OPTIONS BINARY_DIR BUILD_WITH_INSTALL_RPATH BUNDLE BUNDLE_EXTENSION CACHE_VARIABLES CLEAN_NO_CUSTOM CMAKE_CONFIGURE_DEPENDS CMAKE_CXX_KNOWN_FEATURES CMAKE_C_KNOWN_FEATURES COMPATIBLE_INTERFACE_BOOL COMPATIBLE_INTERFACE_NUMBER_MAX COMPATIBLE_INTERFACE_NUMBER_MIN COMPATIBLE_INTERFACE_STRING COMPILE_DEFINITIONS COMPILE_DEFINITIONS_DEBUG COMPILE_DEFINITIONS_RELEASE COMPILE_FEATURES COMPILE_FLAGS COMPILE_OPTIONS COMPILE_PDB_NAME COMPILE_PDB_NAME_DEBUG COMPILE_PDB_NAME_RELEASE COMPILE_PDB_OUTPUT_DIRECTORY COMPILE_PDB_OUTPUT_DIRECTORY_DEBUG COMPILE_PDB_OUTPUT_DIRECTORY_RELEASE COST CPACK_DESKTOP_SHORTCUTS CPACK_NEVER_OVERWRITE CPACK_PERMANENT CPACK_STARTUP_SHORTCUTS CPACK_START_MENU_SHORTCUTS CPACK_WIX_ACL CROSSCOMPILING_EMULATOR CXX_EXTENSIONS CXX_STANDARD CXX_STANDARD_REQUIRED C_EXTENSIONS C_STANDARD C_STANDARD_REQUIRED DEBUG_CONFIGURATIONS DEBUG_POSTFIX DEFINE_SYMBOL DEFINITIONS DEPENDS DISABLED_FEATURES ECLIPSE_EXTRA_NATURES ENABLED_FEATURES ENABLED_LANGUAGES ENABLE_EXPORTS ENVIRONMENT EXCLUDE_FROM_ALL EXCLUDE_FROM_DEFAULT_BUILD EXCLUDE_FROM_DEFAULT_BUILD_DEBUG EXCLUDE_FROM_DEFAULT_BUILD_RELEASE EXPORT_NAME EXTERNAL_OBJECT EchoString FAIL_REGULAR_EXPRESSION FIND_LIBRARY_USE_LIB64_PATHS FIND_LIBRARY_USE_OPENBSD_VERSIONING FOLDER FRAMEWORK FRAMEWORK_VERSION Fortran_FORMAT Fortran_MODULE_DIRECTORY GENERATED GENERATOR_FILE_NAME GLOBAL_DEPENDS_DEBUG_MODE GLOBAL_DEPENDS_NO_CYCLES GNUtoMS HAS_CXX HEADER_FILE_ONLY HELPSTRING IMPLICIT_DEPENDS_INCLUDE_TRANSFORM IMPORTED IMPORTED_CONFIGURATIONS IMPORTED_IMPLIB IMPORTED_IMPLIB_DEBUG IMPORTED_IMPLIB_RELEASE IMPORTED_LINK_DEPENDENT_LIBRARIES IMPORTED_LINK_DEPENDENT_LIBRARIES_DEBUG IMPORTED_LINK_DEPENDENT_LIBRARIES_RELEASE IMPORTED_LINK_INTERFACE_LANGUAGES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE IMPORTED_LINK_INTERFACE_LIBRARIES IMPORTED_LINK_INTERFACE_LIBRARIES_DEBUG IMPORTED_LINK_INTERFACE_LIBRARIES_RELEASE IMPORTED_LINK_INTERFACE_MULTIPLICITY IMPORTED_LINK_INTERFACE_MULTIPLICITY_DEBUG IMPORTED_LINK_INTERFACE_MULTIPLICITY_RELEASE IMPORTED_LOCATION IMPORTED_LOCATION_DEBUG IMPORTED_LOCATION_RELEASE IMPORTED_NO_SONAME IMPORTED_NO_SONAME_DEBUG IMPORTED_NO_SONAME_RELEASE IMPORTED_SONAME IMPORTED_SONAME_DEBUG IMPORTED_SONAME_RELEASE IMPORT_PREFIX IMPORT_SUFFIX INCLUDE_DIRECTORIES INCLUDE_REGULAR_EXPRESSION INSTALL_NAME_DIR INSTALL_RPATH INSTALL_RPATH_USE_LINK_PATH INTERFACE_AUTOUIC_OPTIONS INTERFACE_COMPILE_DEFINITIONS INTERFACE_COMPILE_FEATURES INTERFACE_COMPILE_OPTIONS INTERFACE_INCLUDE_DIRECTORIES INTERFACE_LINK_LIBRARIES INTERFACE_POSITION_INDEPENDENT_CODE INTERFACE_SOURCES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES INTERPROCEDURAL_OPTIMIZATION INTERPROCEDURAL_OPTIMIZATION_DEBUG INTERPROCEDURAL_OPTIMIZATION_RELEASE IN_TRY_COMPILE JOB_POOLS JOB_POOL_COMPILE JOB_POOL_LINK KEEP_EXTENSION LABELS LANGUAGE LIBRARY_OUTPUT_DIRECTORY LIBRARY_OUTPUT_DIRECTORY_DEBUG LIBRARY_OUTPUT_DIRECTORY_RELEASE LIBRARY_OUTPUT_NAME LIBRARY_OUTPUT_NAME_DEBUG LIBRARY_OUTPUT_NAME_RELEASE LINKER_LANGUAGE LINK_DEPENDS LINK_DEPENDS_NO_SHARED LINK_DIRECTORIES LINK_FLAGS LINK_FLAGS_DEBUG LINK_FLAGS_RELEASE LINK_INTERFACE_LIBRARIES LINK_INTERFACE_LIBRARIES_DEBUG LINK_INTERFACE_LIBRARIES_RELEASE LINK_INTERFACE_MULTIPLICITY LINK_INTERFACE_MULTIPLICITY_DEBUG LINK_INTERFACE_MULTIPLICITY_RELEASE LINK_LIBRARIES LINK_SEARCH_END_STATIC LINK_SEARCH_START_STATIC LISTFILE_STACK LOCATION LOCATION_DEBUG LOCATION_RELEASE MACOSX_BUNDLE MACOSX_BUNDLE_INFO_PLIST MACOSX_FRAMEWORK_INFO_PLIST MACOSX_PACKAGE_LOCATION MACOSX_RPATH MACROS MAP_IMPORTED_CONFIG_DEBUG MAP_IMPORTED_CONFIG_RELEASE MEASUREMENT MODIFIED NAME NO_SONAME NO_SYSTEM_FROM_IMPORTED OBJECT_DEPENDS OBJECT_OUTPUTS OSX_ARCHITECTURES OSX_ARCHITECTURES_DEBUG OSX_ARCHITECTURES_RELEASE OUTPUT_NAME OUTPUT_NAME_DEBUG OUTPUT_NAME_RELEASE PACKAGES_FOUND PACKAGES_NOT_FOUND PARENT_DIRECTORY PASS_REGULAR_EXPRESSION PDB_NAME PDB_NAME_DEBUG PDB_NAME_RELEASE PDB_OUTPUT_DIRECTORY PDB_OUTPUT_DIRECTORY_DEBUG PDB_OUTPUT_DIRECTORY_RELEASE POSITION_INDEPENDENT_CODE POST_INSTALL_SCRIPT PREDEFINED_TARGETS_FOLDER PREFIX PRE_INSTALL_SCRIPT PRIVATE_HEADER PROCESSORS PROJECT_LABEL PUBLIC_HEADER REPORT_UNDEFINED_PROPERTIES REQUIRED_FILES RESOURCE RESOURCE_LOCK RULE_LAUNCH_COMPILE RULE_LAUNCH_CUSTOM RULE_LAUNCH_LINK RULE_MESSAGES RUNTIME_OUTPUT_DIRECTORY RUNTIME_OUTPUT_DIRECTORY_DEBUG RUNTIME_OUTPUT_DIRECTORY_RELEASE RUNTIME_OUTPUT_NAME RUNTIME_OUTPUT_NAME_DEBUG RUNTIME_OUTPUT_NAME_RELEASE RUN_SERIAL SKIP_BUILD_RPATH SKIP_RETURN_CODE SOURCES SOURCE_DIR SOVERSION STATIC_LIBRARY_FLAGS STATIC_LIBRARY_FLAGS_DEBUG STATIC_LIBRARY_FLAGS_RELEASE STRINGS SUFFIX SYMBOLIC TARGET_ARCHIVES_MAY_BE_SHARED_LIBS TARGET_MESSAGES TARGET_SUPPORTS_SHARED_LIBS TEST_INCLUDE_FILE TIMEOUT TYPE USE_FOLDERS VALUE VARIABLES VERSION VISIBILITY_INLINES_HIDDEN VS_DEPLOYMENT_CONTENT VS_DEPLOYMENT_LOCATION VS_DESKTOP_EXTENSIONS_VERSION VS_DOTNET_REFERENCES VS_DOTNET_TARGET_FRAMEWORK_VERSION VS_GLOBAL_KEYWORD VS_GLOBAL_PROJECT_TYPES VS_GLOBAL_ROOTNAMESPACE VS_IOT_EXTENSIONS_VERSION VS_IOT_STARTUP_TASK VS_KEYWORD VS_MOBILE_EXTENSIONS_VERSION VS_SCC_AUXPATH VS_SCC_LOCALPATH VS_SCC_PROJECTNAME VS_SCC_PROVIDER VS_SHADER_ENTRYPOINT VS_SHADER_FLAGS VS_SHADER_MODEL VS_SHADER_TYPE VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION VS_WINRT_COMPONENT VS_WINRT_EXTENSIONS VS_WINRT_REFERENCES VS_XAML_TYPE WILL_FAIL WIN32_EXECUTABLE WINDOWS_EXPORT_ALL_SYMBOLS WORKING_DIRECTORY WRAP_EXCLUDE XCODE_EXPLICIT_FILE_TYPE XCODE_LAST_KNOWN_FILE_TYPE XCTEST
+ \ ABSTRACT ADDITIONAL_MAKE_CLEAN_FILES ADVANCED ALIASED_TARGET ALLOW_DUPLICATE_CUSTOM_TARGETS ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID_API ANDROID_API_MIN ANDROID_ARCH ANDROID_ASSETS_DIRECTORIES ANDROID_GUI ANDROID_JAR_DEPENDENCIES ANDROID_JAR_DIRECTORIES ANDROID_JAVA_SOURCE_DIR ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID_NATIVE_LIB_DIRECTORIES ANDROID_PROCESS_MAX ANDROID_PROGUARD ANDROID_PROGUARD_CONFIG_PATH ANDROID_SECURE_PROPS_PATH ANDROID_SKIP_ANT_STEP ANDROID_STL_TYPE ARCHIVE_OUTPUT_DIRECTORY ARCHIVE_OUTPUT_NAME ATTACHED_FILES ATTACHED_FILES_ON_FAIL AUTOGEN_BUILD_DIR AUTOGEN_SOURCE_GROUP AUTOGEN_TARGETS_FOLDER AUTOGEN_TARGET_DEPENDS AUTOMOC AUTOMOC_DEPEND_FILTERS AUTOMOC_MACRO_NAMES AUTOMOC_MOC_OPTIONS AUTOMOC_SOURCE_GROUP AUTOMOC_TARGETS_FOLDER AUTORCC AUTORCC_OPTIONS AUTORCC_SOURCE_GROUP AUTOUIC AUTOUIC_OPTIONS AUTOUIC_SEARCH_PATHS BINARY_DIR BUILDSYSTEM_TARGETS BUILD_RPATH BUILD_WITH_INSTALL_NAME_DIR BUILD_WITH_INSTALL_RPATH BUNDLE BUNDLE_EXTENSION CACHE_VARIABLES CLEAN_NO_CUSTOM CMAKE_CONFIGURE_DEPENDS CMAKE_CXX_KNOWN_FEATURES CMAKE_C_KNOWN_FEATURES COMPATIBLE_INTERFACE_BOOL COMPATIBLE_INTERFACE_NUMBER_MAX COMPATIBLE_INTERFACE_NUMBER_MIN COMPATIBLE_INTERFACE_STRING COMPILE_DEFINITIONS COMPILE_FEATURES COMPILE_FLAGS COMPILE_OPTIONS COMPILE_PDB_NAME COMPILE_PDB_OUTPUT_DIRECTORY COST CPACK_DESKTOP_SHORTCUTS CPACK_NEVER_OVERWRITE CPACK_PERMANENT CPACK_STARTUP_SHORTCUTS CPACK_START_MENU_SHORTCUTS CPACK_WIX_ACL CROSSCOMPILING_EMULATOR CUDA_EXTENSIONS CUDA_PTX_COMPILATION CUDA_RESOLVE_DEVICE_SYMBOLS CUDA_SEPARABLE_COMPILATION CUDA_STANDARD CUDA_STANDARD_REQUIRED CXX_EXTENSIONS CXX_STANDARD CXX_STANDARD_REQUIRED C_EXTENSIONS C_STANDARD C_STANDARD_REQUIRED DEBUG_CONFIGURATIONS DEBUG_POSTFIX DEFINE_SYMBOL DEFINITIONS DEPENDS DEPLOYMENT_REMOTE_DIRECTORY DISABLED DISABLED_FEATURES ECLIPSE_EXTRA_NATURES ENABLED_FEATURES ENABLED_LANGUAGES ENABLE_EXPORTS ENVIRONMENT EXCLUDE_FROM_ALL EXCLUDE_FROM_DEFAULT_BUILD EXPORT_NAME EXTERNAL_OBJECT EchoString FAIL_REGULAR_EXPRESSION FIND_LIBRARY_USE_LIB32_PATHS FIND_LIBRARY_USE_LIB64_PATHS FIND_LIBRARY_USE_LIBX32_PATHS FIND_LIBRARY_USE_OPENBSD_VERSIONING FIXTURES_CLEANUP FIXTURES_REQUIRED FIXTURES_SETUP FOLDER FRAMEWORK FRAMEWORK_VERSION Fortran_FORMAT Fortran_MODULE_DIRECTORY GENERATED GENERATOR_FILE_NAME GENERATOR_IS_MULTI_CONFIG GLOBAL_DEPENDS_DEBUG_MODE GLOBAL_DEPENDS_NO_CYCLES GNUtoMS HAS_CXX HEADER_FILE_ONLY HELPSTRING IMPLICIT_DEPENDS_INCLUDE_TRANSFORM IMPORTED IMPORTED_CONFIGURATIONS IMPORTED_IMPLIB IMPORTED_LIBNAME IMPORTED_LINK_DEPENDENT_LIBRARIES IMPORTED_LINK_INTERFACE_LANGUAGES IMPORTED_LINK_INTERFACE_LIBRARIES IMPORTED_LINK_INTERFACE_MULTIPLICITY IMPORTED_LOCATION IMPORTED_NO_SONAME IMPORTED_OBJECTS IMPORTED_SONAME IMPORT_PREFIX IMPORT_SUFFIX INCLUDE_DIRECTORIES INCLUDE_REGULAR_EXPRESSION INSTALL_NAME_DIR INSTALL_RPATH INSTALL_RPATH_USE_LINK_PATH INTERFACE_AUTOUIC_OPTIONS INTERFACE_COMPILE_DEFINITIONS INTERFACE_COMPILE_FEATURES INTERFACE_COMPILE_OPTIONS INTERFACE_INCLUDE_DIRECTORIES INTERFACE_LINK_LIBRARIES INTERFACE_POSITION_INDEPENDENT_CODE INTERFACE_SOURCES INTERFACE_SYSTEM_INCLUDE_DIRECTORIES INTERPROCEDURAL_OPTIMIZATION IN_TRY_COMPILE IOS_INSTALL_COMBINED JOB_POOLS JOB_POOL_COMPILE JOB_POOL_LINK KEEP_EXTENSION LABELS LANGUAGE LIBRARY_OUTPUT_DIRECTORY LIBRARY_OUTPUT_NAME LINKER_LANGUAGE LINK_DEPENDS LINK_DEPENDS_NO_SHARED LINK_DIRECTORIES LINK_FLAGS LINK_INTERFACE_LIBRARIES LINK_INTERFACE_MULTIPLICITY LINK_LIBRARIES LINK_SEARCH_END_STATIC LINK_SEARCH_START_STATIC LINK_WHAT_YOU_USE LISTFILE_STACK LOCATION MACOSX_BUNDLE MACOSX_BUNDLE_INFO_PLIST MACOSX_FRAMEWORK_INFO_PLIST MACOSX_PACKAGE_LOCATION MACOSX_RPATH MACROS MANUALLY_ADDED_DEPENDENCIES MEASUREMENT MODIFIED NAME NO_SONAME NO_SYSTEM_FROM_IMPORTED OBJECT_DEPENDS OBJECT_OUTPUTS OSX_ARCHITECTURES OUTPUT_NAME PACKAGES_FOUND PACKAGES_NOT_FOUND PARENT_DIRECTORY PASS_REGULAR_EXPRESSION PDB_NAME PDB_OUTPUT_DIRECTORY POSITION_INDEPENDENT_CODE POST_INSTALL_SCRIPT PREDEFINED_TARGETS_FOLDER PREFIX PRE_INSTALL_SCRIPT PRIVATE_HEADER PROCESSORS PROJECT_LABEL PUBLIC_HEADER REPORT_UNDEFINED_PROPERTIES REQUIRED_FILES RESOURCE RESOURCE_LOCK RULE_LAUNCH_COMPILE RULE_LAUNCH_CUSTOM RULE_LAUNCH_LINK RULE_MESSAGES RUNTIME_OUTPUT_DIRECTORY RUNTIME_OUTPUT_NAME RUN_SERIAL SKIP_AUTOGEN SKIP_AUTOMOC SKIP_AUTORCC SKIP_AUTOUIC SKIP_BUILD_RPATH SKIP_RETURN_CODE SOURCES SOURCE_DIR SOVERSION STATIC_LIBRARY_FLAGS STRINGS SUBDIRECTORIES SUFFIX SYMBOLIC TARGET_ARCHIVES_MAY_BE_SHARED_LIBS TARGET_MESSAGES TARGET_SUPPORTS_SHARED_LIBS TEST_INCLUDE_FILE TEST_INCLUDE_FILES TIMEOUT TIMEOUT_AFTER_MATCH TYPE USE_FOLDERS VALUE VARIABLES VERSION VISIBILITY_INLINES_HIDDEN VS_CONFIGURATION_TYPE VS_COPY_TO_OUT_DIR VS_DEBUGGER_WORKING_DIRECTORY VS_DEPLOYMENT_CONTENT VS_DEPLOYMENT_LOCATION VS_DESKTOP_EXTENSIONS_VERSION VS_DOTNET_REFERENCES VS_DOTNET_REFERENCES_COPY_LOCAL VS_DOTNET_TARGET_FRAMEWORK_VERSION VS_GLOBAL_KEYWORD VS_GLOBAL_PROJECT_TYPES VS_GLOBAL_ROOTNAMESPACE VS_INCLUDE_IN_VSIX VS_IOT_EXTENSIONS_VERSION VS_IOT_STARTUP_TASK VS_KEYWORD VS_MOBILE_EXTENSIONS_VERSION VS_RESOURCE_GENERATOR VS_SCC_AUXPATH VS_SCC_LOCALPATH VS_SCC_PROJECTNAME VS_SCC_PROVIDER VS_SDK_REFERENCES VS_SHADER_ENTRYPOINT VS_SHADER_FLAGS VS_SHADER_MODEL VS_SHADER_TYPE VS_SHADER_OUTPUT_HEADER_FILE VS_SHADER_VARIABLE_NAME VS_STARTUP_PROJECT VS_TOOL_OVERRIDE VS_USER_PROPS VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION VS_WINRT_COMPONENT VS_WINRT_EXTENSIONS VS_WINRT_REFERENCES VS_XAML_TYPE WILL_FAIL WIN32_EXECUTABLE WINDOWS_EXPORT_ALL_SYMBOLS WORKING_DIRECTORY WRAP_EXCLUDE XCODE_EMIT_EFFECTIVE_PLATFORM_NAME XCODE_EXPLICIT_FILE_TYPE XCODE_FILE_ATTRIBUTES XCODE_LAST_KNOWN_FILE_TYPE XCODE_PRODUCT_TYPE XCTEST
syn keyword cmakeVariable contained
- \ ANDROID APPLE BORLAND BUILD_SHARED_LIBS CMAKE_ABSOLUTE_DESTINATION_FILES CMAKE_ANDROID_ANT_ADDITIONAL_OPTIONS CMAKE_ANDROID_API CMAKE_ANDROID_API_MIN CMAKE_ANDROID_ARCH CMAKE_ANDROID_ARCH_ABI CMAKE_ANDROID_ARM_MODE CMAKE_ANDROID_ARM_NEON CMAKE_ANDROID_ASSETS_DIRECTORIES CMAKE_ANDROID_GUI CMAKE_ANDROID_JAR_DEPENDENCIES CMAKE_ANDROID_JAR_DIRECTORIES CMAKE_ANDROID_JAVA_SOURCE_DIR CMAKE_ANDROID_NATIVE_LIB_DEPENDENCIES CMAKE_ANDROID_NATIVE_LIB_DIRECTORIES CMAKE_ANDROID_NDK CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION CMAKE_ANDROID_PROCESS_MAX CMAKE_ANDROID_PROGUARD CMAKE_ANDROID_PROGUARD_CONFIG_PATH CMAKE_ANDROID_SECURE_PROPS_PATH CMAKE_ANDROID_SKIP_ANT_STEP CMAKE_ANDROID_STANDALONE_TOOLCHAIN CMAKE_ANDROID_STL_TYPE CMAKE_APPBUNDLE_PATH CMAKE_AR CMAKE_ARCHIVE_OUTPUT_DIRECTORY CMAKE_ARGC CMAKE_ARGV0 CMAKE_AUTOMOC CMAKE_AUTOMOC_DEPEND_FILTERS CMAKE_AUTOMOC_MOC_OPTIONS CMAKE_AUTOMOC_RELAXED_MODE CMAKE_AUTORCC CMAKE_AUTORCC_OPTIONS CMAKE_AUTOUIC CMAKE_AUTOUIC_OPTIONS CMAKE_AUTOUIC_SEARCH_PATHS CMAKE_BACKWARDS_COMPATIBILITY CMAKE_BINARY_DIR CMAKE_BUILD_RPATH CMAKE_BUILD_TOOL CMAKE_BUILD_TYPE CMAKE_BUILD_WITH_INSTALL_NAME_DIR CMAKE_BUILD_WITH_INSTALL_RPATH CMAKE_CACHEFILE_DIR CMAKE_CACHE_MAJOR_VERSION CMAKE_CACHE_MINOR_VERSION CMAKE_CACHE_PATCH_VERSION CMAKE_CFG_INTDIR CMAKE_CL_64 CMAKE_CODELITE_USE_TARGETS CMAKE_COLOR_MAKEFILE CMAKE_COMMAND CMAKE_COMPILER_2005 CMAKE_COMPILER_IS_GNUCC CMAKE_COMPILER_IS_GNUCXX CMAKE_COMPILER_IS_GNUG77 CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY CMAKE_CONFIGURATION_TYPES CMAKE_CROSSCOMPILING CMAKE_CROSSCOMPILING_EMULATOR CMAKE_CTEST_COMMAND CMAKE_CUDA_EXTENSIONS CMAKE_CUDA_STANDARD CMAKE_CUDA_STANDARD_REQUIRED CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES CMAKE_CURRENT_BINARY_DIR CMAKE_CURRENT_LIST_DIR CMAKE_CURRENT_LIST_FILE CMAKE_CURRENT_LIST_LINE CMAKE_CURRENT_SOURCE_DIR CMAKE_CXX_COMPILE_FEATURES CMAKE_CXX_EXTENSIONS CMAKE_CXX_STANDARD CMAKE_CXX_STANDARD_REQUIRED CMAKE_C_COMPILE_FEATURES CMAKE_C_EXTENSIONS CMAKE_C_STANDARD CMAKE_C_STANDARD_REQUIRED CMAKE_DEBUG_POSTFIX CMAKE_DEBUG_TARGET_PROPERTIES CMAKE_DEPENDS_IN_PROJECT_ONLY CMAKE_DL_LIBS CMAKE_ECLIPSE_GENERATE_LINKED_RESOURCES CMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT CMAKE_ECLIPSE_MAKE_ARGUMENTS CMAKE_ECLIPSE_VERSION CMAKE_EDIT_COMMAND CMAKE_ENABLE_EXPORTS CMAKE_ERROR_DEPRECATED CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION CMAKE_EXECUTABLE_SUFFIX CMAKE_EXE_LINKER_FLAGS CMAKE_EXE_LINKER_FLAGS_INIT CMAKE_EXPORT_COMPILE_COMMANDS CMAKE_EXPORT_NO_PACKAGE_REGISTRY CMAKE_EXTRA_GENERATOR CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES CMAKE_FIND_APPBUNDLE CMAKE_FIND_FRAMEWORK CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX CMAKE_FIND_LIBRARY_PREFIXES CMAKE_FIND_LIBRARY_SUFFIXES CMAKE_FIND_NO_INSTALL_PREFIX CMAKE_FIND_PACKAGE_NAME CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY CMAKE_FIND_PACKAGE_SORT_DIRECTION CMAKE_FIND_PACKAGE_SORT_ORDER CMAKE_FIND_PACKAGE_WARN_NO_MODULE CMAKE_FIND_ROOT_PATH CMAKE_FIND_ROOT_PATH_MODE_INCLUDE CMAKE_FIND_ROOT_PATH_MODE_LIBRARY CMAKE_FIND_ROOT_PATH_MODE_PACKAGE CMAKE_FIND_ROOT_PATH_MODE_PROGRAM CMAKE_FRAMEWORK_PATH CMAKE_Fortran_FORMAT CMAKE_Fortran_MODDIR_DEFAULT CMAKE_Fortran_MODDIR_FLAG CMAKE_Fortran_MODOUT_FLAG CMAKE_Fortran_MODULE_DIRECTORY CMAKE_GENERATOR CMAKE_GENERATOR_PLATFORM CMAKE_GENERATOR_TOOLSET CMAKE_GNUtoMS CMAKE_HOME_DIRECTORY CMAKE_HOST_APPLE CMAKE_HOST_SOLARIS CMAKE_HOST_SYSTEM CMAKE_HOST_SYSTEM_NAME CMAKE_HOST_SYSTEM_PROCESSOR CMAKE_HOST_SYSTEM_VERSION CMAKE_HOST_UNIX CMAKE_HOST_WIN32 CMAKE_IGNORE_PATH CMAKE_IMPORT_LIBRARY_PREFIX CMAKE_IMPORT_LIBRARY_SUFFIX CMAKE_INCLUDE_CURRENT_DIR CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE CMAKE_INCLUDE_DIRECTORIES_BEFORE CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE CMAKE_INCLUDE_PATH CMAKE_INSTALL_DEFAULT_COMPONENT_NAME CMAKE_INSTALL_MESSAGE CMAKE_INSTALL_NAME_DIR CMAKE_INSTALL_PREFIX CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT CMAKE_INSTALL_RPATH CMAKE_INSTALL_RPATH_USE_LINK_PATH CMAKE_INTERNAL_PLATFORM_ABI CMAKE_INTERPROCEDURAL_OPTIMIZATION CMAKE_IOS_INSTALL_COMBINED CMAKE_JOB_POOL_COMPILE CMAKE_JOB_POOL_LINK CMAKE_LIBRARY_ARCHITECTURE CMAKE_LIBRARY_ARCHITECTURE_REGEX CMAKE_LIBRARY_OUTPUT_DIRECTORY CMAKE_LIBRARY_PATH CMAKE_LIBRARY_PATH_FLAG CMAKE_LINK_DEF_FILE_FLAG CMAKE_LINK_DEPENDS_NO_SHARED CMAKE_LINK_INTERFACE_LIBRARIES CMAKE_LINK_LIBRARY_FILE_FLAG CMAKE_LINK_LIBRARY_FLAG CMAKE_LINK_LIBRARY_SUFFIX CMAKE_LINK_SEARCH_END_STATIC CMAKE_LINK_SEARCH_START_STATIC CMAKE_LINK_WHAT_YOU_USE CMAKE_MACOSX_BUNDLE CMAKE_MACOSX_RPATH CMAKE_MAJOR_VERSION CMAKE_MAKE_PROGRAM CMAKE_MATCH_COUNT CMAKE_MFC_FLAG CMAKE_MINIMUM_REQUIRED_VERSION CMAKE_MINOR_VERSION CMAKE_MODULE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS_INIT CMAKE_MODULE_PATH CMAKE_NINJA_OUTPUT_PATH_PREFIX CMAKE_NOT_USING_CONFIG_FLAGS CMAKE_NO_BUILTIN_CHRPATH CMAKE_NO_SYSTEM_FROM_IMPORTED CMAKE_OBJECT_PATH_MAX CMAKE_OSX_ARCHITECTURES CMAKE_OSX_DEPLOYMENT_TARGET CMAKE_OSX_SYSROOT CMAKE_PARENT_LIST_FILE CMAKE_PATCH_VERSION CMAKE_PDB_OUTPUT_DIRECTORY CMAKE_POSITION_INDEPENDENT_CODE CMAKE_PREFIX_PATH CMAKE_PROGRAM_PATH CMAKE_PROJECT_DESCRIPTION CMAKE_PROJECT_NAME CMAKE_RANLIB CMAKE_ROOT CMAKE_RUNTIME_OUTPUT_DIRECTORY CMAKE_SCRIPT_MODE_FILE CMAKE_SHARED_LIBRARY_PREFIX CMAKE_SHARED_LIBRARY_SUFFIX CMAKE_SHARED_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS_INIT CMAKE_SHARED_MODULE_PREFIX CMAKE_SHARED_MODULE_SUFFIX CMAKE_SIZEOF_VOID_P CMAKE_SKIP_BUILD_RPATH CMAKE_SKIP_INSTALL_ALL_DEPENDENCY CMAKE_SKIP_INSTALL_RPATH CMAKE_SKIP_INSTALL_RULES CMAKE_SKIP_RPATH CMAKE_SOURCE_DIR CMAKE_STAGING_PREFIX CMAKE_STATIC_LIBRARY_PREFIX CMAKE_STATIC_LIBRARY_SUFFIX CMAKE_STATIC_LINKER_FLAGS CMAKE_STATIC_LINKER_FLAGS_INIT CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE CMAKE_SYSROOT CMAKE_SYSTEM CMAKE_SYSTEM_APPBUNDLE_PATH CMAKE_SYSTEM_FRAMEWORK_PATH CMAKE_SYSTEM_IGNORE_PATH CMAKE_SYSTEM_INCLUDE_PATH CMAKE_SYSTEM_LIBRARY_PATH CMAKE_SYSTEM_NAME CMAKE_SYSTEM_PREFIX_PATH CMAKE_SYSTEM_PROCESSOR CMAKE_SYSTEM_PROGRAM_PATH CMAKE_SYSTEM_VERSION CMAKE_Swift_LANGUAGE_VERSION CMAKE_TOOLCHAIN_FILE CMAKE_TRY_COMPILE_CONFIGURATION CMAKE_TRY_COMPILE_PLATFORM_VARIABLES CMAKE_TRY_COMPILE_TARGET_TYPE CMAKE_TWEAK_VERSION CMAKE_USER_MAKE_RULES_OVERRIDE CMAKE_USE_RELATIVE_PATHS CMAKE_VERBOSE_MAKEFILE CMAKE_VERSION CMAKE_VISIBILITY_INLINES_HIDDEN CMAKE_VS_DEVENV_COMMAND CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD CMAKE_VS_INTEL_Fortran_PROJECT_VERSION CMAKE_VS_MSBUILD_COMMAND CMAKE_VS_NsightTegra_VERSION CMAKE_VS_PLATFORM_NAME CMAKE_VS_PLATFORM_TOOLSET CMAKE_VS_PLATFORM_TOOLSET_CUDA CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION CMAKE_WARN_DEPRECATED CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION CMAKE_WIN32_EXECUTABLE CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS CMAKE_XCODE_GENERATE_SCHEME CMAKE_XCODE_PLATFORM_TOOLSET CPACK_ABSOLUTE_DESTINATION_FILES CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION CPACK_INCLUDE_TOPLEVEL_DIRECTORY CPACK_INSTALL_SCRIPT CPACK_PACKAGING_INSTALL_PREFIX CPACK_SET_DESTDIR CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION CTEST_BINARY_DIRECTORY CTEST_BUILD_COMMAND CTEST_BUILD_NAME CTEST_BZR_COMMAND CTEST_BZR_UPDATE_OPTIONS CTEST_CHANGE_ID CTEST_CHECKOUT_COMMAND CTEST_CONFIGURATION_TYPE CTEST_CONFIGURE_COMMAND CTEST_COVERAGE_COMMAND CTEST_COVERAGE_EXTRA_FLAGS CTEST_CURL_OPTIONS CTEST_CUSTOM_COVERAGE_EXCLUDE CTEST_CUSTOM_ERROR_EXCEPTION CTEST_CUSTOM_ERROR_MATCH CTEST_CUSTOM_ERROR_POST_CONTEXT CTEST_CUSTOM_ERROR_PRE_CONTEXT CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE CTEST_CUSTOM_MEMCHECK_IGNORE CTEST_CUSTOM_POST_MEMCHECK CTEST_CUSTOM_POST_TEST CTEST_CUSTOM_PRE_MEMCHECK CTEST_CUSTOM_PRE_TEST CTEST_CUSTOM_TEST_IGNORE CTEST_CUSTOM_WARNING_EXCEPTION CTEST_CUSTOM_WARNING_MATCH CTEST_CVS_CHECKOUT CTEST_CVS_COMMAND CTEST_CVS_UPDATE_OPTIONS CTEST_DROP_LOCATION CTEST_DROP_METHOD CTEST_DROP_SITE CTEST_DROP_SITE_CDASH CTEST_DROP_SITE_PASSWORD CTEST_DROP_SITE_USER CTEST_EXTRA_COVERAGE_GLOB CTEST_GIT_COMMAND CTEST_GIT_INIT_SUBMODULES CTEST_GIT_UPDATE_CUSTOM CTEST_GIT_UPDATE_OPTIONS CTEST_HG_COMMAND CTEST_HG_UPDATE_OPTIONS CTEST_MEMORYCHECK_COMMAND CTEST_MEMORYCHECK_COMMAND_OPTIONS CTEST_MEMORYCHECK_SANITIZER_OPTIONS CTEST_MEMORYCHECK_SUPPRESSIONS_FILE CTEST_MEMORYCHECK_TYPE CTEST_NIGHTLY_START_TIME CTEST_P4_CLIENT CTEST_P4_COMMAND CTEST_P4_OPTIONS CTEST_P4_UPDATE_OPTIONS CTEST_SCP_COMMAND CTEST_SITE CTEST_SOURCE_DIRECTORY CTEST_SVN_COMMAND CTEST_SVN_OPTIONS CTEST_SVN_UPDATE_OPTIONS CTEST_TEST_LOAD CTEST_TEST_TIMEOUT CTEST_TRIGGER_SITE CTEST_UPDATE_COMMAND CTEST_UPDATE_OPTIONS CTEST_UPDATE_VERSION_ONLY CTEST_USE_LAUNCHERS CYGWIN ENV EXECUTABLE_OUTPUT_PATH GHS-MULTI LIBRARY_OUTPUT_PATH MINGW MSVC MSVC10 MSVC11 MSVC12 MSVC14 MSVC60 MSVC70 MSVC71 MSVC80 MSVC90 MSVC_IDE MSVC_VERSION PROJECT_BINARY_DIR PROJECT_DESCRIPTION PROJECT_NAME PROJECT_SOURCE_DIR PROJECT_VERSION PROJECT_VERSION_MAJOR PROJECT_VERSION_MINOR PROJECT_VERSION_PATCH PROJECT_VERSION_TWEAK UNIX WIN32 WINCE WINDOWS_PHONE WINDOWS_STORE XCODE XCODE_VERSION
+ \ ANDROID APPLE BORLAND BUILD_SHARED_LIBS CMAKE_ABSOLUTE_DESTINATION_FILES CMAKE_ANDROID_ANT_ADDITIONAL_OPTIONS CMAKE_ANDROID_API CMAKE_ANDROID_API_MIN CMAKE_ANDROID_ARCH CMAKE_ANDROID_ARCH_ABI CMAKE_ANDROID_ARM_MODE CMAKE_ANDROID_ARM_NEON CMAKE_ANDROID_ASSETS_DIRECTORIES CMAKE_ANDROID_GUI CMAKE_ANDROID_JAR_DEPENDENCIES CMAKE_ANDROID_JAR_DIRECTORIES CMAKE_ANDROID_JAVA_SOURCE_DIR CMAKE_ANDROID_NATIVE_LIB_DEPENDENCIES CMAKE_ANDROID_NATIVE_LIB_DIRECTORIES CMAKE_ANDROID_NDK CMAKE_ANDROID_NDK_DEPRECATED_HEADERS CMAKE_ANDROID_NDK_TOOLCHAIN_HOST_TAG CMAKE_ANDROID_NDK_TOOLCHAIN_VERSION CMAKE_ANDROID_PROCESS_MAX CMAKE_ANDROID_PROGUARD CMAKE_ANDROID_PROGUARD_CONFIG_PATH CMAKE_ANDROID_SECURE_PROPS_PATH CMAKE_ANDROID_SKIP_ANT_STEP CMAKE_ANDROID_STANDALONE_TOOLCHAIN CMAKE_ANDROID_STL_TYPE CMAKE_APPBUNDLE_PATH CMAKE_AR CMAKE_ARCHIVE_OUTPUT_DIRECTORY CMAKE_ARGC CMAKE_ARGV0 CMAKE_AUTOMOC CMAKE_AUTOMOC_DEPEND_FILTERS CMAKE_AUTOMOC_MACRO_NAMES CMAKE_AUTOMOC_MOC_OPTIONS CMAKE_AUTOMOC_RELAXED_MODE CMAKE_AUTORCC CMAKE_AUTORCC_OPTIONS CMAKE_AUTOUIC CMAKE_AUTOUIC_OPTIONS CMAKE_AUTOUIC_SEARCH_PATHS CMAKE_BACKWARDS_COMPATIBILITY CMAKE_BINARY_DIR CMAKE_BUILD_RPATH CMAKE_BUILD_TOOL CMAKE_BUILD_TYPE CMAKE_BUILD_WITH_INSTALL_NAME_DIR CMAKE_BUILD_WITH_INSTALL_RPATH CMAKE_CACHEFILE_DIR CMAKE_CACHE_MAJOR_VERSION CMAKE_CACHE_MINOR_VERSION CMAKE_CACHE_PATCH_VERSION CMAKE_CFG_INTDIR CMAKE_CL_64 CMAKE_CODELITE_USE_TARGETS CMAKE_COLOR_MAKEFILE CMAKE_COMMAND CMAKE_COMPILER_2005 CMAKE_COMPILER_IS_GNUCC CMAKE_COMPILER_IS_GNUCXX CMAKE_COMPILER_IS_GNUG77 CMAKE_COMPILE_PDB_OUTPUT_DIRECTORY CMAKE_CONFIGURATION_TYPES CMAKE_CROSSCOMPILING CMAKE_CROSSCOMPILING_EMULATOR CMAKE_CTEST_COMMAND CMAKE_CUDA_EXTENSIONS CMAKE_CUDA_STANDARD CMAKE_CUDA_STANDARD_REQUIRED CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES CMAKE_CURRENT_BINARY_DIR CMAKE_CURRENT_LIST_DIR CMAKE_CURRENT_LIST_FILE CMAKE_CURRENT_LIST_LINE CMAKE_CURRENT_SOURCE_DIR CMAKE_CXX_COMPILE_FEATURES CMAKE_CXX_EXTENSIONS CMAKE_CXX_STANDARD CMAKE_CXX_STANDARD_REQUIRED CMAKE_C_COMPILE_FEATURES CMAKE_C_EXTENSIONS CMAKE_C_STANDARD CMAKE_C_STANDARD_REQUIRED CMAKE_DEBUG_POSTFIX CMAKE_DEBUG_TARGET_PROPERTIES CMAKE_DEPENDS_IN_PROJECT_ONLY CMAKE_DIRECTORY_LABELS CMAKE_DL_LIBS CMAKE_ECLIPSE_GENERATE_LINKED_RESOURCES CMAKE_ECLIPSE_GENERATE_SOURCE_PROJECT CMAKE_ECLIPSE_MAKE_ARGUMENTS CMAKE_ECLIPSE_VERSION CMAKE_EDIT_COMMAND CMAKE_ENABLE_EXPORTS CMAKE_ERROR_DEPRECATED CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION CMAKE_EXECUTABLE_SUFFIX CMAKE_EXE_LINKER_FLAGS CMAKE_EXE_LINKER_FLAGS_INIT CMAKE_EXPORT_COMPILE_COMMANDS CMAKE_EXPORT_NO_PACKAGE_REGISTRY CMAKE_EXTRA_GENERATOR CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES CMAKE_FIND_APPBUNDLE CMAKE_FIND_FRAMEWORK CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX CMAKE_FIND_LIBRARY_PREFIXES CMAKE_FIND_LIBRARY_SUFFIXES CMAKE_FIND_NO_INSTALL_PREFIX CMAKE_FIND_PACKAGE_NAME CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY CMAKE_FIND_PACKAGE_SORT_DIRECTION CMAKE_FIND_PACKAGE_SORT_ORDER CMAKE_FIND_PACKAGE_WARN_NO_MODULE CMAKE_FIND_ROOT_PATH CMAKE_FIND_ROOT_PATH_MODE_INCLUDE CMAKE_FIND_ROOT_PATH_MODE_LIBRARY CMAKE_FIND_ROOT_PATH_MODE_PACKAGE CMAKE_FIND_ROOT_PATH_MODE_PROGRAM CMAKE_FRAMEWORK_PATH CMAKE_Fortran_FORMAT CMAKE_Fortran_MODDIR_DEFAULT CMAKE_Fortran_MODDIR_FLAG CMAKE_Fortran_MODOUT_FLAG CMAKE_Fortran_MODULE_DIRECTORY CMAKE_GENERATOR CMAKE_GENERATOR_PLATFORM CMAKE_GENERATOR_TOOLSET CMAKE_GNUtoMS CMAKE_HOME_DIRECTORY CMAKE_HOST_APPLE CMAKE_HOST_SOLARIS CMAKE_HOST_SYSTEM CMAKE_HOST_SYSTEM_NAME CMAKE_HOST_SYSTEM_PROCESSOR CMAKE_HOST_SYSTEM_VERSION CMAKE_HOST_UNIX CMAKE_HOST_WIN32 CMAKE_IGNORE_PATH CMAKE_IMPORT_LIBRARY_PREFIX CMAKE_IMPORT_LIBRARY_SUFFIX CMAKE_INCLUDE_CURRENT_DIR CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE CMAKE_INCLUDE_DIRECTORIES_BEFORE CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE CMAKE_INCLUDE_PATH CMAKE_INSTALL_DEFAULT_COMPONENT_NAME CMAKE_INSTALL_MESSAGE CMAKE_INSTALL_NAME_DIR CMAKE_INSTALL_PREFIX CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT CMAKE_INSTALL_RPATH CMAKE_INSTALL_RPATH_USE_LINK_PATH CMAKE_INTERNAL_PLATFORM_ABI CMAKE_INTERPROCEDURAL_OPTIMIZATION CMAKE_IOS_INSTALL_COMBINED CMAKE_JOB_POOL_COMPILE CMAKE_JOB_POOL_LINK CMAKE_LIBRARY_ARCHITECTURE CMAKE_LIBRARY_ARCHITECTURE_REGEX CMAKE_LIBRARY_OUTPUT_DIRECTORY CMAKE_LIBRARY_PATH CMAKE_LIBRARY_PATH_FLAG CMAKE_LINK_DEF_FILE_FLAG CMAKE_LINK_DEPENDS_NO_SHARED CMAKE_LINK_INTERFACE_LIBRARIES CMAKE_LINK_LIBRARY_FILE_FLAG CMAKE_LINK_LIBRARY_FLAG CMAKE_LINK_LIBRARY_SUFFIX CMAKE_LINK_SEARCH_END_STATIC CMAKE_LINK_SEARCH_START_STATIC CMAKE_LINK_WHAT_YOU_USE CMAKE_MACOSX_BUNDLE CMAKE_MACOSX_RPATH CMAKE_MAJOR_VERSION CMAKE_MAKE_PROGRAM CMAKE_MATCH_COUNT CMAKE_MFC_FLAG CMAKE_MINIMUM_REQUIRED_VERSION CMAKE_MINOR_VERSION CMAKE_MODULE_LINKER_FLAGS CMAKE_MODULE_LINKER_FLAGS_INIT CMAKE_MODULE_PATH CMAKE_MSVCIDE_RUN_PATH CMAKE_NINJA_OUTPUT_PATH_PREFIX CMAKE_NOT_USING_CONFIG_FLAGS CMAKE_NO_BUILTIN_CHRPATH CMAKE_NO_SYSTEM_FROM_IMPORTED CMAKE_OBJECT_PATH_MAX CMAKE_OSX_ARCHITECTURES CMAKE_OSX_DEPLOYMENT_TARGET CMAKE_OSX_SYSROOT CMAKE_PARENT_LIST_FILE CMAKE_PATCH_VERSION CMAKE_PDB_OUTPUT_DIRECTORY CMAKE_POSITION_INDEPENDENT_CODE CMAKE_PREFIX_PATH CMAKE_PROGRAM_PATH CMAKE_PROJECT_DESCRIPTION CMAKE_PROJECT_NAME CMAKE_RANLIB CMAKE_ROOT CMAKE_RUNTIME_OUTPUT_DIRECTORY CMAKE_SCRIPT_MODE_FILE CMAKE_SHARED_LIBRARY_PREFIX CMAKE_SHARED_LIBRARY_SUFFIX CMAKE_SHARED_LINKER_FLAGS CMAKE_SHARED_LINKER_FLAGS_INIT CMAKE_SHARED_MODULE_PREFIX CMAKE_SHARED_MODULE_SUFFIX CMAKE_SIZEOF_VOID_P CMAKE_SKIP_BUILD_RPATH CMAKE_SKIP_INSTALL_ALL_DEPENDENCY CMAKE_SKIP_INSTALL_RPATH CMAKE_SKIP_INSTALL_RULES CMAKE_SKIP_RPATH CMAKE_SOURCE_DIR CMAKE_STAGING_PREFIX CMAKE_STATIC_LIBRARY_PREFIX CMAKE_STATIC_LIBRARY_SUFFIX CMAKE_STATIC_LINKER_FLAGS CMAKE_STATIC_LINKER_FLAGS_INIT CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE CMAKE_SYSROOT CMAKE_SYSROOT_COMPILE CMAKE_SYSROOT_LINK CMAKE_SYSTEM CMAKE_SYSTEM_APPBUNDLE_PATH CMAKE_SYSTEM_FRAMEWORK_PATH CMAKE_SYSTEM_IGNORE_PATH CMAKE_SYSTEM_INCLUDE_PATH CMAKE_SYSTEM_LIBRARY_PATH CMAKE_SYSTEM_NAME CMAKE_SYSTEM_PREFIX_PATH CMAKE_SYSTEM_PROCESSOR CMAKE_SYSTEM_PROGRAM_PATH CMAKE_SYSTEM_VERSION CMAKE_Swift_LANGUAGE_VERSION CMAKE_TOOLCHAIN_FILE CMAKE_TRY_COMPILE_CONFIGURATION CMAKE_TRY_COMPILE_PLATFORM_VARIABLES CMAKE_TRY_COMPILE_TARGET_TYPE CMAKE_TWEAK_VERSION CMAKE_USER_MAKE_RULES_OVERRIDE CMAKE_USE_RELATIVE_PATHS CMAKE_VERBOSE_MAKEFILE CMAKE_VERSION CMAKE_VISIBILITY_INLINES_HIDDEN CMAKE_VS_DEVENV_COMMAND CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD CMAKE_VS_INCLUDE_PACKAGE_TO_DEFAULT_BUILD CMAKE_VS_INTEL_Fortran_PROJECT_VERSION CMAKE_VS_MSBUILD_COMMAND CMAKE_VS_NsightTegra_VERSION CMAKE_VS_PLATFORM_NAME CMAKE_VS_PLATFORM_TOOLSET CMAKE_VS_PLATFORM_TOOLSET_CUDA CMAKE_VS_PLATFORM_TOOLSET_HOST_ARCHITECTURE CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION CMAKE_WARN_DEPRECATED CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION CMAKE_WIN32_EXECUTABLE CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS CMAKE_XCODE_GENERATE_SCHEME CMAKE_XCODE_PLATFORM_TOOLSET CPACK_ABSOLUTE_DESTINATION_FILES CPACK_COMPONENT_INCLUDE_TOPLEVEL_DIRECTORY CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION CPACK_INCLUDE_TOPLEVEL_DIRECTORY CPACK_INSTALL_SCRIPT CPACK_PACKAGING_INSTALL_PREFIX CPACK_SET_DESTDIR CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION CTEST_BINARY_DIRECTORY CTEST_BUILD_COMMAND CTEST_BUILD_NAME CTEST_BZR_COMMAND CTEST_BZR_UPDATE_OPTIONS CTEST_CHANGE_ID CTEST_CHECKOUT_COMMAND CTEST_CONFIGURATION_TYPE CTEST_CONFIGURE_COMMAND CTEST_COVERAGE_COMMAND CTEST_COVERAGE_EXTRA_FLAGS CTEST_CURL_OPTIONS CTEST_CUSTOM_COVERAGE_EXCLUDE CTEST_CUSTOM_ERROR_EXCEPTION CTEST_CUSTOM_ERROR_MATCH CTEST_CUSTOM_ERROR_POST_CONTEXT CTEST_CUSTOM_ERROR_PRE_CONTEXT CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE CTEST_CUSTOM_MEMCHECK_IGNORE CTEST_CUSTOM_POST_MEMCHECK CTEST_CUSTOM_POST_TEST CTEST_CUSTOM_PRE_MEMCHECK CTEST_CUSTOM_PRE_TEST CTEST_CUSTOM_TEST_IGNORE CTEST_CUSTOM_WARNING_EXCEPTION CTEST_CUSTOM_WARNING_MATCH CTEST_CVS_CHECKOUT CTEST_CVS_COMMAND CTEST_CVS_UPDATE_OPTIONS CTEST_DROP_LOCATION CTEST_DROP_METHOD CTEST_DROP_SITE CTEST_DROP_SITE_CDASH CTEST_DROP_SITE_PASSWORD CTEST_DROP_SITE_USER CTEST_EXTRA_COVERAGE_GLOB CTEST_GIT_COMMAND CTEST_GIT_INIT_SUBMODULES CTEST_GIT_UPDATE_CUSTOM CTEST_GIT_UPDATE_OPTIONS CTEST_HG_COMMAND CTEST_HG_UPDATE_OPTIONS CTEST_LABELS_FOR_SUBPROJECTS CTEST_MEMORYCHECK_COMMAND CTEST_MEMORYCHECK_COMMAND_OPTIONS CTEST_MEMORYCHECK_SANITIZER_OPTIONS CTEST_MEMORYCHECK_SUPPRESSIONS_FILE CTEST_MEMORYCHECK_TYPE CTEST_NIGHTLY_START_TIME CTEST_P4_CLIENT CTEST_P4_COMMAND CTEST_P4_OPTIONS CTEST_P4_UPDATE_OPTIONS CTEST_SCP_COMMAND CTEST_SITE CTEST_SOURCE_DIRECTORY CTEST_SVN_COMMAND CTEST_SVN_OPTIONS CTEST_SVN_UPDATE_OPTIONS CTEST_TEST_LOAD CTEST_TEST_TIMEOUT CTEST_TRIGGER_SITE CTEST_UPDATE_COMMAND CTEST_UPDATE_OPTIONS CTEST_UPDATE_VERSION_ONLY CTEST_USE_LAUNCHERS CYGWIN ENV EXECUTABLE_OUTPUT_PATH GHS-MULTI LIBRARY_OUTPUT_PATH MINGW MSVC MSVC10 MSVC11 MSVC12 MSVC14 MSVC60 MSVC70 MSVC71 MSVC80 MSVC90 MSVC_IDE MSVC_VERSION PROJECT_BINARY_DIR PROJECT_DESCRIPTION PROJECT_NAME PROJECT_SOURCE_DIR PROJECT_VERSION PROJECT_VERSION_MAJOR PROJECT_VERSION_MINOR PROJECT_VERSION_PATCH PROJECT_VERSION_TWEAK UNIX WIN32 WINCE WINDOWS_PHONE WINDOWS_STORE XCODE XCODE_VERSION
syn keyword cmakeModule contained
\ ExternalProject
syn keyword cmakeKWExternalProject contained
- \ ALGO BINARY_DIR BUILD_ALWAYS BUILD_BYPRODUCTS BUILD_COMMAND BUILD_IN_SOURCE CMAKE_ARGS CMAKE_CACHE_ARGS CMAKE_CACHE_DEFAULT_ARGS COMMENT CONFIGURE_COMMAND CVSROOT CVS_MODULE CVS_REPOSITORY CVS_TAG DEPENDEES DEPENDERS DEPENDS DOWNLOADED_FILE DOWNLOAD_COMMAND DOWNLOAD_DIR DOWNLOAD_NAME DOWNLOAD_NO_EXTRACT DOWNLOAD_NO_PROGRESS EP_BASE EP_INDEPENDENT_STEP_TARGETS EP_PREFIX EP_STEP_TARGETS EP_UPDATE_DISCONNECTED EXCLUDE_FROM_ALL FORCE GIT_CONFIG GIT_PROGRESS GIT_REMOTE_NAME GIT_REPOSITORY GIT_SHALLOW GIT_SUBMODULES GIT_TAG HG_REPOSITORY HG_TAG HTTP_HEADER HTTP_PASSWORD HTTP_USERNAME INDEPENDENT_STEP_TARGETS INSTALL_COMMAND INSTALL_DIR JOB_POOLS LIST_SEPARATOR LOG_BUILD LOG_CONFIGURE LOG_DOWNLOAD LOG_INSTALL LOG_TEST LOG_UPDATE NO_DEPENDS PATCH_COMMAND PREFIX PROPERTY SOURCE_DIR SOURCE_SUBDIR STAMP_DIR STEP_TARGETS SVN_PASSWORD SVN_REPOSITORY SVN_REVISION SVN_TRUST_CERT SVN_USERNAME TEST_AFTER_INSTALL TEST_BEFORE_INSTALL TEST_COMMAND TEST_EXCLUDE_FROM_MAIN TIMEOUT TLS_CAINFO TLS_VERIFY TMP_DIR UPDATE_COMMAND UPDATE_DISCONNECTED URL URL_HASH USES_TERMINAL_BUILD USES_TERMINAL_CONFIGURE USES_TERMINAL_DOWNLOAD USES_TERMINAL_INSTALL USES_TERMINAL_TEST USES_TERMINAL_UPDATE WORKING_DIRECTORY
+ \ ALGO AWS BINARY_DIR BUILD_ALWAYS BUILD_BYPRODUCTS BUILD_COMMAND BUILD_IN_SOURCE CMAKE_ARGS CMAKE_CACHE_ARGS CMAKE_CACHE_DEFAULT_ARGS CMAKE_TLS_CAINFO CMAKE_TLS_VERIFY COMMENT CONFIGURE_COMMAND CVS CVSROOT CVS_MODULE CVS_REPOSITORY CVS_TAG DEPENDEES DEPENDERS DEPENDS DOWNLOADED_FILE DOWNLOAD_COMMAND DOWNLOAD_DIR DOWNLOAD_NAME DOWNLOAD_NO_EXTRACT DOWNLOAD_NO_PROGRESS EP_BASE EP_INDEPENDENT_STEP_TARGETS EP_PREFIX EP_STEP_TARGETS EP_UPDATE_DISCONNECTED EXCLUDE_FROM_ALL FORCE GIT_CONFIG GIT_PROGRESS GIT_REMOTE_NAME GIT_REPOSITORY GIT_SHALLOW GIT_SUBMODULES GIT_TAG HG_REPOSITORY HG_TAG HTTP_HEADER HTTP_PASSWORD HTTP_USERNAME INDEPENDENT_STEP_TARGETS INSTALL_COMMAND INSTALL_DIR JOB_POOLS LIST_SEPARATOR LOG_ LOG_BUILD LOG_CONFIGURE LOG_DOWNLOAD LOG_INSTALL LOG_TEST LOG_UPDATE MAKE_EXE NAMES NOTE NO_DEPENDS PATCH_COMMAND PREFIX PROPERTY SOURCE_DIR SOURCE_SUBDIR STAMP_DIR STEP_TARGETS STRING SVN_PASSWORD SVN_REPOSITORY SVN_REVISION SVN_TRUST_CERT SVN_USERNAME TEST_AFTER_INSTALL TEST_BEFORE_INSTALL TEST_COMMAND TEST_EXCLUDE_FROM_MAIN TIMEOUT TLS_CAINFO TLS_VERIFY TMP_DIR TRUE UPDATE_COMMAND UPDATE_DISCONNECTED URL URL_HASH USES_TERMINAL_BUILD USES_TERMINAL_CONFIGURE USES_TERMINAL_DOWNLOAD USES_TERMINAL_INSTALL USES_TERMINAL_TEST USES_TERMINAL_UPDATE WORKING_DIRECTORY
syn keyword cmakeKWadd_compile_options contained
\ COMPILE_OPTIONS
@@ -60,10 +65,10 @@ syn keyword cmakeKWadd_dependencies contained
\ DEPENDS OBJECT_DEPENDS
syn keyword cmakeKWadd_executable contained
- \ ALIAS CONFIG EXCLUDE_FROM_ALL GLOBAL IMPORTED IMPORTED_ IMPORTED_LOCATION IMPORTED_LOCATION_ MACOSX_BUNDLE OUTPUT_NAME RUNTIME_OUTPUT_DIRECTORY TARGET
+ \ ALIAS CONFIG EXCLUDE_FROM_ALL GLOBAL HEADER_FILE_ONLY IMPORTED IMPORTED_ IMPORTED_LOCATION IMPORTED_LOCATION_ MACOSX_BUNDLE OUTPUT_NAME RUNTIME_OUTPUT_DIRECTORY TARGET
syn keyword cmakeKWadd_library contained
- \ ALIAS ARCHIVE_OUTPUT_DIRECTORY CLI CONFIG DLL EXCLUDE_FROM_ALL FRAMEWORK GLOBAL IMPORTED IMPORTED_ IMPORTED_LOCATION IMPORTED_LOCATION_ INTERFACE_ LIBRARY_OUTPUT_DIRECTORY MODULE OBJECT ON OUTPUT_NAME POSITION_INDEPENDENT_CODE POST_BUILD PRE_BUILD PRE_LINK RUNTIME_OUTPUT_DIRECTORY SHARED STATIC TARGET_OBJECTS UNKNOWN
+ \ ALIAS ARCHIVE_OUTPUT_DIRECTORY CLI CONFIG DLL EXCLUDE_FROM_ALL FRAMEWORK GLOBAL HEADER_FILE_ONLY IMPORTED IMPORTED_ IMPORTED_LOCATION IMPORTED_LOCATION_ INTERFACE_ LIBRARY_OUTPUT_DIRECTORY MODULE OBJECT ON OUTPUT_NAME POSITION_INDEPENDENT_CODE POST_BUILD PRE_BUILD PRE_LINK RUNTIME_OUTPUT_DIRECTORY SHARED STATIC TARGET_OBJECTS UNKNOWN
syn keyword cmakeKWadd_subdirectory contained
\ EXCLUDE_FROM_ALL
@@ -78,7 +83,7 @@ syn keyword cmakeKWbuild_name contained
\ CMAKE_CXX_COMPILER
syn keyword cmakeKWcmake_host_system_information contained
- \ AVAILABLE_PHYSICAL_MEMORY AVAILABLE_VIRTUAL_MEMORY FQDN HOSTNAME NUMBER_OF_LOGICAL_CORES NUMBER_OF_PHYSICAL_CORES QUERY RESULT TOTAL_PHYSICAL_MEMORY TOTAL_VIRTUAL_MEMORY
+ \ AVAILABLE_PHYSICAL_MEMORY AVAILABLE_VIRTUAL_MEMORY FQDN HAS_FPU HAS_MMX HAS_MMX_PLUS HAS_SERIAL_NUMBER HAS_SSE HAS_SSE_FP HAS_SSE_MMX HOSTNAME ID NUMBER_OF_LOGICAL_CORES NUMBER_OF_PHYSICAL_CORES OS_NAME OS_PLATFORM OS_RELEASE OS_VERSION PROCESSOR_DESCRIPTION PROCESSOR_NAME PROCESSOR_SERIAL_NUMBER QUERY RESULT TOTAL_PHYSICAL_MEMORY TOTAL_VIRTUAL_MEMORY
syn keyword cmakeKWcmake_minimum_required contained
\ FATAL_ERROR VERSION
@@ -105,7 +110,7 @@ syn keyword cmakeKWctest_coverage contained
\ APPEND BUILD CAPTURE_CMAKE_ERROR LABELS QUIET RETURN_VALUE
syn keyword cmakeKWctest_memcheck contained
- \ APPEND BUILD DEFECT_COUNT EXCLUDE EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD
+ \ APPEND BUILD DEFECT_COUNT EXCLUDE EXCLUDE_FIXTURE EXCLUDE_FIXTURE_CLEANUP EXCLUDE_FIXTURE_SETUP EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD
syn keyword cmakeKWctest_run_script contained
\ NEW_PROCESS RETURN_VALUE
@@ -114,10 +119,10 @@ syn keyword cmakeKWctest_start contained
\ APPEND QUIET TAG TRACK
syn keyword cmakeKWctest_submit contained
- \ API CDASH_UPLOAD CDASH_UPLOAD_TYPE CTEST_EXTRA_SUBMIT_FILES CTEST_NOTES_FILES FILES PARTS QUIET RETRY_COUNT RETRY_DELAY RETURN_VALUE
+ \ API CDASH_UPLOAD CDASH_UPLOAD_TYPE CTEST_EXTRA_SUBMIT_FILES CTEST_NOTES_FILES FILES HTTPHEADER PARTS QUIET RETRY_COUNT RETRY_DELAY RETURN_VALUE
syn keyword cmakeKWctest_test contained
- \ APPEND BUILD CAPTURE_CMAKE_ERROR CPU EXCLUDE EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD
+ \ APPEND BUILD CAPTURE_CMAKE_ERROR CPU EXCLUDE EXCLUDE_FIXTURE EXCLUDE_FIXTURE_CLEANUP EXCLUDE_FIXTURE_SETUP EXCLUDE_LABEL INCLUDE INCLUDE_LABEL OFF ON PARALLEL_LEVEL QUIET RETURN_VALUE SCHEDULE_RANDOM START STOP_TIME STRIDE TEST_LOAD
syn keyword cmakeKWctest_update contained
\ QUIET RETURN_VALUE SOURCE
@@ -135,7 +140,7 @@ syn keyword cmakeKWexec_program contained
\ ARGS OUTPUT_VARIABLE RETURN_VALUE
syn keyword cmakeKWexecute_process contained
- \ ANSI AUTO COMMAND ENCODING ERROR_FILE ERROR_QUIET ERROR_STRIP_TRAILING_WHITESPACE ERROR_VARIABLE INPUT_FILE NONE OEM OUTPUT_FILE OUTPUT_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE RESULT_VARIABLE TIMEOUT UTF VERBATIM WORKING_DIRECTORY
+ \ ANSI AUTO COMMAND ENCODING ERROR_FILE ERROR_QUIET ERROR_STRIP_TRAILING_WHITESPACE ERROR_VARIABLE INPUT_FILE NONE OEM OUTPUT_FILE OUTPUT_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE RESULTS_VARIABLE RESULT_VARIABLE TIMEOUT UTF VERBATIM WORKING_DIRECTORY
syn keyword cmakeKWexport contained
\ ANDROID_MK APPEND CONFIG EXPORT EXPORT_LINK_INTERFACE_LIBRARIES FILE IMPORTED IMPORTED_ NAMESPACE NDK OLD PACKAGE TARGETS
@@ -144,7 +149,7 @@ syn keyword cmakeKWexport_library_dependencies contained
\ APPEND EXPORT INCLUDE LINK_INTERFACE_LIBRARIES SET
syn keyword cmakeKWfile contained
- \ ALGO APPEND ASCII CMAKE_TLS_CAINFO CMAKE_TLS_VERIFY CONDITION CONFIG CONTENT COPY CR DESTINATION DIRECTORY_PERMISSIONS DOWNLOAD ENCODING EXCLUDE EXPECTED_HASH FILES_MATCHING FILE_PERMISSIONS FOLLOW_SYMLINKS FUNCTION GENERATE GLOB GLOB_RECURSE GUARD HASH HEX HTTPHEADER INACTIVITY_TIMEOUT INSTALL LENGTH_MAXIMUM LENGTH_MINIMUM LF LIMIT LIMIT_COUNT LIMIT_INPUT LIMIT_OUTPUT LIST_DIRECTORIES LOCK LOG MAKE_DIRECTORY NEWLINE_CONSUME NO_HEX_CONVERSION NO_SOURCE_PERMISSIONS OFFSET OLD PATTERN PROCESS READ REGEX RELATIVE RELATIVE_PATH RELEASE REMOVE REMOVE_RECURSE RENAME RESULT_VARIABLE SHOW_PROGRESS SORT SSL STATUS STRINGS TIMESTAMP TLS_CAINFO TLS_VERIFY TO_CMAKE_PATH TO_NATIVE_PATH UPLOAD USERPWD USE_SOURCE_PERMISSIONS UTC UTF WRITE
+ \ ALGO APPEND ASCII CMAKE_TLS_CAINFO CMAKE_TLS_VERIFY CONDITION CONFIG CONTENT COPY CR DESTINATION DIRECTORY_PERMISSIONS DOWNLOAD ENCODING EXCLUDE EXPECTED_HASH FILES_MATCHING FILE_PERMISSIONS FOLLOW_SYMLINKS FUNCTION GENERATE GLOB GLOB_RECURSE GUARD HASH HEX HTTPHEADER INACTIVITY_TIMEOUT INSTALL LENGTH_MAXIMUM LENGTH_MINIMUM LF LIMIT LIMIT_COUNT LIMIT_INPUT LIMIT_OUTPUT LIST_DIRECTORIES LOCK LOG MAKE_DIRECTORY NEWLINE_CONSUME NO_HEX_CONVERSION NO_SOURCE_PERMISSIONS OFFSET OLD PATTERN PROCESS READ REGEX RELATIVE RELATIVE_PATH RELEASE REMOVE REMOVE_RECURSE RENAME RESULT_VARIABLE SHOW_PROGRESS SSL STATUS STRINGS TIMESTAMP TLS_CAINFO TLS_VERIFY TO_CMAKE_PATH TO_NATIVE_PATH UPLOAD USERPWD USE_SOURCE_PERMISSIONS UTC UTF WRITE
syn keyword cmakeKWfind_file contained
\ CMAKE_FIND_ROOT_PATH_BOTH DOC DVAR HINTS INCLUDE NAMES NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_FIND_ROOT_PATH NO_CMAKE_PATH NO_CMAKE_SYSTEM_PATH NO_DEFAULT_PATH NO_SYSTEM_ENVIRONMENT_PATH ONLY_CMAKE_FIND_ROOT_PATH OS PATHS PATH_SUFFIXES VAR
@@ -203,6 +208,9 @@ syn keyword cmakeKWinclude_directories contained
syn keyword cmakeKWinclude_external_msproject contained
\ GUID MAP_IMPORTED_CONFIG_ PLATFORM TYPE WIX
+syn keyword cmakeKWinclude_guard contained
+ \ DIRECTORY GLOBAL TRUE __CURRENT_FILE_VAR__
+
syn keyword cmakeKWinstall contained
\ ARCHIVE BUNDLE CODE COMPONENT CONFIGURATIONS CVS DESTDIR DESTINATION DIRECTORY DIRECTORY_PERMISSIONS DLL EXCLUDE_FROM_ALL EXPORT EXPORT_ANDROID_MK EXPORT_LINK_INTERFACE_LIBRARIES FILES FILES_MATCHING FILE_PERMISSIONS FRAMEWORK GROUP_EXECUTE GROUP_READ GROUP_WRITE IMPORTED_ INCLUDES INSTALL_PREFIX INTERFACE_INCLUDE_DIRECTORIES LIBRARY MACOSX_BUNDLE MESSAGE_NEVER NAMELINK_ONLY NAMELINK_SKIP NAMESPACE NDK OBJECTS OPTIONAL OWNER_EXECUTE OWNER_READ OWNER_WRITE PATTERN PERMISSIONS POST_INSTALL_SCRIPT PRE_INSTALL_SCRIPT PRIVATE_HEADER PROGRAMS PUBLIC_HEADER REGEX RENAME RESOURCE RUNTIME SCRIPT SETGID SETUID SOVERSION TARGETS TRUE USE_SOURCE_PERMISSIONS VERSION WORLD_EXECUTE WORLD_READ WORLD_WRITE
@@ -273,7 +281,7 @@ syn keyword cmakeKWsource_group contained
\ FILES PREFIX REGULAR_EXPRESSION TREE
syn keyword cmakeKWstring contained
- \ ALPHABET APPEND ASCII CMAKE_MATCH_ COMPARE CONCAT CONFIGURE EQUAL ESCAPE_QUOTES FIND GENEX_STRIP GREATER GREATER_EQUAL GUID HASH LENGTH LESS LESS_EQUAL MAKE_C_IDENTIFIER MATCH MATCHALL MATCHES NAMESPACE NOTEQUAL ONLY RANDOM RANDOM_SEED REGEX REPLACE REVERSE RFC SHA SOURCE_DATE_EPOCH STRIP SUBSTRING SZ TIMESTAMP TOLOWER TOUPPER TYPE US UTC UUID
+ \ ALPHABET APPEND ASCII CMAKE_MATCH_ COMPARE CONCAT CONFIGURE EQUAL ESCAPE_QUOTES FIND GENEX_STRIP GREATER GREATER_EQUAL GUID HASH LENGTH LESS LESS_EQUAL MAKE_C_IDENTIFIER MATCH MATCHALL MATCHES NAMESPACE NOTEQUAL ONLY PREPEND RANDOM RANDOM_SEED REGEX REPLACE REVERSE RFC SHA SOURCE_DATE_EPOCH STRIP SUBSTRING SZ TIMESTAMP TOLOWER TOUPPER TYPE US UTC UUID
syn keyword cmakeKWsubdirs contained
\ EXCLUDE_FROM_ALL PREORDER
@@ -327,7 +335,7 @@ syn keyword cmakeGeneratorExpressions contained
syn case ignore
syn keyword cmakeCommand
- \ add_compile_options add_custom_command add_custom_target add_definitions add_dependencies add_executable add_library add_subdirectory add_test aux_source_directory break build_command cmake_host_system_information cmake_minimum_required cmake_parse_arguments cmake_policy configure_file continue create_test_sourcelist ctest_build ctest_configure ctest_coverage ctest_empty_binary_directory ctest_memcheck ctest_read_custom_files ctest_run_script ctest_sleep ctest_start ctest_submit ctest_test ctest_update ctest_upload define_property enable_language enable_testing endfunction endmacro execute_process export file find_file find_library find_package find_path find_program fltk_wrap_ui function get_cmake_property get_directory_property get_filename_component get_property get_source_file_property get_target_property get_test_property include include_directories include_external_msproject include_regular_expression install link_directories list load_cache load_command macro mark_as_advanced math message option project qt_wrap_cpp qt_wrap_ui remove_definitions return separate_arguments set set_directory_properties set_property set_source_files_properties set_target_properties set_tests_properties site_name source_group string target_compile_definitions target_compile_features target_compile_options target_include_directories target_link_libraries target_sources try_compile try_run unset variable_watch
+ \ add_compile_options add_custom_command add_custom_target add_definitions add_dependencies add_executable add_library add_subdirectory add_test aux_source_directory break build_command cmake_host_system_information cmake_minimum_required cmake_parse_arguments cmake_policy configure_file continue create_test_sourcelist ctest_build ctest_configure ctest_coverage ctest_empty_binary_directory ctest_memcheck ctest_read_custom_files ctest_run_script ctest_sleep ctest_start ctest_submit ctest_test ctest_update ctest_upload define_property enable_language enable_testing endfunction endmacro execute_process export file find_file find_library find_package find_path find_program fltk_wrap_ui function get_cmake_property get_directory_property get_filename_component get_property get_source_file_property get_target_property get_test_property include include_directories include_external_msproject include_guard include_regular_expression install link_directories list load_cache load_command macro mark_as_advanced math message option project qt_wrap_cpp qt_wrap_ui remove_definitions return separate_arguments set set_directory_properties set_property set_source_files_properties set_target_properties set_tests_properties site_name source_group string target_compile_definitions target_compile_features target_compile_options target_include_directories target_link_libraries target_sources try_compile try_run unset variable_watch
\ nextgroup=cmakeArguments
syn keyword cmakeCommandConditional
@@ -420,6 +428,7 @@ hi def link cmakeKWif ModeMsg
hi def link cmakeKWinclude ModeMsg
hi def link cmakeKWinclude_directories ModeMsg
hi def link cmakeKWinclude_external_msproject ModeMsg
+hi def link cmakeKWinclude_guard ModeMsg
hi def link cmakeKWinstall ModeMsg
hi def link cmakeKWinstall_files ModeMsg
hi def link cmakeKWinstall_programs ModeMsg
@@ -461,3 +470,8 @@ hi def link cmakeKWwhile ModeMsg
hi def link cmakeKWwrite_file ModeMsg
let b:current_syntax = "cmake"
+
+let &cpo = s:keepcpo
+unlet s:keepcpo
+
+"EOF"
diff --git a/CMakeCPack.cmake b/CMakeCPack.cmake
index a0aacb465..dc9f0bae6 100644
--- a/CMakeCPack.cmake
+++ b/CMakeCPack.cmake
@@ -245,5 +245,23 @@ configure_file("${CMake_SOURCE_DIR}/CMakeCPackOptions.cmake.in"
"${CMake_BINARY_DIR}/CMakeCPackOptions.cmake" @ONLY)
set(CPACK_PROJECT_CONFIG_FILE "${CMake_BINARY_DIR}/CMakeCPackOptions.cmake")
+set(CPACK_SOURCE_IGNORE_FILES
+ # Files specific to version control.
+ "/\\\\.git/"
+ "/\\\\.gitattributes$"
+ "/\\\\.github/"
+ "/\\\\.gitignore$"
+ "/\\\\.hooks-config$"
+
+ # Cygwin package build.
+ "/\\\\.build/"
+
+ # Temporary files.
+ "\\\\.swp$"
+ "\\\\.#"
+ "/#"
+ "~$"
+ )
+
# include CPack model once all variables are set
include(CPack)
diff --git a/CMakeCPackOptions.cmake.in b/CMakeCPackOptions.cmake.in
index ad0c24586..a08c97d04 100644
--- a/CMakeCPackOptions.cmake.in
+++ b/CMakeCPackOptions.cmake.in
@@ -208,12 +208,6 @@ if(CPACK_GENERATOR MATCHES "IFW")
endif()
-if(CPACK_GENERATOR MATCHES "CygwinSource")
- # when packaging source make sure the .build directory is not included
- set(CPACK_SOURCE_IGNORE_FILES
- "/CVS/" "/\\.build/" "/\\.svn/" "\\.swp$" "\\.#" "/#" "~$")
-endif()
-
if("${CPACK_GENERATOR}" STREQUAL "PackageMaker")
if(CMAKE_PACKAGE_QTGUI)
set(CPACK_PACKAGE_DEFAULT_LOCATION "/Applications")
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ed924eb4e..f14f62f6b 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,13 +1,7 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
-cmake_minimum_required(VERSION 2.8.12.2 FATAL_ERROR)
-if(POLICY CMP0025)
- cmake_policy(SET CMP0025 NEW)
-endif()
-if(POLICY CMP0053)
- cmake_policy(SET CMP0053 NEW)
-endif()
+cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
project(CMake)
# Make sure we can find internal find_package modules only used for
@@ -21,6 +15,14 @@ if(CMAKE_BOOTSTRAP)
endif()
if(NOT CMake_TEST_EXTERNAL_CMAKE)
+ if(CMAKE_SYSTEM_NAME STREQUAL "HP-UX")
+ message(FATAL_ERROR
+ "CMake no longer compiles on HP-UX. See\n"
+ " https://gitlab.kitware.com/cmake/cmake/issues/17137\n"
+ "Use CMake 3.9 or lower instead."
+ )
+ endif()
+
set(CMake_BIN_DIR ${CMake_BINARY_DIR}/bin)
endif()
@@ -72,6 +74,10 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
# check for available C++ features
include(${CMake_SOURCE_DIR}/Source/Checks/cm_cxx_features.cmake)
+
+ if(NOT CMake_HAVE_CXX_UNIQUE_PTR)
+ message(FATAL_ERROR "The C++ compiler does not support C++11 (e.g. std::unique_ptr).")
+ endif()
endif()
# set the internal encoding of CMake to UTF-8
@@ -244,6 +250,12 @@ if(CMake_RUN_CLANG_TIDY)
message(FATAL_ERROR "CMake_RUN_CLANG_TIDY is ON but clang-tidy is not found!")
endif()
set(CMAKE_CXX_CLANG_TIDY "${CLANG_TIDY_COMMAND}")
+
+ # provide definitions for targets that require a rebuild once .clang-tidy changes
+ file(SHA1 ${CMAKE_CURRENT_SOURCE_DIR}/.clang-tidy clang_tidy_sha1)
+ set(CLANG_TIDY_DEFINITIONS "CLANG_TIDY_SHA1=${clang_tidy_sha1}")
+ unset(clang_tidy_sha1)
+
endif()
configure_file(.clang-tidy .clang-tidy COPYONLY)
@@ -333,11 +345,7 @@ macro (CMAKE_BUILD_UTILITIES)
endif()
if(CMAKE_USE_SYSTEM_LIBRHASH)
- if(NOT CMAKE_VERSION VERSION_LESS 3.0)
- find_package(LibRHash)
- else()
- message(FATAL_ERROR "CMAKE_USE_SYSTEM_LIBRHASH requires CMake >= 3.0")
- endif()
+ find_package(LibRHash)
if(NOT LibRHash_FOUND)
message(FATAL_ERROR
"CMAKE_USE_SYSTEM_LIBRHASH is ON but LibRHash is not found!")
@@ -503,11 +511,7 @@ macro (CMAKE_BUILD_UTILITIES)
#---------------------------------------------------------------------
# Build jsoncpp library.
if(CMAKE_USE_SYSTEM_JSONCPP)
- if(NOT CMAKE_VERSION VERSION_LESS 3.0)
- find_package(JsonCpp)
- else()
- message(FATAL_ERROR "CMAKE_USE_SYSTEM_JSONCPP requires CMake >= 3.0")
- endif()
+ find_package(JsonCpp)
if(NOT JsonCpp_FOUND)
message(FATAL_ERROR
"CMAKE_USE_SYSTEM_JSONCPP is ON but a JsonCpp is not found!")
@@ -521,45 +525,17 @@ macro (CMAKE_BUILD_UTILITIES)
#---------------------------------------------------------------------
# Build libuv library.
- if(NOT DEFINED CMAKE_USE_LIBUV)
- set(CMAKE_USE_LIBUV 1)
- if(APPLE)
- include(CheckCSourceCompiles)
- check_c_source_compiles("
-#include <CoreServices/CoreServices.h>
-#include <AvailabilityMacros.h>
-#ifndef MAC_OS_X_VERSION_10_5
-#error \"MAC_OS_X_VERSION_10_5 is not defined\"
-#endif
-int main(void) { return 0; }
-" HAVE_CoreServices_OS_X_10_5)
- if(NOT HAVE_CoreServices_OS_X_10_5)
- set(CMAKE_USE_LIBUV 0)
- endif()
- elseif(CMAKE_SYSTEM_NAME STREQUAL "HP-UX")
- # Disable until it can be ported.
- set(CMAKE_USE_LIBUV 0)
- endif()
- endif()
- if(CMAKE_USE_LIBUV)
- if(CMAKE_USE_SYSTEM_LIBUV)
- if(NOT CMAKE_VERSION VERSION_LESS 3.0)
- find_package(LibUV 1.0.0)
- else()
- message(FATAL_ERROR "CMAKE_USE_SYSTEM_LIBUV requires CMake >= 3.0")
- endif()
- if(NOT LIBUV_FOUND)
- message(FATAL_ERROR
- "CMAKE_USE_SYSTEM_LIBUV is ON but a libuv is not found!")
- endif()
- set(CMAKE_LIBUV_LIBRARIES LibUV::LibUV)
- else()
- set(CMAKE_LIBUV_LIBRARIES cmlibuv)
- add_subdirectory(Utilities/cmlibuv)
- CMAKE_SET_TARGET_FOLDER(cmlibuv "Utilities/3rdParty")
+ if(CMAKE_USE_SYSTEM_LIBUV)
+ find_package(LibUV 1.0.0)
+ if(NOT LIBUV_FOUND)
+ message(FATAL_ERROR
+ "CMAKE_USE_SYSTEM_LIBUV is ON but a libuv is not found!")
endif()
+ set(CMAKE_LIBUV_LIBRARIES LibUV::LibUV)
else()
- set(CMAKE_LIBUV_LIBRARIES)
+ set(CMAKE_LIBUV_LIBRARIES cmlibuv)
+ add_subdirectory(Utilities/cmlibuv)
+ CMAKE_SET_TARGET_FOLDER(cmlibuv "Utilities/3rdParty")
endif()
#---------------------------------------------------------------------
@@ -748,31 +724,6 @@ endif()
# setup some Testing support (a macro defined in this file)
CMAKE_SETUP_TESTING()
-# Check whether to build server mode or not:
-if(NOT CMake_TEST_EXTERNAL_CMAKE)
- if(NOT DEFINED CMake_ENABLE_SERVER_MODE)
- list(FIND CMAKE_CXX_COMPILE_FEATURES cxx_auto_type CMake_HAVE_CXX_AUTO_TYPE)
- list(FIND CMAKE_CXX_COMPILE_FEATURES cxx_range_for CMake_HAVE_CXX_RANGE_FOR)
- if(CMAKE_USE_LIBUV
- AND CMake_HAVE_CXX_AUTO_TYPE
- AND CMake_HAVE_CXX_MAKE_UNIQUE
- AND CMake_HAVE_CXX_RANGE_FOR
- )
- set(CMake_ENABLE_SERVER_MODE 1)
- else()
- set(CMake_ENABLE_SERVER_MODE 0)
- endif()
- endif()
- if(CMake_ENABLE_SERVER_MODE AND NOT CMAKE_USE_LIBUV)
- message(FATAL_ERROR "The server mode requires libuv!")
- endif()
-else()
- set(CMake_ENABLE_SERVER_MODE 0)
-endif()
-if(NOT DEFINED CMake_TEST_SERVER_MODE)
- set(CMake_TEST_SERVER_MODE ${CMake_ENABLE_SERVER_MODE})
-endif()
-
if(NOT CMake_TEST_EXTERNAL_CMAKE)
if(NOT CMake_VERSION_IS_RELEASE)
if(CMAKE_C_COMPILER_ID STREQUAL "GNU" AND
@@ -808,6 +759,9 @@ add_subdirectory(Tests)
if(NOT CMake_TEST_EXTERNAL_CMAKE)
if(BUILD_TESTING)
CMAKE_SET_TARGET_FOLDER(CMakeLibTests "Tests")
+ IF(TARGET CMakeServerLibTests)
+ CMAKE_SET_TARGET_FOLDER(CMakeServerLibTests "Tests")
+ ENDIF()
endif()
if(TARGET documentation)
CMAKE_SET_TARGET_FOLDER(documentation "Documentation")
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst
index e2197632a..381769d16 100644
--- a/CONTRIBUTING.rst
+++ b/CONTRIBUTING.rst
@@ -27,9 +27,13 @@ To contribute patches:
#. Run `Utilities/SetupForDevelopment.sh`_ for local configuration.
#. See the `CMake Source Code Guide`_ for coding guidelines.
#. Base all new work on the upstream ``master`` branch.
-#. Create commits making incremental, distinct, logically complete changes.
+ Base work on the upstream ``release`` branch only if it fixes a
+ regression or bug in a feature new to that release.
+#. Create commits making incremental, distinct, logically complete changes
+ with appropriate `commit messages`_.
#. Push a topic branch to a personal repository fork on GitLab.
-#. Create a GitLab Merge Request targeting the upstream ``master`` branch.
+#. Create a GitLab Merge Request targeting the upstream ``master`` branch
+ (even if the change is intended for merge to the ``release`` branch).
The merge request will enter the `CMake Review Process`_ for consideration.
@@ -37,6 +41,7 @@ The merge request will enter the `CMake Review Process`_ for consideration.
.. _`CMake Repository`: https://gitlab.kitware.com/cmake/cmake
.. _`Utilities/SetupForDevelopment.sh`: Utilities/SetupForDevelopment.sh
.. _`CMake Source Code Guide`: Help/dev/source.rst
+.. _`commit messages`: Help/dev/review.rst#commit-messages
.. _`CMake Review Process`: Help/dev/review.rst
License
diff --git a/CTestCustom.cmake.in b/CTestCustom.cmake.in
index fa2fbe35c..0e4e9fe15 100644
--- a/CTestCustom.cmake.in
+++ b/CTestCustom.cmake.in
@@ -44,6 +44,8 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
"Warning: LINN32: Last line.*is less.*"
"Warning: Olimit was exceeded on function.*"
"Warning: To override Olimit for all functions in file.*"
+ "Warning: Function .* can throw only the exceptions thrown by the function .* it overrides\\."
+ "WarningMessagesDialog\\.cxx"
"warning.*directory name.*CMake-Xcode.*/bin/.*does not exist.*"
"stl_deque.h:1051"
"(Lexer|Parser).*warning.*conversion.*may (alter its value|change the sign)"
@@ -68,11 +70,11 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
"cm(StringCommand|CTestTestHandler)\\.cxx.*warning.*srand.*seed choices are.*poor" # we do not do crypto
"IPA warning: function.*multiply defined in"
- # Ignore clang's summary warning, assuming prior text has matched some
+ # Ignore compiler summary warning, assuming prior text has matched some
# other warning expression:
- "[0-9,]+ warnings? generated."
- # similarly for PGI
- "compilation completed with warnings"
+ "[0-9,]+ warnings? generated." # Clang
+ "compilation completed with warnings" # PGI
+ "[0-9]+ Warning\\(s\\) detected" # SunPro
# scanbuild exceptions
"char_traits.h:.*: warning: Null pointer argument in call to string length function"
diff --git a/CompileFlags.cmake b/CompileFlags.cmake
index 7a9d4cdf3..9834b04d8 100644
--- a/CompileFlags.cmake
+++ b/CompileFlags.cmake
@@ -37,18 +37,6 @@ if(CMAKE_SYSTEM MATCHES "OSF1-V")
endif()
endif()
-if(CMAKE_SYSTEM_NAME MATCHES "HP-UX" AND CMAKE_CXX_COMPILER_ID MATCHES "HP")
- # HP aCC since version 3.80 supports the flag +hpxstd98 to get ANSI C++98
- # template support. It is known that version 6.25 doesn't need that flag.
- # Versions prior to 3.80 will not be able to build CMake. Current assumption:
- # it is needed for every version from 3.80 to 4 to get it working.
- if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4 AND
- NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.80)
- # use new C++ library and improved template support
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -AA +hpxstd98")
- endif()
-endif()
-
# Workaround for short jump tables on PA-RISC
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^parisc")
if(CMAKE_COMPILER_IS_GNUCC)
diff --git a/Copyright.txt b/Copyright.txt
index 33201080d..3c92a815b 100644
--- a/Copyright.txt
+++ b/Copyright.txt
@@ -34,6 +34,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The following individuals and institutions are among the Contributors:
* Aaron C. Meadows <cmake@shadowguarddev.com>
+* Adriaan de Groot <groot@kde.org>
* Aleksey Avdeev <solo@altlinux.ru>
* Alexander Neundorf <neundorf@kde.org>
* Alexander Smorkalov <alexander.smorkalov@itseez.com>
@@ -75,6 +76,7 @@ The following individuals and institutions are among the Contributors:
* Nicolas Bock <nicolasbock@gmail.com>
* Nicolas Despres <nicolas.despres@gmail.com>
* Nikita Krupen'ko <krnekit@gmail.com>
+* NVIDIA Corporation <www.nvidia.com>
* OpenGamma Ltd. <opengamma.com>
* Per Øyvind Karlsen <peroyvind@mandriva.org>
* Peter Collingbourne <peter@pcc.me.uk>
diff --git a/Help/command/add_custom_command.rst b/Help/command/add_custom_command.rst
index d03840633..1b0aa1465 100644
--- a/Help/command/add_custom_command.rst
+++ b/Help/command/add_custom_command.rst
@@ -225,3 +225,13 @@ of the following is specified:
:command:`add_custom_target` command.
``POST_BUILD``
Run after all other rules within the target have been executed.
+
+.. note::
+ Because generator expressions can be used in custom commands,
+ it is possible to define ``COMMAND`` lines or whole custom commands
+ which evaluate to empty strings for certain configurations.
+ For **Visual Studio 2010 (and newer)** generators these command
+ lines or custom commands will be omitted for the specific
+ configuration and no "empty-string-command" will be added.
+
+ This allows to add individual build events for every configuration.
diff --git a/Help/command/cmake_host_system_information.rst b/Help/command/cmake_host_system_information.rst
index 9402d57e9..7199874ce 100644
--- a/Help/command/cmake_host_system_information.rst
+++ b/Help/command/cmake_host_system_information.rst
@@ -13,13 +13,34 @@ queried. The list of queried values is stored in ``<variable>``.
``<key>`` can be one of the following values:
-::
-
- 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 megabytes.
- AVAILABLE_VIRTUAL_MEMORY = Available virtual memory in megabytes.
- TOTAL_PHYSICAL_MEMORY = Total physical memory in megabytes.
- AVAILABLE_PHYSICAL_MEMORY = Available physical memory in megabytes.
+============================= ================================================
+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 megabytes
+``AVAILABLE_VIRTUAL_MEMORY`` Available virtual memory in megabytes
+``TOTAL_PHYSICAL_MEMORY`` Total physical memory in megabytes
+``AVAILABLE_PHYSICAL_MEMORY`` Available physical memory in megabytes
+``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 porcessor supports Ext. MMX instructions
+``HAS_SSE`` One if porcessor supports SSE instructions
+``HAS_SSE2`` One if porcessor supports SSE2 instructions
+``HAS_SSE_FP`` One if porcessor supports SSE FP instructions
+``HAS_SSE_MMX`` One if porcessor supports SSE MMX instructions
+``HAS_AMD_3DNOW`` One if porcessor supports 3DNow instructions
+``HAS_AMD_3DNOW_PLUS`` One if porcessor 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`
+============================= ================================================
diff --git a/Help/command/cmake_parse_arguments.rst b/Help/command/cmake_parse_arguments.rst
index ec4ffed3a..b334a89c1 100644
--- a/Help/command/cmake_parse_arguments.rst
+++ b/Help/command/cmake_parse_arguments.rst
@@ -43,15 +43,18 @@ macro which can be followed by more than one value, like e.g. the
``<multi_value_keywords>``. A warning will be emitted if uniqueness is
violated.
-When done, ``cmake_parse_arguments`` will have defined for each of the
+When done, ``cmake_parse_arguments`` will consider for each of the
keywords listed in ``<options>``, ``<one_value_keywords>`` and
``<multi_value_keywords>`` a variable composed of the given ``<prefix>``
followed by ``"_"`` and the name of the respective keyword. These
-variables will then hold the respective value from the argument list.
-For the ``<options>`` keywords this will be ``TRUE`` or ``FALSE``.
+variables will then hold the respective value from the argument list
+or be undefined if the associated option could not be found.
+For the ``<options>`` keywords, these will always be defined,
+to ``TRUE`` or ``FALSE``, whether the option is in the argument list or not.
All remaining arguments are collected in a variable
-``<prefix>_UNPARSED_ARGUMENTS``, this can be checked afterwards to see
+``<prefix>_UNPARSED_ARGUMENTS`` that will be undefined if all argument
+where recognized. This can be checked afterwards to see
whether your macro was called with unrecognized parameters.
As an example here a ``my_install()`` macro, which takes similar arguments
@@ -74,16 +77,16 @@ Assume ``my_install()`` has been called like this:
my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub)
-After the ``cmake_parse_arguments`` call the macro will have set the
-following variables::
+After the ``cmake_parse_arguments`` call the macro will have set or undefined
+the following variables::
MY_INSTALL_OPTIONAL = TRUE
- MY_INSTALL_FAST = FALSE (was not used in call to my_install)
+ MY_INSTALL_FAST = FALSE # was not used in call to my_install
MY_INSTALL_DESTINATION = "bin"
- MY_INSTALL_RENAME = "" (was not used)
+ MY_INSTALL_RENAME <UNDEFINED> # was not used
MY_INSTALL_TARGETS = "foo;bar"
- MY_INSTALL_CONFIGURATIONS = "" (was not used)
- MY_INSTALL_UNPARSED_ARGUMENTS = "blub" (nothing expected after "OPTIONAL")
+ MY_INSTALL_CONFIGURATIONS <UNDEFINED> # was not used
+ MY_INSTALL_UNPARSED_ARGUMENTS = "blub" # nothing expected after "OPTIONAL"
You can then continue and process these variables.
diff --git a/Help/command/configure_file.rst b/Help/command/configure_file.rst
index 4304f095b..e08c57347 100644
--- a/Help/command/configure_file.rst
+++ b/Help/command/configure_file.rst
@@ -30,9 +30,23 @@ a false constant by the :command:`if` command. The "..." content on the
line after the variable name, if any, is processed as above.
Input file lines of the form ``#cmakedefine01 VAR`` will be replaced with
either ``#define VAR 1`` or ``#define VAR 0`` similarly.
+The result lines (with the exception of the ``#undef`` comments) can be
+indented using spaces and/or tabs between the ``#`` character
+and the ``cmakedefine`` or ``cmakedefine01`` words. This whitespace
+indentation will be preserved in the output lines::
+
+ # cmakedefine VAR
+ # cmakedefine01 VAR
+
+will be replaced, if ``VAR`` is defined, with::
+
+ # define VAR
+ # define VAR 1
If the input file is modified the build system will re-run CMake to
re-configure the file and generate the build system again.
+The generated file is modified and its timestamp updated on subsequent
+cmake runs only if its content is changed.
The arguments are:
diff --git a/Help/command/execute_process.rst b/Help/command/execute_process.rst
index d617243d1..799493f6c 100644
--- a/Help/command/execute_process.rst
+++ b/Help/command/execute_process.rst
@@ -10,6 +10,7 @@ Execute one or more child processes.
[WORKING_DIRECTORY <directory>]
[TIMEOUT <seconds>]
[RESULT_VARIABLE <variable>]
+ [RESULTS_VARIABLE <variable>]
[OUTPUT_VARIABLE <variable>]
[ERROR_VARIABLE <variable>]
[INPUT_FILE <file>]
@@ -49,10 +50,16 @@ Options:
specified number of seconds (fractions are allowed).
``RESULT_VARIABLE``
- The variable will be set to contain the result of running the processes.
+ The variable will be set to contain the result of last child process.
This will be an integer return code from the last child or a string
describing an error condition.
+``RESULTS_VARIABLE <variable>``
+ The variable will be set to contain the result of all processes as a
+ :ref:`;-list <CMake Language Lists>`, in order of the given ``COMMAND``
+ arguments. Each entry will be an integer return code from the
+ corresponding child or a string describing an error condition.
+
``OUTPUT_VARIABLE``, ``ERROR_VARIABLE``
The variable named will be set with the contents of the standard output
and standard error pipes, respectively. If the same variable is named
diff --git a/Help/command/file.rst b/Help/command/file.rst
index b2e4eea44..edccac5b2 100644
--- a/Help/command/file.rst
+++ b/Help/command/file.rst
@@ -13,8 +13,11 @@ File manipulation command.
Write ``<content>`` into a file called ``<filename>``. If the file does
not exist, it will be created. If the file already exists, ``WRITE``
mode will overwrite it and ``APPEND`` mode will append to the end.
-(If the file is a build input, use the :command:`configure_file` command
-to update the file only when its content changes.)
+Any directories in the path specified by ``<filename>`` that do not
+exist will be created.
+
+If the file is a build input, use the :command:`configure_file` command
+to update the file only when its content changes.
------------------------------------------------------------------------------
@@ -105,9 +108,7 @@ Generate a list of files that match the ``<globbing-expressions>`` and
store it into the ``<variable>``. Globbing expressions are similar to
regular expressions, but much simpler. If ``RELATIVE`` flag is
specified, the results will be returned as relative paths to the given
-path. No specific order of results is defined other than that it is
-deterministic. If order is important then sort the list explicitly
-(e.g. using the :command:`list(SORT)` command).
+path. The results will be ordered lexicographically.
By default ``GLOB`` lists directories - directories are omited in result if
``LIST_DIRECTORIES`` is set to false.
@@ -291,6 +292,8 @@ from the input content to produce the output content. The options are:
``INPUT <input-file>``
Use the content from a given file as input.
+ A relative path is treated with respect to the value of
+ :variable:`CMAKE_CURRENT_SOURCE_DIR`. See policy :policy:`CMP0070`.
``OUTPUT <output-file>``
Specify the output file name to generate. Use generator expressions
@@ -298,11 +301,14 @@ from the input content to produce the output content. The options are:
name. Multiple configurations may generate the same output file only
if the generated content is identical. Otherwise, the ``<output-file>``
must evaluate to an unique name for each configuration.
+ A relative path (after evaluating generator expressions) is treated
+ with respect to the value of :variable:`CMAKE_CURRENT_BINARY_DIR`.
+ See policy :policy:`CMP0070`.
Exactly one ``CONTENT`` or ``INPUT`` option must be given. A specific
``OUTPUT`` file may be named by at most one invocation of ``file(GENERATE)``.
-Generated files are modified on subsequent cmake runs only if their content
-is changed.
+Generated files are modified and their timestamp updated on subsequent cmake
+runs only if their content is changed.
Note also that ``file(GENERATE)`` does not create the output file until the
generation phase. The output file will not yet have been written when the
diff --git a/Help/command/if.rst b/Help/command/if.rst
index edd343de2..f04f23321 100644
--- a/Help/command/if.rst
+++ b/Help/command/if.rst
@@ -30,7 +30,7 @@ else and endif clause is optional. Long expressions can be used and
there is a traditional order of precedence. Parenthetical expressions
are evaluated first followed by unary tests such as ``EXISTS``,
``COMMAND``, and ``DEFINED``. Then any binary tests such as
-``EQUAL``, ``LESS``, ``LESS_EQUAL, ``GREATER``, ``GREATER_EQUAL``,
+``EQUAL``, ``LESS``, ``LESS_EQUAL``, ``GREATER``, ``GREATER_EQUAL``,
``STREQUAL``, ``STRLESS``, ``STRLESS_EQUAL``, ``STRGREATER``,
``STRGREATER_EQUAL``, ``VERSION_EQUAL``, ``VERSION_LESS``,
``VERSION_LESS_EQUAL``, ``VERSION_GREATER``, ``VERSION_GREATER_EQUAL``,
diff --git a/Help/command/include_guard.rst b/Help/command/include_guard.rst
new file mode 100644
index 000000000..62cce2215
--- /dev/null
+++ b/Help/command/include_guard.rst
@@ -0,0 +1,46 @@
+include_guard
+-------------
+
+Provides an include guard for the file currently being processed by CMake.
+
+::
+
+ include_guard([DIRECTORY|GLOBAL])
+
+Sets up an include guard for the current CMake file (see the
+:variable:`CMAKE_CURRENT_LIST_FILE` variable documentation).
+
+CMake will end its processing of the current file at the location of the
+:command:`include_guard` command if the current file has already been
+processed for the applicable scope (see below). This provides functionality
+similar to the include guards commonly used in source headers or to the
+``#pragma once`` directive. If the current file has been processed previously
+for the applicable scope, the effect is as though :command:`return` had been
+called. Do not call this command from inside a function being defined within
+the current file.
+
+An optional argument specifying the scope of the guard may be provided.
+Possible values for the option are:
+
+``DIRECTORY``
+ The include guard applies within the current directory and below. The file
+ will only be included once within this directory scope, but may be included
+ again by other files outside of this directory (i.e. a parent directory or
+ another directory not pulled in by :command:`add_subdirectory` or
+ :command:`include` from the current file or its children).
+
+``GLOBAL``
+ The include guard applies globally to the whole build. The current file
+ will only be included once regardless of the scope.
+
+If no arguments given, ``include_guard`` has the same scope as a variable,
+meaning that the include guard effect is isolated by the most recent
+function scope or current directory if no inner function scopes exist.
+In this case the command behavior is the same as:
+
+.. code-block:: cmake
+
+ if(__CURRENT_FILE_VAR__)
+ return()
+ endif()
+ set(__CURRENT_FILE_VAR__ TRUE)
diff --git a/Help/command/string.rst b/Help/command/string.rst
index 4f0c45c29..fb3893f2b 100644
--- a/Help/command/string.rst
+++ b/Help/command/string.rst
@@ -132,6 +132,15 @@ APPEND
Append all the input arguments to the string.
+PREPEND
+"""""""
+
+::
+
+ string(PREPEND <string variable> [<input>...])
+
+Prepend all the input arguments to the string.
+
CONCAT
""""""
@@ -315,6 +324,7 @@ specifiers:
%j The day of the current year (001-366).
%m The month of the current year (01-12).
%b Abbreviated month name (e.g. Oct).
+ %B Full month name (e.g. October).
%M The minute of the current hour (00-59).
%s Seconds since midnight (UTC) 1-Jan-1970 (UNIX time).
%S The second of the current minute.
@@ -322,6 +332,7 @@ specifiers:
%U The week number of the current year (00-53).
%w The day of the current week. 0 is Sunday. (0-6)
%a Abbreviated weekday name (e.g. Fri).
+ %A Full weekday name (e.g. Friday).
%y The last two digits of the current year (00-99)
%Y The current year.
diff --git a/Help/dev/maint.rst b/Help/dev/maint.rst
index 78c06df65..bdfb3d078 100644
--- a/Help/dev/maint.rst
+++ b/Help/dev/maint.rst
@@ -8,6 +8,80 @@ See documentation on `CMake Development`_ for more information.
.. contents:: Maintainer Processes:
+Review a Merge Request
+======================
+
+The `CMake Review Process`_ requires a maintainer to issue the ``Do: merge``
+command to integrate a merge request. Please check at least the following:
+
+* If the MR source branch is not named well for the change it makes
+ (e.g. it is just ``master`` or the patch changed during review),
+ add a ``Topic-rename: <topic>`` trailing line to the MR description
+ to provide a better topic name.
+
+* If the MR introduces a new feature or a user-facing behavior change,
+ such as a policy, ensure that a ``Help/release/dev/$topic.rst`` file
+ is added with a release note.
+
+* If a commit changes a specific area, such as a module, its commit
+ message should have an ``area:`` prefix on its first line.
+
+* If a commit fixes a tracked issue, its commit message should have
+ a trailing line such as ``Fixes: #00000``.
+
+* Ensure that the MR adds sufficient documentation and test cases.
+
+* Ensure that the MR has been tested sufficiently. Typically it should
+ be staged for nightly testing with ``Do: stage``. Then manually
+ review the `CMake CDash Page`_ to verify that no regressions were
+ introduced. (Learn to tolerate spurious failures due to idiosyncrasies
+ of various nightly builders.)
+
+* Ensure that the MR targets the ``master`` branch. A MR intended for
+ the ``release`` branch should be based on ``release`` but still merged
+ to ``master`` first (via ``Do: merge``). A maintainer may then merge
+ the MR topic to ``release`` manually.
+
+Maintain Current Release
+========================
+
+The ``release`` branch is used to maintain the current release or release
+candidate. The branch is published with no version number but maintained
+using a local branch named ``release-$ver``, where ``$ver`` is the version
+number of the current release in the form ``$major.$minor``. It is always
+merged into ``master`` before publishing.
+
+To merge some ``$topic`` branch into ``release``, first create the local
+branch:
+
+.. code-block:: shell
+
+ git fetch origin
+ git checkout -b release-$ver origin/release
+
+Merge the ``$topic`` branch into the local ``release-$ver`` branch:
+
+.. code-block:: shell
+
+ git merge --no-ff $topic
+
+Merge the ``release-$ver`` branch to ``master``:
+
+.. code-block:: shell
+
+ git checkout master
+ git pull
+ git merge --no-ff release-$ver
+
+Publish both ``master`` and ``release`` simultaneously:
+
+.. code-block:: shell
+
+ git push --atomic origin master release-$ver:release
+
+.. _`CMake Review Process`: review.rst
+.. _`CMake CDash Page`: https://open.cdash.org/index.php?project=CMake
+
Branch a New Release
====================
diff --git a/Help/dev/review.rst b/Help/dev/review.rst
index 9450bf081..be02a1af0 100644
--- a/Help/dev/review.rst
+++ b/Help/dev/review.rst
@@ -185,6 +185,83 @@ commands to ``@kwrobot`` using the form ``Do: ...``:
See the corresponding sections for details on permissions and options
for each command.
+Commit Messages
+---------------
+
+Part of the human review is to check that each commit message is appropriate.
+The first line of the message should begin with one or two words indicating the
+area the commit applies to, followed by a colon and then a brief summary.
+Committers should aim to keep this first line short. Any subsequent lines
+should be separated from the first by a blank line and provide relevant, useful
+information.
+
+Area Prefix on Commit Messages
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The appropriateness of the initial word describing the area the commit applies
+to is not something the automatic robot review can judge, so it is up to the
+human reviewer to confirm that the area is specified and that it is
+appropriate. Good area words include the module name the commit is primarily
+fixing, the main C++ source file being edited, ``Help`` for generic
+documentation changes or a feature or functionality theme the changes apply to
+(e.g. ``server`` or ``Autogen``). Examples of suitable first lines of a commit
+message include:
+
+* ``Help: Fix example in cmake-buildsystem(7) manual``
+* ``FindBoost: Add support for 1.64``
+* ``Autogen: Extended mocInclude tests``
+* ``cmLocalGenerator: Explain standard flag selection logic in comments``
+
+Referencing Issues in Commit Messages
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+If the commit fixes a particular reported issue, this information should
+ideally also be part of the commit message. The recommended way to do this is
+to place a line at the end of the message in the form ``Fixes: #xxxxx`` where
+``xxxxx`` is the GitLab issue number and to separate it from the rest of the
+text by a blank line. For example::
+
+ Help: Fix FooBar example robustness issue
+
+ FooBar supports option X, but the example provided
+ would not work if Y was also specified.
+
+ Fixes: #12345
+
+GitLab will automatically create relevant links to the merge request and will
+close the issue when the commit is merged into master. GitLab understands a few
+other synonyms for ``Fixes`` and allows much more flexible forms than the
+above, but committers should aim for this format for consistency. Note that
+such details can alternatively be specified in the merge request description.
+
+Referencing Commits in Commit Messages
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The preferred form for references to other commits is
+``commit <commit> (<subject>, <date>)``, where:
+
+* ``<commit>``:
+ If available, a tag-relative name of the commit produced by
+ ``git describe --contains <commit-ish>``. Otherwise, the first
+ 8-10 characters of the commit ``<hash>``.
+
+* ``<subject>``:
+ The first line of the commit message.
+
+* ``<date>``:
+ The author date of the commit, in its original time zone, formatted as
+ ``CCYY-MM-DD``. ``git-log(1)`` shows the original time zone by default.
+
+Alternatively, the full commit ``<hash>`` may be used.
+
+Revising Commit Messages
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+Reviewers are encouraged to ask the committer to amend commit messages to
+follow these guidelines, but prefer to focus on the changes themselves as a
+first priority. Maintainers will also make a check of commit messages before
+merging.
+
Topic Testing
=============
diff --git a/Help/dev/source.rst b/Help/dev/source.rst
index 7e4499559..d0c19eba1 100644
--- a/Help/dev/source.rst
+++ b/Help/dev/source.rst
@@ -23,24 +23,12 @@ format only a subset of files, such as those that are locally modified.
C++ Subset Permitted
====================
-CMake supports compiling as C++98 in addition to C++11 and C++14.
-In order to support building on older toolchains some constructs
-need to be handled with care:
+CMake requires compiling as C++11 or above. However, in order to support
+building on older toolchains some constructs need to be handled with care:
-* Use ``CM_AUTO_PTR`` instead of ``std::auto_ptr``.
+* Do not use ``std::auto_ptr``.
- The ``std::auto_ptr`` template is deprecated in C++11. We want to use it
- so we can build on C++98 compilers but we do not want to turn off compiler
- warnings about deprecated interfaces in general. Use the ``CM_AUTO_PTR``
- macro instead.
-
-* Use ``CM_EQ_DELETE;`` instead of ``= delete;``.
-
- Defining functions as *deleted* is not supported in C++98. Using
- ``CM_EQ_DELETE`` will delete the functions if the compiler supports it and
- give them no implementation otherwise. Calling such a function will lead
- to compiler errors if the compiler supports *deleted* functions and linker
- errors otherwise.
+ The ``std::auto_ptr`` template is deprecated in C++11. Use ``std::unique_ptr``.
* Use ``CM_DISABLE_COPY(Class)`` to mark classes as non-copyable.
@@ -58,3 +46,50 @@ need to be handled with care:
When assigning the result of ``.size()`` on a container for example,
the result should be assigned to ``size_t`` not to ``std::size_t``,
``unsigned int`` or similar types.
+
+Source Tree Layout
+==================
+
+The CMake source tree is organized as follows.
+
+* ``Auxiliary/``:
+ Shell and editor integration files.
+
+* ``Help/``:
+ Documentation.
+
+ * ``Help/dev/``:
+ Developer documentation.
+
+ * ``Help/release/dev/``:
+ Release note snippets for development since last release.
+
+* ``Licenses/``:
+ License files for third-party libraries in binary distributions.
+
+* ``Modules/``:
+ CMake language modules installed with CMake.
+
+* ``Packaging/``:
+ Files used for packaging CMake itself for distribution.
+
+* ``Source/``:
+ Source code of CMake itself.
+
+* ``Templates/``:
+ Files distributed with CMake as implementation details for generators,
+ packagers, etc.
+
+* ``Tests/``:
+ The test suite. See `Tests/README.rst`_.
+
+* ``Utilities/``:
+ Scripts, third-party source code.
+
+ * ``Utilities/Sphinx/``:
+ Sphinx configuration to build CMake user documentation.
+
+ * ``Utilities/Release/``:
+ Scripts used to package CMake itself for distribution on ``cmake.org``.
+
+.. _`Tests/README.rst`: ../../Tests/README.rst
diff --git a/Help/envvar/ASM_DIALECT.rst b/Help/envvar/ASM_DIALECT.rst
new file mode 100644
index 000000000..ec48f7145
--- /dev/null
+++ b/Help/envvar/ASM_DIALECT.rst
@@ -0,0 +1,11 @@
+ASM<DIALECT>
+------------
+
+Preferred executable for compiling a specific dialect of assembly language
+files. ``ASM<DIALECT>`` can be ``ASM``, ``ASM_NASM``, ``ASM_MASM`` or
+``ASM-ATT``. Will only be used by CMake on the first configuration to determine
+``ASM<DIALECT>`` compiler, after which the value for ``ASM<DIALECT>`` is stored
+in the cache as
+:variable:`CMAKE_ASM<DIALECT>_COMPILER <CMAKE_<LANG>_COMPILER>`. For subsequent
+configuration runs, the environment variable will be ignored in favor of
+:variable:`CMAKE_ASM<DIALECT>_COMPILER <CMAKE_<LANG>_COMPILER>`.
diff --git a/Help/envvar/ASM_DIALECTFLAGS.rst b/Help/envvar/ASM_DIALECTFLAGS.rst
new file mode 100644
index 000000000..4ed02fe22
--- /dev/null
+++ b/Help/envvar/ASM_DIALECTFLAGS.rst
@@ -0,0 +1,11 @@
+ASM<DIALECT>FLAGS
+-----------------
+
+Default compilation flags to be used when compiling a specific dialect of an
+assembly language. ``ASM<DIALECT>FLAGS`` can be ``ASMFLAGS``, ``ASM_NASMFLAGS``,
+``ASM_MASMFLAGS`` or ``ASM-ATTFLAGS``. Will only be used by CMake on the
+first configuration to determine ``ASM<DIALECT>`` default compilation flags, after
+which the value for ``ASM<DIALECT>FLAGS`` is stored in the cache as
+:variable:`CMAKE_ASM<DIALECT>_FLAGS <CMAKE_<LANG>_FLAGS>`. For any configuration
+run (including the first), the environment variable will be ignored if the
+:variable:`CMAKE_ASM<DIALECT>_FLAGS <CMAKE_<LANG>_FLAGS>` variable is defined.
diff --git a/Help/envvar/CC.rst b/Help/envvar/CC.rst
new file mode 100644
index 000000000..7e68110a1
--- /dev/null
+++ b/Help/envvar/CC.rst
@@ -0,0 +1,9 @@
+CC
+--
+
+Preferred executable for compiling ``C`` language files. Will only be used by
+CMake on the first configuration to determine ``C`` compiler, after which the
+value for ``CC`` is stored in the cache as
+:variable:`CMAKE_C_COMPILER <CMAKE_<LANG>_COMPILER>`. For any configuration run
+(including the first), the environment variable will be ignored if the
+:variable:`CMAKE_C_COMPILER <CMAKE_<LANG>_COMPILER>` variable is defined.
diff --git a/Help/envvar/CFLAGS.rst b/Help/envvar/CFLAGS.rst
new file mode 100644
index 000000000..60b2cd36a
--- /dev/null
+++ b/Help/envvar/CFLAGS.rst
@@ -0,0 +1,9 @@
+CFLAGS
+------
+
+Default compilation flags to be used when compiling ``C`` files. Will only be
+used by CMake on the first configuration to determine ``CC`` default compilation
+flags, after which the value for ``CFLAGS`` is stored in the cache
+as :variable:`CMAKE_C_FLAGS <CMAKE_<LANG>_FLAGS>`. For any configuration run
+(including the first), the environment variable will be ignored if the
+:variable:`CMAKE_C_FLAGS <CMAKE_<LANG>_FLAGS>` variable is defined.
diff --git a/Help/envvar/CMAKE_CONFIG_TYPE.rst b/Help/envvar/CMAKE_CONFIG_TYPE.rst
new file mode 100644
index 000000000..1306b47da
--- /dev/null
+++ b/Help/envvar/CMAKE_CONFIG_TYPE.rst
@@ -0,0 +1,5 @@
+CMAKE_CONFIG_TYPE
+-----------------
+
+The default build configuration for :ref:`Build Tool Mode` and
+``ctest`` build handler when there is no explicit configuration given.
diff --git a/Help/envvar/CMAKE_MSVCIDE_RUN_PATH.rst b/Help/envvar/CMAKE_MSVCIDE_RUN_PATH.rst
new file mode 100644
index 000000000..54d5f9e02
--- /dev/null
+++ b/Help/envvar/CMAKE_MSVCIDE_RUN_PATH.rst
@@ -0,0 +1,8 @@
+CMAKE_MSVCIDE_RUN_PATH
+----------------------
+
+Extra PATH locations for custom commands when using
+:generator:`Visual Studio 9 2008` (or above) generators.
+
+The ``CMAKE_MSVCIDE_RUN_PATH`` environment variable sets the default value for
+the :variable:`CMAKE_MSVCIDE_RUN_PATH` variable if not already explicitly set.
diff --git a/Help/envvar/CMAKE_OSX_ARCHITECTURES.rst b/Help/envvar/CMAKE_OSX_ARCHITECTURES.rst
new file mode 100644
index 000000000..8bbf993bd
--- /dev/null
+++ b/Help/envvar/CMAKE_OSX_ARCHITECTURES.rst
@@ -0,0 +1,8 @@
+CMAKE_OSX_ARCHITECTURES
+-----------------------
+
+Target specific architectures for OS X.
+
+The ``CMAKE_OSX_ARCHITECTURES`` environment variable sets the default value for
+the :variable:`CMAKE_OSX_ARCHITECTURES` variable. See
+:prop_tgt:`OSX_ARCHITECTURES` for more information.
diff --git a/Help/envvar/CSFLAGS.rst b/Help/envvar/CSFLAGS.rst
new file mode 100644
index 000000000..251ddc577
--- /dev/null
+++ b/Help/envvar/CSFLAGS.rst
@@ -0,0 +1,9 @@
+CSFLAGS
+-------
+
+Preferred executable for compiling ``CSharp`` language files. Will only be
+used by CMake on the first configuration to determine ``CSharp`` default
+compilation flags, after which the value for ``CSFLAGS`` is stored in the cache
+as :variable:`CMAKE_CSharp_FLAGS <CMAKE_<LANG>_FLAGS>`. For any configuration
+run (including the first), the environment variable will be ignored if the
+:variable:`CMAKE_CSharp_FLAGS <CMAKE_<LANG>_FLAGS>` variable is defined.
diff --git a/Help/envvar/CTEST_INTERACTIVE_DEBUG_MODE.rst b/Help/envvar/CTEST_INTERACTIVE_DEBUG_MODE.rst
new file mode 100644
index 000000000..25ed14f1b
--- /dev/null
+++ b/Help/envvar/CTEST_INTERACTIVE_DEBUG_MODE.rst
@@ -0,0 +1,5 @@
+CTEST_INTERACTIVE_DEBUG_MODE
+----------------------------
+
+Environment variable that will exist and be set to ``1`` when a test executed
+by CTest is run in interactive mode.
diff --git a/Help/envvar/CTEST_OUTPUT_ON_FAILURE.rst b/Help/envvar/CTEST_OUTPUT_ON_FAILURE.rst
new file mode 100644
index 000000000..1fcf42bcf
--- /dev/null
+++ b/Help/envvar/CTEST_OUTPUT_ON_FAILURE.rst
@@ -0,0 +1,7 @@
+CTEST_OUTPUT_ON_FAILURE
+-----------------------
+
+Boolean environment variable that controls if the output should be logged for
+failed tests. Set the value to 1, True, or ON to enable output on failure.
+See :manual:`ctest(1)` for more information on controlling output of failed
+tests.
diff --git a/Help/envvar/CTEST_PARALLEL_LEVEL.rst b/Help/envvar/CTEST_PARALLEL_LEVEL.rst
new file mode 100644
index 000000000..c767a01ae
--- /dev/null
+++ b/Help/envvar/CTEST_PARALLEL_LEVEL.rst
@@ -0,0 +1,5 @@
+CTEST_PARALLEL_LEVEL
+--------------------
+
+Specify the number of tests for CTest to run in parallel. See :manual:`ctest(1)`
+for more information on parallel test execution.
diff --git a/Help/envvar/CTEST_USE_LAUNCHERS_DEFAULT.rst b/Help/envvar/CTEST_USE_LAUNCHERS_DEFAULT.rst
new file mode 100644
index 000000000..8d8eea5f8
--- /dev/null
+++ b/Help/envvar/CTEST_USE_LAUNCHERS_DEFAULT.rst
@@ -0,0 +1,4 @@
+CTEST_USE_LAUNCHERS_DEFAULT
+---------------------------
+
+Initializes the :variable:`CTEST_USE_LAUNCHERS` variable if not already defined.
diff --git a/Help/envvar/CUDACXX.rst b/Help/envvar/CUDACXX.rst
new file mode 100644
index 000000000..8a5fd4be3
--- /dev/null
+++ b/Help/envvar/CUDACXX.rst
@@ -0,0 +1,9 @@
+CUDACXX
+-------
+
+Preferred executable for compiling ``CUDA`` language files. Will only be used by
+CMake on the first configuration to determine ``CUDA`` compiler, after which the
+value for ``CUDA`` is stored in the cache as
+:variable:`CMAKE_CUDA_COMPILER <CMAKE_<LANG>_COMPILER>`. For any configuration
+run (including the first), the environment variable will be ignored if the
+:variable:`CMAKE_CUDA_COMPILER <CMAKE_<LANG>_COMPILER>` variable is defined.
diff --git a/Help/envvar/CUDAFLAGS.rst b/Help/envvar/CUDAFLAGS.rst
new file mode 100644
index 000000000..3dff49fb6
--- /dev/null
+++ b/Help/envvar/CUDAFLAGS.rst
@@ -0,0 +1,9 @@
+CUDAFLAGS
+---------
+
+Default compilation flags to be used when compiling ``CUDA`` files. Will only be
+used by CMake on the first configuration to determine ``CUDA`` default
+compilation flags, after which the value for ``CUDAFLAGS`` is stored in the
+cache as :variable:`CMAKE_CUDA_FLAGS <CMAKE_<LANG>_FLAGS>`. For any configuration
+run (including the first), the environment variable will be ignored if
+the :variable:`CMAKE_CUDA_FLAGS <CMAKE_<LANG>_FLAGS>` variable is defined.
diff --git a/Help/envvar/CUDAHOSTCXX.rst b/Help/envvar/CUDAHOSTCXX.rst
new file mode 100644
index 000000000..f0f94f647
--- /dev/null
+++ b/Help/envvar/CUDAHOSTCXX.rst
@@ -0,0 +1,9 @@
+CUDAHOSTCXX
+-----------
+
+Preferred executable for compiling host code when compiling ``CUDA``
+language files. Will only be used by CMake on the first configuration to
+determine ``CUDA`` host compiler, after which the value for ``CUDAHOSTCXX`` is
+stored in the cache as :variable:`CMAKE_CUDA_HOST_COMPILER`. For any
+configuration run (including the first), the environment variable will be
+ignored if the :variable:`CMAKE_CUDA_HOST_COMPILER` variable is defined.
diff --git a/Help/envvar/CXX.rst b/Help/envvar/CXX.rst
new file mode 100644
index 000000000..3b1e445b4
--- /dev/null
+++ b/Help/envvar/CXX.rst
@@ -0,0 +1,9 @@
+CXX
+---
+
+Preferred executable for compiling ``CXX`` language files. Will only be used by
+CMake on the first configuration to determine ``CXX`` compiler, after which the
+value for ``CXX`` is stored in the cache as
+:variable:`CMAKE_CXX_COMPILER <CMAKE_<LANG>_COMPILER>`. For any configuration
+run (including the first), the environment variable will be ignored if the
+:variable:`CMAKE_CXX_COMPILER <CMAKE_<LANG>_COMPILER>` variable is defined.
diff --git a/Help/envvar/CXXFLAGS.rst b/Help/envvar/CXXFLAGS.rst
new file mode 100644
index 000000000..8b58abd06
--- /dev/null
+++ b/Help/envvar/CXXFLAGS.rst
@@ -0,0 +1,9 @@
+CXXFLAGS
+--------
+
+Default compilation flags to be used when compiling ``CXX`` (C++) files. Will
+only be used by CMake on the first configuration to determine ``CXX`` default
+compilation flags, after which the value for ``CXXFLAGS`` is stored in the cache
+as :variable:`CMAKE_CXX_FLAGS <CMAKE_<LANG>_FLAGS>`. For any configuration run (
+including the first), the environment variable will be ignored if
+the :variable:`CMAKE_CXX_FLAGS <CMAKE_<LANG>_FLAGS>` variable is defined.
diff --git a/Help/envvar/DASHBOARD_TEST_FROM_CTEST.rst b/Help/envvar/DASHBOARD_TEST_FROM_CTEST.rst
new file mode 100644
index 000000000..fab1c0c33
--- /dev/null
+++ b/Help/envvar/DASHBOARD_TEST_FROM_CTEST.rst
@@ -0,0 +1,5 @@
+DASHBOARD_TEST_FROM_CTEST
+-------------------------
+
+Environment variable that will exist when a test executed by CTest is run
+in non-interactive mode. The value will be equal to :variable:`CMAKE_VERSION`.
diff --git a/Help/envvar/FC.rst b/Help/envvar/FC.rst
new file mode 100644
index 000000000..7d293fdd4
--- /dev/null
+++ b/Help/envvar/FC.rst
@@ -0,0 +1,10 @@
+FC
+--
+
+Preferred executable for compiling ``Fortran`` language files. Will only be used
+by CMake on the first configuration to determine ``Fortran`` compiler, after
+which the value for ``Fortran`` is stored in the cache as
+:variable:`CMAKE_Fortran_COMPILER <CMAKE_<LANG>_COMPILER>`. For any
+configuration run (including the first), the environment variable will be
+ignored if the :variable:`CMAKE_Fortran_COMPILER <CMAKE_<LANG>_COMPILER>`
+variable is defined.
diff --git a/Help/envvar/FFLAGS.rst b/Help/envvar/FFLAGS.rst
new file mode 100644
index 000000000..19d61690c
--- /dev/null
+++ b/Help/envvar/FFLAGS.rst
@@ -0,0 +1,9 @@
+FFLAGS
+------
+
+Default compilation flags to be used when compiling ``Fortran`` files. Will only
+be used by CMake on the first configuration to determine ``Fortran`` default
+compilation flags, after which the value for ``FFLAGS`` is stored in the cache
+as :variable:`CMAKE_Fortran_FLAGS <CMAKE_<LANG>_FLAGS>`. For any configuration
+run (including the first), the environment variable will be ignored if
+the :variable:`CMAKE_Fortran_FLAGS <CMAKE_<LANG>_FLAGS>` variable is defined.
diff --git a/Help/envvar/LDFLAGS.rst b/Help/envvar/LDFLAGS.rst
new file mode 100644
index 000000000..52da99c1b
--- /dev/null
+++ b/Help/envvar/LDFLAGS.rst
@@ -0,0 +1,10 @@
+LDFLAGS
+-------
+
+Will only be used by CMake on the first configuration to determine the default
+linker flags, after which the value for ``LDFLAGS`` is stored in the cache
+as :variable:`CMAKE_EXE_LINKER_FLAGS_INIT`,
+:variable:`CMAKE_SHARED_LINKER_FLAGS_INIT`, and
+:variable:`CMAKE_MODULE_LINKER_FLAGS_INIT`. For any configuration run
+(including the first), the environment variable will be ignored if the
+equivalent ``CMAKE_<TYPE>_LINKER_FLAGS_INIT`` variable is defined.
diff --git a/Help/envvar/MACOSX_DEPLOYMENT_TARGET.rst b/Help/envvar/MACOSX_DEPLOYMENT_TARGET.rst
new file mode 100644
index 000000000..e6051b44a
--- /dev/null
+++ b/Help/envvar/MACOSX_DEPLOYMENT_TARGET.rst
@@ -0,0 +1,8 @@
+MACOSX_DEPLOYMENT_TARGET
+------------------------
+
+Specify the minimum version of OS X on which the target binaries are
+to be deployed.
+
+The ``MACOSX_DEPLOYMENT_TARGET`` environment variable sets the default value for
+the :variable:`CMAKE_OSX_DEPLOYMENT_TARGET` variable.
diff --git a/Help/envvar/RC.rst b/Help/envvar/RC.rst
new file mode 100644
index 000000000..6c2db1984
--- /dev/null
+++ b/Help/envvar/RC.rst
@@ -0,0 +1,9 @@
+RC
+--
+
+Preferred executable for compiling ``resource`` files. Will only be used by CMake
+on the first configuration to determine ``resource`` compiler, after which the
+value for ``RC`` is stored in the cache as
+:variable:`CMAKE_RC_COMPILER <CMAKE_<LANG>_COMPILER>`. For any configuration run
+(including the first), the environment variable will be ignored if the
+:variable:`CMAKE_RC_COMPILER <CMAKE_<LANG>_COMPILER>` variable is defined.
diff --git a/Help/envvar/RCFLAGS.rst b/Help/envvar/RCFLAGS.rst
new file mode 100644
index 000000000..4f2f31c03
--- /dev/null
+++ b/Help/envvar/RCFLAGS.rst
@@ -0,0 +1,9 @@
+RCFLAGS
+-------
+
+Default compilation flags to be used when compiling ``resource`` files. Will
+only be used by CMake on the first configuration to determine ``resource``
+default compilation flags, after which the value for ``RCFLAGS`` is stored in
+the cache as :variable:`CMAKE_RC_FLAGS <CMAKE_<LANG>_FLAGS>`. For any
+configuration run (including the first), the environment variable will be ignored
+if the :variable:`CMAKE_RC_FLAGS <CMAKE_<LANG>_FLAGS>` variable is defined.
diff --git a/Help/generator/CodeBlocks.rst b/Help/generator/CodeBlocks.rst
index d03cb0ce6..06cc746b1 100644
--- a/Help/generator/CodeBlocks.rst
+++ b/Help/generator/CodeBlocks.rst
@@ -6,7 +6,11 @@ Generates CodeBlocks project files.
Project files for CodeBlocks will be created in the top directory and
in every subdirectory which features a CMakeLists.txt file containing
a PROJECT() call. Additionally a hierarchy of makefiles is generated
-into the build tree. The appropriate make program can build the
+into the build tree.
+The :variable:`CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES` variable may
+be set to ``ON`` to exclude any files which are located outside of
+the project root directory.
+The appropriate make program can build the
project through the default make target. A "make install" target is
also provided.
diff --git a/Help/index.rst b/Help/index.rst
index 97cd1073b..3dccdda0d 100644
--- a/Help/index.rst
+++ b/Help/index.rst
@@ -40,6 +40,7 @@ Reference Manuals
/manual/cmake-qt.7
/manual/cmake-toolchains.7
/manual/cmake-variables.7
+ /manual/cmake-env-variables.7
.. only:: html or text
diff --git a/Help/manual/cmake-buildsystem.7.rst b/Help/manual/cmake-buildsystem.7.rst
index 95f5b8735..ae538edc2 100644
--- a/Help/manual/cmake-buildsystem.7.rst
+++ b/Help/manual/cmake-buildsystem.7.rst
@@ -266,7 +266,7 @@ The :command:`target_link_libraries` command has ``PRIVATE``,
Because ``archive`` is a ``PUBLIC`` dependency of ``archiveExtras``, the
usage requirements of it are propagated to ``consumer`` too. Because
-``serialization`` is a ``PRIVATE`` dependency of ``archive``, the usage
+``serialization`` is a ``PRIVATE`` dependency of ``archiveExtras``, the usage
requirements of it are not propagated to ``consumer``.
Generally, a dependency should be specified in a use of
@@ -687,7 +687,8 @@ property are treated as ``SYSTEM`` include directories, as if they were
listed in the :prop_tgt:`INTERFACE_SYSTEM_INCLUDE_DIRECTORIES` of the
dependency. This can result in omission of compiler warnings for headers
found in those directories. This behavior for :ref:`imported targets` may
-be controlled with the :prop_tgt:`NO_SYSTEM_FROM_IMPORTED` target property.
+be controlled by setting the :prop_tgt:`NO_SYSTEM_FROM_IMPORTED` target
+property on the *consumers* of imported targets.
If a binary target is linked transitively to a Mac OX framework, the
``Headers`` directory of the framework is also treated as a usage requirement.
@@ -970,7 +971,6 @@ are:
* ``EXPORT_NAME``
* ``IMPORTED``
* ``NAME``
-* ``NO_SYSTEM_FROM_IMPORTED``
* Properties matching ``IMPORTED_LIBNAME_*``
* Properties matching ``MAP_IMPORTED_CONFIG_*``
diff --git a/Help/manual/cmake-commands.7.rst b/Help/manual/cmake-commands.7.rst
index 611c989a0..f8bfb323a 100644
--- a/Help/manual/cmake-commands.7.rst
+++ b/Help/manual/cmake-commands.7.rst
@@ -44,6 +44,7 @@ These commands are always available.
/command/get_property
/command/if
/command/include
+ /command/include_guard
/command/list
/command/macro
/command/mark_as_advanced
diff --git a/Help/manual/cmake-env-variables.7.rst b/Help/manual/cmake-env-variables.7.rst
new file mode 100644
index 000000000..fed129e45
--- /dev/null
+++ b/Help/manual/cmake-env-variables.7.rst
@@ -0,0 +1,54 @@
+.. cmake-manual-description: CMake Environment Variables Reference
+
+cmake-env-variables(7)
+**********************
+
+.. only:: html
+
+ .. contents::
+
+Environment Variables that Control the Build
+============================================
+
+.. toctree::
+ :maxdepth: 1
+
+ /envvar/CMAKE_CONFIG_TYPE
+ /envvar/CMAKE_MSVCIDE_RUN_PATH
+ /envvar/CMAKE_OSX_ARCHITECTURES
+ /envvar/LDFLAGS
+ /envvar/MACOSX_DEPLOYMENT_TARGET
+
+Environment Variables for Languages
+===================================
+
+.. toctree::
+ :maxdepth: 1
+
+ /envvar/ASM_DIALECT
+ /envvar/ASM_DIALECTFLAGS
+ /envvar/CC
+ /envvar/CFLAGS
+ /envvar/CSFLAGS
+ /envvar/CUDACXX
+ /envvar/CUDAFLAGS
+ /envvar/CUDAHOSTCXX
+ /envvar/CXX
+ /envvar/CXXFLAGS
+ /envvar/FC
+ /envvar/FFLAGS
+ /envvar/RC
+ /envvar/RCFLAGS
+
+Environment Variables for CTest
+===============================
+
+.. toctree::
+ :maxdepth: 1
+
+ /envvar/CMAKE_CONFIG_TYPE
+ /envvar/CTEST_INTERACTIVE_DEBUG_MODE
+ /envvar/CTEST_OUTPUT_ON_FAILURE
+ /envvar/CTEST_PARALLEL_LEVEL
+ /envvar/CTEST_USE_LAUNCHERS_DEFAULT
+ /envvar/DASHBOARD_TEST_FROM_CTEST
diff --git a/Help/manual/cmake-language.7.rst b/Help/manual/cmake-language.7.rst
index 27b5d30b4..87f8f9dec 100644
--- a/Help/manual/cmake-language.7.rst
+++ b/Help/manual/cmake-language.7.rst
@@ -183,18 +183,18 @@ same length:
.. productionlist::
bracket_argument: `bracket_open` `bracket_content` `bracket_close`
- bracket_open: '[' '='{len} '['
- bracket_content: <any text not containing a `bracket_close`
- : of the same {len} as the `bracket_open`>
- bracket_close: ']' '='{len} ']'
+ bracket_open: '[' '='* '['
+ bracket_content: <any text not containing a `bracket_close` with
+ : the same number of '=' as the `bracket_open`>
+ bracket_close: ']' '='* ']'
.. raw:: latex
\end{small}
-An opening bracket of length *len >= 0* is written ``[`` followed
-by *len* ``=`` followed by ``[`` and the corresponding closing
-bracket is written ``]`` followed by *len* ``=`` followed by ``]``.
+An opening bracket is written ``[`` followed by zero or more ``=`` followed
+by ``[``. The corresponding closing bracket is written ``]`` followed
+by the same number of ``=`` followed by ``]``.
Brackets do not nest. A unique length may always be chosen
for the opening and closing brackets to contain closing brackets
of other lengths.
@@ -334,6 +334,8 @@ For example:
beginning of an unquoted argument, and are treated as part of the
content. For example, the unquoted arguments ``-Da="b c"``,
``-Da=$(v)``, and ``a" "b"c"d`` are each interpreted literally.
+ They may instead be written as quoted arguments ``"-Da=\"b c\""``,
+ ``"-Da=$(v)"``, and ``"a\" \"b\"c\"d"``, respectively.
Make-style references are treated literally as part of the content
and do not undergo variable expansion. They are treated as part
@@ -514,7 +516,7 @@ Function Scope
create commands that, when invoked, process the recorded commands
in a new variable binding scope. A variable "set" or "unset"
binds in this scope and is visible for the current function and
- any nested calls, but not after the function returns.
+ any nested calls within it, but not after the function returns.
Directory Scope
Each of the `Directories`_ in a source tree has its own variable
diff --git a/Help/manual/cmake-modules.7.rst b/Help/manual/cmake-modules.7.rst
index 4a03b7a80..8f4b2522d 100644
--- a/Help/manual/cmake-modules.7.rst
+++ b/Help/manual/cmake-modules.7.rst
@@ -60,6 +60,7 @@ All Modules
/module/CPackCygwin
/module/CPackDeb
/module/CPackDMG
+ /module/CPackFreeBSD
/module/CPackIFW
/module/CPackIFWConfigureFile
/module/CPackNSIS
@@ -152,6 +153,7 @@ All Modules
/module/FindMPEG2
/module/FindMPEG
/module/FindMPI
+ /module/FindOpenACC
/module/FindOpenAL
/module/FindOpenCL
/module/FindOpenGL
@@ -181,6 +183,7 @@ All Modules
/module/FindosgWidget
/module/FindPackageHandleStandardArgs
/module/FindPackageMessage
+ /module/FindPatch
/module/FindPerlLibs
/module/FindPerl
/module/FindPHP4
diff --git a/Help/manual/cmake-policies.7.rst b/Help/manual/cmake-policies.7.rst
index 7b858176f..c81ba59cd 100644
--- a/Help/manual/cmake-policies.7.rst
+++ b/Help/manual/cmake-policies.7.rst
@@ -51,6 +51,15 @@ 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.10
+=================================
+
+.. toctree::
+ :maxdepth: 1
+
+ CMP0071: Let AUTOMOC and AUTOUIC process GENERATED files. </policy/CMP0071>
+ CMP0070: Define file(GENERATE) behavior for relative paths. </policy/CMP0070>
+
Policies Introduced by CMake 3.9
================================
diff --git a/Help/manual/cmake-properties.7.rst b/Help/manual/cmake-properties.7.rst
index ec25596f3..dd59a0054 100644
--- a/Help/manual/cmake-properties.7.rst
+++ b/Help/manual/cmake-properties.7.rst
@@ -74,6 +74,7 @@ Properties on Directories
/prop_dir/INCLUDE_REGULAR_EXPRESSION
/prop_dir/INTERPROCEDURAL_OPTIMIZATION_CONFIG
/prop_dir/INTERPROCEDURAL_OPTIMIZATION
+ /prop_dir/LABELS
/prop_dir/LINK_DIRECTORIES
/prop_dir/LISTFILE_STACK
/prop_dir/MACROS
@@ -83,7 +84,7 @@ Properties on Directories
/prop_dir/RULE_LAUNCH_LINK
/prop_dir/SOURCE_DIR
/prop_dir/SUBDIRECTORIES
- /prop_dir/TEST_INCLUDE_FILE
+ /prop_dir/TEST_INCLUDE_FILES
/prop_dir/VARIABLES
/prop_dir/VS_GLOBAL_SECTION_POST_section
/prop_dir/VS_GLOBAL_SECTION_PRE_section
@@ -121,7 +122,9 @@ Properties on Targets
/prop_tgt/ARCHIVE_OUTPUT_NAME
/prop_tgt/AUTOGEN_BUILD_DIR
/prop_tgt/AUTOGEN_TARGET_DEPENDS
+ /prop_tgt/AUTOMOC_COMPILER_PREDEFINES
/prop_tgt/AUTOMOC_DEPEND_FILTERS
+ /prop_tgt/AUTOMOC_MACRO_NAMES
/prop_tgt/AUTOMOC_MOC_OPTIONS
/prop_tgt/AUTOMOC
/prop_tgt/AUTOUIC
@@ -225,6 +228,7 @@ Properties on Targets
/prop_tgt/LABELS
/prop_tgt/LANG_CLANG_TIDY
/prop_tgt/LANG_COMPILER_LAUNCHER
+ /prop_tgt/LANG_CPPCHECK
/prop_tgt/LANG_CPPLINT
/prop_tgt/LANG_INCLUDE_WHAT_YOU_USE
/prop_tgt/LANG_VISIBILITY_PRESET
@@ -291,6 +295,7 @@ Properties on Targets
/prop_tgt/VS_DEBUGGER_WORKING_DIRECTORY
/prop_tgt/VS_DESKTOP_EXTENSIONS_VERSION
/prop_tgt/VS_DOTNET_REFERENCE_refname
+ /prop_tgt/VS_DOTNET_REFERENCEPROP_refname_TAG_tagname
/prop_tgt/VS_DOTNET_REFERENCES
/prop_tgt/VS_DOTNET_REFERENCES_COPY_LOCAL
/prop_tgt/VS_DOTNET_TARGET_FRAMEWORK_VERSION
@@ -388,7 +393,9 @@ Properties on Source Files
/prop_sf/VS_SHADER_ENTRYPOINT
/prop_sf/VS_SHADER_FLAGS
/prop_sf/VS_SHADER_MODEL
+ /prop_sf/VS_SHADER_OUTPUT_HEADER_FILE
/prop_sf/VS_SHADER_TYPE
+ /prop_sf/VS_SHADER_VARIABLE_NAME
/prop_sf/VS_TOOL_OVERRIDE.rst
/prop_sf/VS_XAML_TYPE
/prop_sf/WRAP_EXCLUDE
@@ -434,6 +441,7 @@ Deprecated Properties on Directories
:maxdepth: 1
/prop_dir/COMPILE_DEFINITIONS_CONFIG
+ /prop_dir/TEST_INCLUDE_FILE
Deprecated Properties on Targets
diff --git a/Help/manual/cmake-qt.7.rst b/Help/manual/cmake-qt.7.rst
index b7f16b9ea..cafeae170 100644
--- a/Help/manual/cmake-qt.7.rst
+++ b/Help/manual/cmake-qt.7.rst
@@ -59,9 +59,10 @@ The :prop_tgt:`AUTOMOC` target property controls whether :manual:`cmake(1)`
inspects the C++ files in the target to determine if they require ``moc`` to
be run, and to create rules to execute ``moc`` at the appropriate time.
-If a ``Q_OBJECT`` or ``Q_GADGET`` macro is found in a header file, ``moc``
-will be run on the file. The result will be put into a file named according
-to ``moc_<basename>.cpp``. If the macro is found in a C++ implementation
+If a macro from :prop_tgt:`AUTOMOC_MACRO_NAMES` is found in a header file,
+``moc`` will be run on the file. The result will be put into a file named
+according to ``moc_<basename>.cpp``.
+If the macro is found in a C++ implementation
file, the moc output will be put into a file named according to
``<basename>.moc``, following the Qt conventions. The ``<basename>.moc`` must
be included by the user in the C++ implementation file with a preprocessor
@@ -72,6 +73,10 @@ Included ``moc_*.cpp`` and ``*.moc`` files will be generated in the
automatically added to the target's :prop_tgt:`INCLUDE_DIRECTORIES`.
* This differs from CMake 3.7 and below; see their documentation for details.
+
+* For :prop_gbl:`multi configuration generators <GENERATOR_IS_MULTI_CONFIG>`,
+ the include directory is ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>``.
+
* See :prop_tgt:`AUTOGEN_BUILD_DIR`.
Not included ``moc_<basename>.cpp`` files will be generated in custom
@@ -91,6 +96,8 @@ following targets by setting the :variable:`CMAKE_AUTOMOC` variable. The
options to pass to ``moc``. The :variable:`CMAKE_AUTOMOC_MOC_OPTIONS`
variable may be populated to pre-set the options for all following targets.
+Additional macro names to search for can be added to :prop_tgt:`AUTOMOC_MACRO_NAMES`.
+
Additional ``moc`` dependency file names can be extracted from source code
by using :prop_tgt:`AUTOMOC_DEPEND_FILTERS`.
@@ -124,6 +131,10 @@ The generated generated ``ui_*.h`` files are placed in the
automatically added to the target's :prop_tgt:`INCLUDE_DIRECTORIES`.
* This differs from CMake 3.7 and below; see their documentation for details.
+
+* For :prop_gbl:`multi configuration generators <GENERATOR_IS_MULTI_CONFIG>`,
+ the include directory is ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>``.
+
* See :prop_tgt:`AUTOGEN_BUILD_DIR`.
The :prop_tgt:`AUTOUIC` target property may be pre-set for all following
@@ -202,6 +213,24 @@ overrides options from the :prop_tgt:`AUTORCC_OPTIONS` target property.
Source files can be excluded from :prop_tgt:`AUTORCC` processing by
enabling :prop_sf:`SKIP_AUTORCC` or the broader :prop_sf:`SKIP_AUTOGEN`.
+Visual Studio Generators
+========================
+
+When using the :manual:`Visual Studio generators <cmake-generators(7)>`
+CMake tries to use a ``PRE_BUILD``
+:command:`custom command <add_custom_command>` instead
+of a :command:`custom target <add_custom_target>` for autogen.
+``PRE_BUILD`` can't be used when the autogen target depends on files.
+This happens when
+
+- :prop_tgt:`AUTOMOC` or :prop_tgt:`AUTOUIC` is enabled and the origin target
+ depends on :prop_sf:`GENERATED` files which aren't excluded from autogen by
+ :prop_sf:`SKIP_AUTOMOC`, :prop_sf:`SKIP_AUTOUIC`, :prop_sf:`SKIP_AUTOGEN`
+ or :policy:`CMP0071`
+- :prop_tgt:`AUTORCC` is enabled and a ``.qrc`` file is listed in
+ the origin target sources
+- :prop_tgt:`AUTOGEN_TARGET_DEPENDS` lists a source file
+
qtmain.lib on Windows
=====================
diff --git a/Help/manual/cmake-server.7.rst b/Help/manual/cmake-server.7.rst
index 9520cc140..c56e5a716 100644
--- a/Help/manual/cmake-server.7.rst
+++ b/Help/manual/cmake-server.7.rst
@@ -254,6 +254,11 @@ versions supported by the cmake server. These are JSON objects with "major" and
as experimental. These will contain the "isExperimental" key set to true. Enabling
these requires a special command line argument when starting the cmake server mode.
+Within a "major" version all "minor" versions are fully backwards compatible.
+New "minor" versions may introduce functionality in such a way that existing
+clients of the same "major" version will continue to work, provided they
+ignore keys in the output that they do not know about.
+
Example::
[== "CMake Server" ==[
@@ -268,8 +273,13 @@ The first request that the client may send to the server is of type "handshake".
This request needs to pass one of the "supportedProtocolVersions" of the "hello"
type response received earlier back to the server in the "protocolVersion" field.
+Giving the "major" version of the requested protocol version will make the server
+use the latest minor version of that protocol. Use this if you do not explicitly
+need to depend on a specific minor version.
-Each protocol version may request additional attributes to be present.
+If the build directory already contains a CMake cache, it is sufficient to set
+the "buildDirectory" attribute. To create a fresh build directory, additional
+attributes are required depending on the protocol version.
Protocol version 1.0 requires the following attributes to be set:
@@ -496,6 +506,9 @@ Each target object can have the following keys:
with the sysroot path.
"fileGroups"
contains the source files making up the target.
+"crossReferences"
+ contains the location of the target in the corresponding CMakeLists.txt
+ file and the locations of the related statements like "target_link_libraries"
FileGroups are used to group sources using similar settings together.
@@ -521,6 +534,16 @@ Each fileGroup object may contain the following keys:
All file paths in the fileGroup are either absolute or relative to the
sourceDirectory of the target.
+CrossReferences object is used to report the location of the target (including
+the entire call stack if the target is defined in a function) and the related
+"target_link_libraries", "target_include_directories", "target_compile_definitions"
+and "target_compile_options" statements.
+
+See the example below for details on the internal format of the "crossReferences" object.
+Line numbers stated in the "backtrace" entries are 1-based. The last entry of a backtrace
+is a special entry with missing "line" and "name" fields that specifies the initial
+CMakeLists.txt file.
+
Example::
[== "CMake Server" ==[
@@ -557,7 +580,34 @@ CMake will reply::
"linkerLanguage": "C",
"name": "cmForm",
"sourceDirectory": "/home/code/src/cmake/Source/CursesDialog/form",
- "type": "STATIC_LIBRARY"
+ "type": "STATIC_LIBRARY",
+ "crossReferences": {
+ "backtrace": [
+ {
+ "line": 7,
+ "name": "add_executable",
+ "path": "C:/full/path/CMakeLists.txt"
+ },
+ {
+ "path": "c:/full/path/CMakeLists.txt"
+ }
+ ],
+ "relatedStatements": [
+ {
+ "backtrace": [
+ {
+ "line": 8,
+ "name": "target_link_libraries",
+ "path": "c:/full/path/CMakeLists.txt"
+ },
+ {
+ "path": "c:/full/path/CMakeLists.txt"
+ }
+ ],
+ "type": "target_link_libraries"
+ }
+ ]
+ }
}
]
},
@@ -616,8 +666,7 @@ and will not survive the build directory getting cleaned out.
Type "cache"
^^^^^^^^^^^^
-The "cache" request can be used once a project is configured and will
-list the cached configuration values.
+The "cache" request will list the cached configuration values.
Example::
diff --git a/Help/manual/cmake-variables.7.rst b/Help/manual/cmake-variables.7.rst
index 1a2726dd3..2e369e37d 100644
--- a/Help/manual/cmake-variables.7.rst
+++ b/Help/manual/cmake-variables.7.rst
@@ -32,6 +32,7 @@ Variables that Provide Information
/variable/CMAKE_CURRENT_LIST_FILE
/variable/CMAKE_CURRENT_LIST_LINE
/variable/CMAKE_CURRENT_SOURCE_DIR
+ /variable/CMAKE_DIRECTORY_LABELS
/variable/CMAKE_DL_LIBS
/variable/CMAKE_EDIT_COMMAND
/variable/CMAKE_EXECUTABLE_SUFFIX
@@ -120,6 +121,7 @@ Variables that Change Behavior
/variable/CMAKE_AUTOMOC_RELAXED_MODE
/variable/CMAKE_BACKWARDS_COMPATIBILITY
/variable/CMAKE_BUILD_TYPE
+ /variable/CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES
/variable/CMAKE_CODELITE_USE_TARGETS
/variable/CMAKE_COLOR_MAKEFILE
/variable/CMAKE_CONFIGURATION_TYPES
@@ -268,7 +270,9 @@ Variables that Control the Build
/variable/CMAKE_ARCHIVE_OUTPUT_DIRECTORY
/variable/CMAKE_ARCHIVE_OUTPUT_DIRECTORY_CONFIG
/variable/CMAKE_AUTOMOC
+ /variable/CMAKE_AUTOMOC_COMPILER_PREDEFINES
/variable/CMAKE_AUTOMOC_DEPEND_FILTERS
+ /variable/CMAKE_AUTOMOC_MACRO_NAMES
/variable/CMAKE_AUTOMOC_MOC_OPTIONS
/variable/CMAKE_AUTORCC
/variable/CMAKE_AUTORCC_OPTIONS
@@ -300,6 +304,7 @@ Variables that Control the Build
/variable/CMAKE_IOS_INSTALL_COMBINED
/variable/CMAKE_LANG_CLANG_TIDY
/variable/CMAKE_LANG_COMPILER_LAUNCHER
+ /variable/CMAKE_LANG_CPPCHECK
/variable/CMAKE_LANG_CPPLINT
/variable/CMAKE_LANG_INCLUDE_WHAT_YOU_USE
/variable/CMAKE_LANG_VISIBILITY_PRESET
@@ -319,6 +324,7 @@ Variables that Control the Build
/variable/CMAKE_MODULE_LINKER_FLAGS_CONFIG
/variable/CMAKE_MODULE_LINKER_FLAGS_CONFIG_INIT
/variable/CMAKE_MODULE_LINKER_FLAGS_INIT
+ /variable/CMAKE_MSVCIDE_RUN_PATH
/variable/CMAKE_NINJA_OUTPUT_PATH_PREFIX
/variable/CMAKE_NO_BUILTIN_CHRPATH
/variable/CMAKE_NO_SYSTEM_FROM_IMPORTED
@@ -362,6 +368,7 @@ Variables for Languages
/variable/CMAKE_COMPILER_IS_GNUCC
/variable/CMAKE_COMPILER_IS_GNUCXX
/variable/CMAKE_COMPILER_IS_GNUG77
+ /variable/CMAKE_CUDA_HOST_COMPILER
/variable/CMAKE_CUDA_EXTENSIONS
/variable/CMAKE_CUDA_STANDARD
/variable/CMAKE_CUDA_STANDARD_REQUIRED
@@ -386,11 +393,14 @@ Variables for Languages
/variable/CMAKE_LANG_ARCHIVE_FINISH
/variable/CMAKE_LANG_COMPILER
/variable/CMAKE_LANG_COMPILER_ABI
+ /variable/CMAKE_LANG_COMPILER_ARCHITECTURE_ID
/variable/CMAKE_LANG_COMPILER_EXTERNAL_TOOLCHAIN
/variable/CMAKE_LANG_COMPILER_ID
/variable/CMAKE_LANG_COMPILER_LOADED
+ /variable/CMAKE_LANG_COMPILER_PREDEFINES_COMMAND
/variable/CMAKE_LANG_COMPILER_TARGET
/variable/CMAKE_LANG_COMPILER_VERSION
+ /variable/CMAKE_LANG_COMPILER_VERSION_INTERNAL
/variable/CMAKE_LANG_COMPILE_OBJECT
/variable/CMAKE_LANG_CREATE_SHARED_LIBRARY
/variable/CMAKE_LANG_CREATE_SHARED_MODULE
@@ -480,6 +490,7 @@ Variables for CTest
/variable/CTEST_GIT_UPDATE_OPTIONS
/variable/CTEST_HG_COMMAND
/variable/CTEST_HG_UPDATE_OPTIONS
+ /variable/CTEST_LABELS_FOR_SUBPROJECTS
/variable/CTEST_MEMORYCHECK_COMMAND
/variable/CTEST_MEMORYCHECK_COMMAND_OPTIONS
/variable/CTEST_MEMORYCHECK_SANITIZER_OPTIONS
diff --git a/Help/manual/cmake.1.rst b/Help/manual/cmake.1.rst
index ba925e8ec..6a2168321 100644
--- a/Help/manual/cmake.1.rst
+++ b/Help/manual/cmake.1.rst
@@ -69,11 +69,11 @@ Options
See `Find-Package Tool Mode`_.
``--graphviz=[file]``
- Generate graphviz of dependencies, see CMakeGraphVizOptions.cmake for more.
+ Generate graphviz of dependencies, see :module:`CMakeGraphVizOptions` for more.
Generate a graphviz input file that will contain all the library and
executable dependencies in the project. See the documentation for
- CMakeGraphVizOptions.cmake for more details.
+ :module:`CMakeGraphVizOptions` for more details.
``--system-information [file]``
Dump information about this system.
@@ -138,6 +138,8 @@ Options
.. include:: OPTIONS_HELP.txt
+.. _`Build Tool Mode`:
+
Build Tool Mode
===============
@@ -262,6 +264,36 @@ Available commands are:
351abe79cd3800b38cdfb25d45015a15 file1.txt
052f86c15bbde68af55c7f7b340ab639 file2.txt
+``sha1sum <file>...``
+ Create SHA1 checksum of files in ``sha1sum`` compatible format::
+
+ 4bb7932a29e6f73c97bb9272f2bdc393122f86e0 file1.txt
+ 1df4c8f318665f9a5f2ed38f55adadb7ef9f559c file2.txt
+
+``sha224sum <file>...``
+ Create SHA224 checksum of files in ``sha224sum`` compatible format::
+
+ b9b9346bc8437bbda630b0b7ddfc5ea9ca157546dbbf4c613192f930 file1.txt
+ 6dfbe55f4d2edc5fe5c9197bca51ceaaf824e48eba0cc453088aee24 file2.txt
+
+``sha256sum <file>...``
+ Create SHA256 checksum of files in ``sha256sum`` compatible format::
+
+ 76713b23615d31680afeb0e9efe94d47d3d4229191198bb46d7485f9cb191acc file1.txt
+ 15b682ead6c12dedb1baf91231e1e89cfc7974b3787c1e2e01b986bffadae0ea file2.txt
+
+``sha384sum <file>...``
+ Create SHA384 checksum of files in ``sha384sum`` compatible format::
+
+ acc049fedc091a22f5f2ce39a43b9057fd93c910e9afd76a6411a28a8f2b8a12c73d7129e292f94fc0329c309df49434 file1.txt
+ 668ddeb108710d271ee21c0f3acbd6a7517e2b78f9181c6a2ff3b8943af92b0195dcb7cce48aa3e17893173c0a39e23d file2.txt
+
+``sha512sum <file>...``
+ Create SHA512 checksum of files in ``sha512sum`` compatible format::
+
+ 2a78d7a6c5328cfb1467c63beac8ff21794213901eaadafd48e7800289afbc08e5fb3e86aa31116c945ee3d7bf2a6194489ec6101051083d1108defc8e1dba89 file1.txt
+ 7a0b54896fe5e70cca6dd643ad6f672614b189bf26f8153061c4d219474b05dad08c4e729af9f4b009f1a1a280cb625454bf587c690f4617c27e3aebdf3b7a2d file2.txt
+
``remove [-f] <file>...``
Remove the file(s). If any of the listed files already do not
exist, the command returns a non-zero exit code, but no message
diff --git a/Help/manual/ctest.1.rst b/Help/manual/ctest.1.rst
index a89c4e9bb..423f1ca91 100644
--- a/Help/manual/ctest.1.rst
+++ b/Help/manual/ctest.1.rst
@@ -250,6 +250,13 @@ Options
label associated with the tests run. If there are no labels on the
tests, nothing extra is printed.
+ ``--no-subproject-summary``
+ Disable timing summary information for subprojects.
+
+ This option tells ctest not to print summary information for each
+ subproject associated with the tests run. If there are no subprojects on the
+ tests, nothing extra is printed.
+
``--build-and-test <path-to-source> <path-to-build>``
Configure, build and run a test.
@@ -758,6 +765,15 @@ Configuration settings include:
* :module:`CTest` module variable: :variable:`CMAKE_COMMAND`
followed by :variable:`PROJECT_SOURCE_DIR`
+``LabelsForSubprojects``
+ Specify a semicolon-separated list of labels that will be treated as
+ subprojects. This mapping will be passed on to CDash when configure, test or
+ build results are submitted.
+
+ * `CTest Script`_ variable: :variable:`CTEST_LABELS_FOR_SUBPROJECTS`
+ * :module:`CTest` module variable: ``CTEST_LABELS_FOR_SUBPROJECTS``
+
+
.. _`CTest Build Step`:
CTest Build Step
@@ -780,6 +796,14 @@ Configuration settings include:
* :module:`CTest` module variable: ``DEFAULT_CTEST_CONFIGURATION_TYPE``,
initialized by the ``CMAKE_CONFIG_TYPE`` environment variable
+``LabelsForSubprojects``
+ Specify a semicolon-separated list of labels that will be treated as
+ subprojects. This mapping will be passed on to CDash when configure, test or
+ build results are submitted.
+
+ * `CTest Script`_ variable: :variable:`CTEST_LABELS_FOR_SUBPROJECTS`
+ * :module:`CTest` module variable: ``CTEST_LABELS_FOR_SUBPROJECTS``
+
``MakeCommand``
Command-line to launch the software build process.
It will be executed in the location specified by the
@@ -815,6 +839,15 @@ Arguments to the command may specify some of the step settings.
Configuration settings include:
+``LabelsForSubprojects``
+ Specify a semicolon-separated list of labels that will be treated as
+ subprojects. This mapping will be passed on to CDash when configure, test or
+ build results are submitted.
+
+ * `CTest Script`_ variable: :variable:`CTEST_LABELS_FOR_SUBPROJECTS`
+ * :module:`CTest` module variable: ``CTEST_LABELS_FOR_SUBPROJECTS``
+
+
``TestLoad``
While running tests in parallel (e.g. with ``-j``), try not to start
tests when they may cause the CPU load to pass above a given threshold.
@@ -853,6 +886,8 @@ Configuration settings include:
* `CTest Script`_ variable: :variable:`CTEST_COVERAGE_EXTRA_FLAGS`
* :module:`CTest` module variable: ``COVERAGE_EXTRA_FLAGS``
+ These options are the first arguments passed to ``CoverageCommand``.
+
.. _`CTest MemCheck Step`:
CTest MemCheck Step
diff --git a/Help/module/CPackFreeBSD.rst b/Help/module/CPackFreeBSD.rst
new file mode 100644
index 000000000..083f0cbfa
--- /dev/null
+++ b/Help/module/CPackFreeBSD.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/CPackFreeBSD.cmake
diff --git a/Help/module/FindOpenACC.rst b/Help/module/FindOpenACC.rst
new file mode 100644
index 000000000..dda330831
--- /dev/null
+++ b/Help/module/FindOpenACC.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindOpenACC.cmake
diff --git a/Help/module/FindPatch.rst b/Help/module/FindPatch.rst
new file mode 100644
index 000000000..ba5e9102d
--- /dev/null
+++ b/Help/module/FindPatch.rst
@@ -0,0 +1 @@
+.. cmake-module:: ../../Modules/FindPatch.cmake
diff --git a/Help/policy/CMP0040.rst b/Help/policy/CMP0040.rst
index d46baf647..0afe5895d 100644
--- a/Help/policy/CMP0040.rst
+++ b/Help/policy/CMP0040.rst
@@ -2,7 +2,7 @@ CMP0040
-------
The target in the ``TARGET`` signature of :command:`add_custom_command`
-must exist and must be defined in current directory.
+must exist and must be defined in the current directory.
CMake 2.8.12 and lower silently ignored a custom command created with
the ``TARGET`` signature of :command:`add_custom_command`
diff --git a/Help/policy/CMP0070.rst b/Help/policy/CMP0070.rst
new file mode 100644
index 000000000..0fb361779
--- /dev/null
+++ b/Help/policy/CMP0070.rst
@@ -0,0 +1,25 @@
+CMP0070
+-------
+
+Define :command:`file(GENERATE)` behavior for relative paths.
+
+CMake 3.10 and newer define that relative paths given to ``INPUT`` and
+``OUTPUT`` arguments of ``file(GENERATE)`` are interpreted relative to the
+current source and binary directories, respectively. CMake 3.9 and lower did
+not define any behavior for relative paths but did not diagnose them either
+and accidentally treated them relative to the process working directory.
+Policy ``CMP0070`` provides compatibility with projects that used the old
+undefined behavior.
+
+This policy affects behavior of relative paths given to ``file(GENERATE)``.
+The ``OLD`` behavior for this policy is to treat the paths relative to the
+working directory of CMake. The ``NEW`` behavior for this policy is to
+interpret relative paths with respect to the current source or binary
+directory of the caller.
+
+This policy was introduced in CMake version 3.10. 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/policy/CMP0071.rst b/Help/policy/CMP0071.rst
new file mode 100644
index 000000000..ee33aa1c2
--- /dev/null
+++ b/Help/policy/CMP0071.rst
@@ -0,0 +1,42 @@
+CMP0071
+-------
+
+Let :prop_tgt:`AUTOMOC` and :prop_tgt:`AUTOUIC` process
+:prop_sf:`GENERATED` files.
+
+Since version 3.10, CMake processes **regular** and :prop_sf:`GENERATED`
+source files in :prop_tgt:`AUTOMOC` and :prop_tgt:`AUTOUIC`.
+In earlier CMake versions, only **regular** source files were processed.
+:prop_sf:`GENERATED` source files were ignored silently.
+
+This policy affects how source files that are :prop_sf:`GENERATED`
+get treated in :prop_tgt:`AUTOMOC` and :prop_tgt:`AUTOUIC`.
+
+The ``OLD`` behavior for this policy is to ignore :prop_sf:`GENERATED`
+source files in :prop_tgt:`AUTOMOC` and :prop_tgt:`AUTOUIC`.
+
+The ``NEW`` behavior for this policy is to process :prop_sf:`GENERATED`
+source files in :prop_tgt:`AUTOMOC` and :prop_tgt:`AUTOUIC` just like regular
+source files.
+
+.. note::
+
+ To silence the CMP0071 warning source files can be excluded from
+ :prop_tgt:`AUTOMOC` and :prop_tgt:`AUTOUIC` processing by setting the
+ source file properties :prop_sf:`SKIP_AUTOMOC`, :prop_sf:`SKIP_AUTOUIC` or
+ :prop_sf:`SKIP_AUTOGEN`.
+
+Source skip example::
+
+ # ...
+ set_property(SOURCE /path/to/file1.h PROPERTY SKIP_AUTOMOC ON)
+ set_property(SOURCE /path/to/file2.h PROPERTY SKIP_AUTOUIC ON)
+ set_property(SOURCE /path/to/file3.h PROPERTY SKIP_AUTOGEN ON)
+ # ...
+
+This policy was introduced in CMake version 3.10. 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_dir/LABELS.rst b/Help/prop_dir/LABELS.rst
new file mode 100644
index 000000000..de27d906e
--- /dev/null
+++ b/Help/prop_dir/LABELS.rst
@@ -0,0 +1,13 @@
+LABELS
+------
+
+Specify a list of text labels associated with a directory and all of its
+subdirectories. This is equivalent to setting the :prop_tgt:`LABELS` target
+property and the :prop_test:`LABELS` test property on all targets and tests in
+the current directory and subdirectories. Note: Launchers must enabled to
+propagate labels to targets.
+
+The :variable:`CMAKE_DIRECTORY_LABELS` variable can be used to initialize this
+property.
+
+The list is reported in dashboard submissions.
diff --git a/Help/prop_dir/TEST_INCLUDE_FILE.rst b/Help/prop_dir/TEST_INCLUDE_FILE.rst
index e47795191..31b23829d 100644
--- a/Help/prop_dir/TEST_INCLUDE_FILE.rst
+++ b/Help/prop_dir/TEST_INCLUDE_FILE.rst
@@ -1,7 +1,9 @@
TEST_INCLUDE_FILE
-----------------
+Deprecated. Use :prop_dir:`TEST_INCLUDE_FILES` instead.
+
A cmake file that will be included when ctest is run.
-If you specify TEST_INCLUDE_FILE, that file will be included and
+If you specify ``TEST_INCLUDE_FILE``, that file will be included and
processed when ctest is run on the directory.
diff --git a/Help/prop_dir/TEST_INCLUDE_FILES.rst b/Help/prop_dir/TEST_INCLUDE_FILES.rst
new file mode 100644
index 000000000..c3e4602b0
--- /dev/null
+++ b/Help/prop_dir/TEST_INCLUDE_FILES.rst
@@ -0,0 +1,7 @@
+TEST_INCLUDE_FILES
+------------------
+
+A list of cmake files that will be included when ctest is run.
+
+If you specify ``TEST_INCLUDE_FILES``, those files will be included and
+processed when ctest is run on the directory.
diff --git a/Help/prop_sf/AUTORCC_OPTIONS.rst b/Help/prop_sf/AUTORCC_OPTIONS.rst
index d9dc4d33e..2bec033e4 100644
--- a/Help/prop_sf/AUTORCC_OPTIONS.rst
+++ b/Help/prop_sf/AUTORCC_OPTIONS.rst
@@ -9,5 +9,14 @@ optional ``OPTIONS`` argument of the :module:`qt4_add_resources() <FindQt4>` mac
By default it is empty.
-The options set on the ``.qrc`` source file may override :prop_tgt:`AUTORCC_OPTIONS` set
-on the target.
+The options set on the ``.qrc`` source file may override
+:prop_tgt:`AUTORCC_OPTIONS` set on the target.
+
+EXAMPLE
+^^^^^^^
+
+.. code-block:: cmake
+
+ # ...
+ set_property(SOURCE resources.qrc PROPERTY AUTORCC_OPTIONS "--compress;9")
+ # ...
diff --git a/Help/prop_sf/AUTOUIC_OPTIONS.rst b/Help/prop_sf/AUTOUIC_OPTIONS.rst
index bb48da90f..e2f47ecd2 100644
--- a/Help/prop_sf/AUTOUIC_OPTIONS.rst
+++ b/Help/prop_sf/AUTOUIC_OPTIONS.rst
@@ -4,11 +4,20 @@ AUTOUIC_OPTIONS
Additional options for ``uic`` when using :prop_tgt:`AUTOUIC`
This property holds additional command line options
-which will be used when ``uic`` is executed during the build via :prop_tgt:`AUTOUIC`,
-i.e. it is equivalent to the optional ``OPTIONS`` argument of the
-:module:`qt4_wrap_ui() <FindQt4>` macro.
+which will be used when ``uic`` is executed during the build via
+:prop_tgt:`AUTOUIC`, i.e. it is equivalent to the optional ``OPTIONS``
+argument of the :module:`qt4_wrap_ui() <FindQt4>` macro.
By default it is empty.
-The options set on the ``.ui`` source file may override :prop_tgt:`AUTOUIC_OPTIONS` set
-on the target.
+The options set on the ``.ui`` source file may override
+:prop_tgt:`AUTOUIC_OPTIONS` set on the target.
+
+EXAMPLE
+^^^^^^^
+
+.. code-block:: cmake
+
+ # ...
+ set_property(SOURCE widget.ui PROPERTY AUTOUIC_OPTIONS "--no-protection")
+ # ...
diff --git a/Help/prop_sf/SKIP_AUTOGEN.rst b/Help/prop_sf/SKIP_AUTOGEN.rst
index 6bf2409b2..f31185a5b 100644
--- a/Help/prop_sf/SKIP_AUTOGEN.rst
+++ b/Help/prop_sf/SKIP_AUTOGEN.rst
@@ -4,5 +4,14 @@ SKIP_AUTOGEN
Exclude the source file from :prop_tgt:`AUTOMOC`, :prop_tgt:`AUTOUIC` and
:prop_tgt:`AUTORCC` processing (for Qt projects).
-For finer control see :prop_sf:`SKIP_AUTOMOC`, :prop_sf:`SKIP_AUTOUIC` and
-:prop_sf:`SKIP_AUTORCC`.
+For finer exclusion control see :prop_sf:`SKIP_AUTOMOC`,
+:prop_sf:`SKIP_AUTOUIC` and :prop_sf:`SKIP_AUTORCC`.
+
+EXAMPLE
+^^^^^^^
+
+.. code-block:: cmake
+
+ # ...
+ set_property(SOURCE file.h PROPERTY SKIP_AUTOGEN ON)
+ # ...
diff --git a/Help/prop_sf/SKIP_AUTOMOC.rst b/Help/prop_sf/SKIP_AUTOMOC.rst
index 2245ca639..a9294489a 100644
--- a/Help/prop_sf/SKIP_AUTOMOC.rst
+++ b/Help/prop_sf/SKIP_AUTOMOC.rst
@@ -3,4 +3,13 @@ SKIP_AUTOMOC
Exclude the source file from :prop_tgt:`AUTOMOC` processing (for Qt projects).
-For broader control see :prop_sf:`SKIP_AUTOGEN`
+For broader exclusion control see :prop_sf:`SKIP_AUTOGEN`.
+
+EXAMPLE
+^^^^^^^
+
+.. code-block:: cmake
+
+ # ...
+ set_property(SOURCE file.h PROPERTY SKIP_AUTOMOC ON)
+ # ...
diff --git a/Help/prop_sf/SKIP_AUTORCC.rst b/Help/prop_sf/SKIP_AUTORCC.rst
index 394d8f8cf..bccccfc93 100644
--- a/Help/prop_sf/SKIP_AUTORCC.rst
+++ b/Help/prop_sf/SKIP_AUTORCC.rst
@@ -3,4 +3,13 @@ SKIP_AUTORCC
Exclude the source file from :prop_tgt:`AUTORCC` processing (for Qt projects).
-For broader control see :prop_sf:`SKIP_AUTOGEN`
+For broader exclusion control see :prop_sf:`SKIP_AUTOGEN`.
+
+EXAMPLE
+^^^^^^^
+
+.. code-block:: cmake
+
+ # ...
+ set_property(SOURCE file.qrc PROPERTY SKIP_AUTORCC ON)
+ # ...
diff --git a/Help/prop_sf/SKIP_AUTOUIC.rst b/Help/prop_sf/SKIP_AUTOUIC.rst
index 50f78ef66..8c962dbfe 100644
--- a/Help/prop_sf/SKIP_AUTOUIC.rst
+++ b/Help/prop_sf/SKIP_AUTOUIC.rst
@@ -3,4 +3,18 @@ SKIP_AUTOUIC
Exclude the source file from :prop_tgt:`AUTOUIC` processing (for Qt projects).
-For broader control see :prop_sf:`SKIP_AUTOGEN`
+:prop_sf:`SKIP_AUTOUIC` can be set on C++ header and source files and on
+``.ui`` files.
+
+For broader exclusion control see :prop_sf:`SKIP_AUTOGEN`.
+
+EXAMPLE
+^^^^^^^
+
+.. code-block:: cmake
+
+ # ...
+ set_property(SOURCE file.h PROPERTY SKIP_AUTOUIC ON)
+ set_property(SOURCE file.cpp PROPERTY SKIP_AUTOUIC ON)
+ set_property(SOURCE widget.ui PROPERTY SKIP_AUTOUIC ON)
+ # ...
diff --git a/Help/prop_sf/VS_SHADER_OUTPUT_HEADER_FILE.rst b/Help/prop_sf/VS_SHADER_OUTPUT_HEADER_FILE.rst
new file mode 100644
index 000000000..e6763d332
--- /dev/null
+++ b/Help/prop_sf/VS_SHADER_OUTPUT_HEADER_FILE.rst
@@ -0,0 +1,5 @@
+VS_SHADER_OUTPUT_HEADER_FILE
+----------------------------
+
+Set filename for output header file containing object code of a ``.hlsl``
+source file.
diff --git a/Help/prop_sf/VS_SHADER_VARIABLE_NAME.rst b/Help/prop_sf/VS_SHADER_VARIABLE_NAME.rst
new file mode 100644
index 000000000..1a5e36921
--- /dev/null
+++ b/Help/prop_sf/VS_SHADER_VARIABLE_NAME.rst
@@ -0,0 +1,5 @@
+VS_SHADER_VARIABLE_NAME
+-----------------------
+
+Set name of variable in header file containing object code of a ``.hlsl``
+source file.
diff --git a/Help/prop_test/FIXTURES_CLEANUP.rst b/Help/prop_test/FIXTURES_CLEANUP.rst
index f0a4be0ec..3075b4d48 100644
--- a/Help/prop_test/FIXTURES_CLEANUP.rst
+++ b/Help/prop_test/FIXTURES_CLEANUP.rst
@@ -2,7 +2,8 @@ FIXTURES_CLEANUP
----------------
Specifies a list of fixtures for which the test is to be treated as a cleanup
-test.
+test. These fixture names are distinct from test case names and are not
+required to have any similarity to the names of tests associated with them.
Fixture cleanup tests are ordinary tests with all of the usual test
functionality. Setting the ``FIXTURES_CLEANUP`` property for a test has two
diff --git a/Help/prop_test/FIXTURES_REQUIRED.rst b/Help/prop_test/FIXTURES_REQUIRED.rst
index e37dfb57d..e3f60c426 100644
--- a/Help/prop_test/FIXTURES_REQUIRED.rst
+++ b/Help/prop_test/FIXTURES_REQUIRED.rst
@@ -2,7 +2,7 @@ FIXTURES_REQUIRED
-----------------
Specifies a list of fixtures the test requires. Fixture names are case
-sensitive.
+sensitive and they are not required to have any similarity to test names.
Fixtures are a way to attach setup and cleanup tasks to a set of tests. If a
test requires a given fixture, then all tests marked as setup tasks for that
@@ -19,7 +19,9 @@ some setup tests fail.
When CTest is asked to execute only a subset of tests (e.g. by the use of
regular expressions or when run with the ``--rerun-failed`` command line
option), it will automatically add any setup or cleanup tests for fixtures
-required by any of the tests that are in the execution set.
+required by any of the tests that are in the execution set. This behavior can
+be overridden with the ``-FS``, ``-FC`` and ``-FA`` command line options to
+:manual:`ctest(1)` if desired.
Since setup and cleanup tasks are also tests, they can have an ordering
specified by the :prop_test:`DEPENDS` test property just like any other tests.
diff --git a/Help/prop_test/FIXTURES_SETUP.rst b/Help/prop_test/FIXTURES_SETUP.rst
index a22021592..fdb21cc76 100644
--- a/Help/prop_test/FIXTURES_SETUP.rst
+++ b/Help/prop_test/FIXTURES_SETUP.rst
@@ -2,14 +2,15 @@ FIXTURES_SETUP
--------------
Specifies a list of fixtures for which the test is to be treated as a setup
-test.
+test. These fixture names are distinct from test case names and are not
+required to have any similarity to the names of tests associated with them.
Fixture setup tests are ordinary tests with all of the usual test
functionality. Setting the ``FIXTURES_SETUP`` property for a test has two
primary effects:
- CTest will ensure the test executes before any other test which lists the
- fixture(s) in its :prop_test:`FIXTURES_REQUIRED` property.
+ fixture name(s) in its :prop_test:`FIXTURES_REQUIRED` property.
- If CTest is asked to run only a subset of tests (e.g. using regular
expressions or the ``--rerun-failed`` option) and the setup test is not in
diff --git a/Help/prop_test/PROCESSORS.rst b/Help/prop_test/PROCESSORS.rst
index 763b6d003..a1211fb69 100644
--- a/Help/prop_test/PROCESSORS.rst
+++ b/Help/prop_test/PROCESSORS.rst
@@ -1,8 +1,13 @@
PROCESSORS
----------
-How many process slots this test requires
+Set to specify how many process slots this test requires.
Denotes the number of processors that this test will require. This is
typically used for MPI tests, and should be used in conjunction with
-the ctest_test PARALLEL_LEVEL option.
+the :command:`ctest_test` ``PARALLEL_LEVEL`` option.
+
+This will also be used to display a weighted test timing result in label and
+subproject summaries in the command line output of :manual:`ctest(1)`. The wall
+clock time for the test run will be multiplied by this property to give a
+better idea of how much cpu resource CTest allocated for the test.
diff --git a/Help/prop_tgt/AUTOMOC.rst b/Help/prop_tgt/AUTOMOC.rst
index 0171d20e7..9e5261fd3 100644
--- a/Help/prop_tgt/AUTOMOC.rst
+++ b/Help/prop_tgt/AUTOMOC.rst
@@ -5,44 +5,49 @@ Should the target be processed with automoc (for Qt projects).
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.
+:module:`QT4_WRAP_CPP() <FindQt4>` or QT5_WRAP_CPP() macro.
+Currently Qt4 and Qt5 are supported.
When this property is set ``ON``, CMake will scan the header and
source files at build time and invoke moc accordingly.
* If an ``#include`` statement like ``#include "moc_<basename>.cpp"`` is found,
- the ``Q_OBJECT`` or ``Q_GADGET`` macros are expected in an otherwise empty
- line of the ``<basename>.h(xx)`` header file. ``moc`` is run on the header
+ a macro from :prop_tgt:`AUTOMOC_MACRO_NAMES` is expected to appear in the
+ ``<basename>.h(xx)`` header file. ``moc`` is run on the header
file to generate ``moc_<basename>.cpp`` in the
``<AUTOGEN_BUILD_DIR>/include`` directory which is automatically added
to the target's :prop_tgt:`INCLUDE_DIRECTORIES`.
This allows the compiler to find the included ``moc_<basename>.cpp`` file
regardless of the location the original source.
+ * For :prop_gbl:`multi configuration generators <GENERATOR_IS_MULTI_CONFIG>`,
+ the include directory is ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>``.
+
* See :prop_tgt:`AUTOGEN_BUILD_DIR`.
* If an ``#include`` statement like ``#include "<basename>.moc"`` is found,
- then ``Q_OBJECT`` or ``Q_GADGET`` macros are expected in the current source
- file and ``moc`` is run on the source file itself.
+ a macro from :prop_tgt:`AUTOMOC_MACRO_NAMES` is expected to appear in the
+ source file and ``moc`` is run on the source file itself.
* Header files that are not included by an ``#include "moc_<basename>.cpp"``
- statement are nonetheless scanned for ``Q_OBJECT`` or ``Q_GADGET`` macros.
+ statement are nonetheless scanned for a macro out of
+ :prop_tgt:`AUTOMOC_MACRO_NAMES`.
The resulting ``moc_<basename>.cpp`` files are generated in custom
directories and automatically included in a generated
``<AUTOGEN_BUILD_DIR>/mocs_compilation.cpp`` file,
which is compiled as part of the target.
* The custom directories with checksum
- based names help to avoid name collisions for moc files with the same
+ based names help to avoid name collisions for ``moc`` files with the same
``<basename>``.
* See :prop_tgt:`AUTOGEN_BUILD_DIR`.
* Additionally, header files with the same base name as a source file,
(like ``<basename>.h``) or ``_p`` appended to the base name (like
- ``<basename>_p.h``), are parsed for ``Q_OBJECT`` or ``Q_GADGET`` macros,
- and if found, ``moc`` is also executed on those files.
+ ``<basename>_p.h``), are scanned for a macro out of
+ :prop_tgt:`AUTOMOC_MACRO_NAMES`, and if found, ``moc``
+ is also executed on those files.
* ``AUTOMOC`` always checks multiple header alternative extensions,
such as ``hpp``, ``hxx``, etc. when searching for headers.
@@ -53,11 +58,11 @@ source files at build time and invoke moc accordingly.
This property is initialized by the value of the :variable:`CMAKE_AUTOMOC`
variable if it is set when a target is created.
-Additional command line options for moc can be set via the
+Additional command line options for ``moc`` can be set via the
:prop_tgt:`AUTOMOC_MOC_OPTIONS` property.
By enabling the :variable:`CMAKE_AUTOMOC_RELAXED_MODE` variable the
-rules for searching the files which will be processed by moc can be relaxed.
+rules for searching the files which will be processed by ``moc`` can be relaxed.
See the documentation for this variable for more details.
The global property :prop_gbl:`AUTOGEN_TARGETS_FOLDER` can be used to group the
@@ -66,9 +71,14 @@ automoc targets together in an IDE, e.g. in MSVS.
The global property :prop_gbl:`AUTOGEN_SOURCE_GROUP` can be used to group
files generated by :prop_tgt:`AUTOMOC` together in an IDE, e.g. in MSVS.
+Additional macro names to search for can be added to :prop_tgt:`AUTOMOC_MACRO_NAMES`.
+
Additional ``moc`` dependency file names can be extracted from source code
by using :prop_tgt:`AUTOMOC_DEPEND_FILTERS`.
+Compiler pre definitions for ``moc`` are written to a ``moc_predefs.h`` file
+which is controlled by :prop_tgt:`AUTOMOC_COMPILER_PREDEFINES`.
+
Source C++ files can be excluded from :prop_tgt:`AUTOMOC` processing by
enabling :prop_sf:`SKIP_AUTOMOC` or the broader :prop_sf:`SKIP_AUTOGEN`.
diff --git a/Help/prop_tgt/AUTOMOC_COMPILER_PREDEFINES.rst b/Help/prop_tgt/AUTOMOC_COMPILER_PREDEFINES.rst
new file mode 100644
index 000000000..57a647f3c
--- /dev/null
+++ b/Help/prop_tgt/AUTOMOC_COMPILER_PREDEFINES.rst
@@ -0,0 +1,24 @@
+AUTOMOC_COMPILER_PREDEFINES
+---------------------------
+
+Boolean value used by :prop_tgt:`AUTOMOC` to determine if the
+compiler pre definitions file ``moc_predefs.h`` should be generated.
+
+CMake generates a ``moc_predefs.h`` file with compiler pre definitions
+from the output of the command defined in
+:variable:`CMAKE_CXX_COMPILER_PREDEFINES_COMMAND <CMAKE_<LANG>_COMPILER_PREDEFINES_COMMAND>`
+when
+
+- :prop_tgt:`AUTOMOC` is enabled,
+- :prop_tgt:`AUTOMOC_COMPILER_PREDEFINES` is enabled,
+- :variable:`CMAKE_CXX_COMPILER_PREDEFINES_COMMAND <CMAKE_<LANG>_COMPILER_PREDEFINES_COMMAND>` isn't empty and
+- the Qt version is greater or equal 5.8.
+
+The ``moc_predefs.h`` file, which is generated in :prop_tgt:`AUTOGEN_BUILD_DIR`,
+is passed to ``moc`` as the argument to the ``--include`` option.
+
+By default :prop_tgt:`AUTOMOC_COMPILER_PREDEFINES` is initialized from
+:variable:`CMAKE_AUTOMOC_COMPILER_PREDEFINES`, which is ON by default.
+
+See the :manual:`cmake-qt(7)` manual for more information on using CMake
+with Qt.
diff --git a/Help/prop_tgt/AUTOMOC_DEPEND_FILTERS.rst b/Help/prop_tgt/AUTOMOC_DEPEND_FILTERS.rst
index 810cbf4ae..b738ecf05 100644
--- a/Help/prop_tgt/AUTOMOC_DEPEND_FILTERS.rst
+++ b/Help/prop_tgt/AUTOMOC_DEPEND_FILTERS.rst
@@ -25,7 +25,7 @@ with Qt.
Example
--------
+^^^^^^^
Consider a file ``FOO.hpp`` holds a custom macro ``OBJ_JSON_FILE`` and we
want the ``moc`` file to depend on the macro`s file name argument::
diff --git a/Help/prop_tgt/AUTOMOC_MACRO_NAMES.rst b/Help/prop_tgt/AUTOMOC_MACRO_NAMES.rst
new file mode 100644
index 000000000..a5ad9d5ec
--- /dev/null
+++ b/Help/prop_tgt/AUTOMOC_MACRO_NAMES.rst
@@ -0,0 +1,32 @@
+AUTOMOC_MACRO_NAMES
+-------------------
+
+A :ref:`;-list <CMake Language Lists>` list of macro names used by
+:prop_tgt:`AUTOMOC` to determine if a C++ file needs to be processed by ``moc``.
+
+This property is only used if the :prop_tgt:`AUTOMOC` property is ``ON``
+for this target.
+
+When running :prop_tgt:`AUTOMOC`, CMake searches for the strings listed in
+:prop_tgt:`AUTOMOC_MACRO_NAMES` in C++ source and header files.
+If any of the strings is found
+
+- as the first non space string on a new line or
+- as the first non space string after a ``{`` on a new line,
+
+then the file will be processed by ``moc``.
+
+By default :prop_tgt:`AUTOMOC_MACRO_NAMES` is initialized from
+:variable:`CMAKE_AUTOMOC_MACRO_NAMES`.
+
+See the :manual:`cmake-qt(7)` manual for more information on using CMake
+with Qt.
+
+Example
+^^^^^^^
+
+In this case the the ``Q_OBJECT`` macro is hidden inside an other macro
+called ``CUSTOM_MACRO``. To let CMake know that source files, that contain
+``CUSTOM_MACRO``, need to be ``moc`` processed, we call::
+
+ set_property(TARGET tgt APPEND PROPERTY AUTOMOC_MACRO_NAMES "CUSTOM_MACRO")
diff --git a/Help/prop_tgt/AUTORCC_OPTIONS.rst b/Help/prop_tgt/AUTORCC_OPTIONS.rst
index 8a0f632c2..d6ade5adb 100644
--- a/Help/prop_tgt/AUTORCC_OPTIONS.rst
+++ b/Help/prop_tgt/AUTORCC_OPTIONS.rst
@@ -19,3 +19,12 @@ set on the ``.qrc`` source file.
See the :manual:`cmake-qt(7)` manual for more information on using CMake
with Qt.
+
+EXAMPLE
+^^^^^^^
+
+.. code-block:: cmake
+
+ # ...
+ set_property(TARGET tgt PROPERTY AUTORCC_OPTIONS "--compress;9")
+ # ...
diff --git a/Help/prop_tgt/AUTOUIC.rst b/Help/prop_tgt/AUTOUIC.rst
index 6493bbc78..1791384fc 100644
--- a/Help/prop_tgt/AUTOUIC.rst
+++ b/Help/prop_tgt/AUTOUIC.rst
@@ -17,6 +17,9 @@ optional :prop_tgt:`AUTOUIC_SEARCH_PATHS` of the target.
``<AUTOGEN_BUILD_DIR>/include``,
which is automatically added to the target's :prop_tgt:`INCLUDE_DIRECTORIES`.
+* For :prop_gbl:`multi configuration generators <GENERATOR_IS_MULTI_CONFIG>`,
+ the include directory is ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>``.
+
* See :prop_tgt:`AUTOGEN_BUILD_DIR`.
This property is initialized by the value of the :variable:`CMAKE_AUTOUIC`
diff --git a/Help/prop_tgt/AUTOUIC_OPTIONS.rst b/Help/prop_tgt/AUTOUIC_OPTIONS.rst
index 9fb042ea6..3f613b952 100644
--- a/Help/prop_tgt/AUTOUIC_OPTIONS.rst
+++ b/Help/prop_tgt/AUTOUIC_OPTIONS.rst
@@ -23,3 +23,12 @@ expressions.
See the :manual:`cmake-qt(7)` manual for more information on using CMake
with Qt.
+
+EXAMPLE
+^^^^^^^
+
+.. code-block:: cmake
+
+ # ...
+ set_property(TARGET tgt PROPERTY AUTOUIC_OPTIONS "--no-protection")
+ # ...
diff --git a/Help/prop_tgt/CUDA_STANDARD.rst b/Help/prop_tgt/CUDA_STANDARD.rst
index b26281471..a3a2f5689 100644
--- a/Help/prop_tgt/CUDA_STANDARD.rst
+++ b/Help/prop_tgt/CUDA_STANDARD.rst
@@ -7,7 +7,7 @@ This property specifies the CUDA/C++ standard whose features are requested
to build this target. For some compilers, this results in adding a
flag such as ``-std=gnu++11`` to the compile line.
-Supported values are ``98``, ``11``.
+Supported values are ``98``, ``11``, ``14``.
If the value requested does not result in a compile flag being added for
the compiler in use, a previous standard flag will be added instead. This
diff --git a/Help/prop_tgt/CXX_STANDARD.rst b/Help/prop_tgt/CXX_STANDARD.rst
index 30a612db6..0762033d4 100644
--- a/Help/prop_tgt/CXX_STANDARD.rst
+++ b/Help/prop_tgt/CXX_STANDARD.rst
@@ -6,7 +6,8 @@ The C++ standard whose features are requested to build this target.
This property specifies the C++ standard whose features are requested
to build this target. For some compilers, this results in adding a
flag such as ``-std=gnu++11`` to the compile line. For compilers that
-have no notion of a standard level, such as MSVC, this has no effect.
+have no notion of a standard level, such as Microsoft Visual C++ before
+2015 Update 3, this has no effect.
Supported values are ``98``, ``11``, ``14``, and ``17``.
diff --git a/Help/prop_tgt/C_STANDARD.rst b/Help/prop_tgt/C_STANDARD.rst
index 815a68676..e7f7904f2 100644
--- a/Help/prop_tgt/C_STANDARD.rst
+++ b/Help/prop_tgt/C_STANDARD.rst
@@ -6,7 +6,8 @@ The C standard whose features are requested to build this target.
This property specifies the C standard whose features are requested
to build this target. For some compilers, this results in adding a
flag such as ``-std=gnu11`` to the compile line. For compilers that
-have no notion of a standard level, such as MSVC, this has no effect.
+have no notion of a standard level, such as Microsoft Visual C++ before
+2015 Update 3, this has no effect.
Supported values are ``90``, ``99`` and ``11``.
diff --git a/Help/prop_tgt/LANG_COMPILER_LAUNCHER.rst b/Help/prop_tgt/LANG_COMPILER_LAUNCHER.rst
index 0fe0b31e5..28925fcc1 100644
--- a/Help/prop_tgt/LANG_COMPILER_LAUNCHER.rst
+++ b/Help/prop_tgt/LANG_COMPILER_LAUNCHER.rst
@@ -1,7 +1,8 @@
<LANG>_COMPILER_LAUNCHER
------------------------
-This property is implemented only when ``<LANG>`` is ``C`` or ``CXX``.
+This property is implemented only when ``<LANG>`` is ``C``, ``CXX``,
+or ``CUDA``.
Specify a :ref:`;-list <CMake Language Lists>` containing a command line
for a compiler launching tool. The :ref:`Makefile Generators` and the
diff --git a/Help/prop_tgt/LANG_CPPCHECK.rst b/Help/prop_tgt/LANG_CPPCHECK.rst
new file mode 100644
index 000000000..5f8be00f1
--- /dev/null
+++ b/Help/prop_tgt/LANG_CPPCHECK.rst
@@ -0,0 +1,13 @@
+<LANG>_CPPCHECK
+---------------
+
+This property is supported only when ``<LANG>`` is ``C`` or ``CXX``.
+
+Specify a :ref:`;-list <CMake Language Lists>` containing a command line
+for the ``cppcheck`` static analysis tool. The :ref:`Makefile Generators`
+and the :generator:`Ninja` generator will run ``cppcheck`` along with the
+compiler and report any problems.
+
+This property is initialized by the value of the
+:variable:`CMAKE_<LANG>_CPPCHECK` variable if it is set when a target is
+created.
diff --git a/Help/prop_tgt/MACOSX_BUNDLE.rst b/Help/prop_tgt/MACOSX_BUNDLE.rst
index 7cd80462a..f9e11ee3e 100644
--- a/Help/prop_tgt/MACOSX_BUNDLE.rst
+++ b/Help/prop_tgt/MACOSX_BUNDLE.rst
@@ -6,7 +6,7 @@ Build an executable as an Application Bundle on OS X or iOS.
When this property is set to ``TRUE`` the executable when built on OS X
or iOS will be created as an application bundle. This makes it
a GUI executable that can be launched from the Finder. See the
-:prop_tgt:`MACOSX_FRAMEWORK_INFO_PLIST` target property for information about
+:prop_tgt:`MACOSX_BUNDLE_INFO_PLIST` target property for information about
creation of the ``Info.plist`` file for the application bundle.
This property is initialized by the value of the variable
:variable:`CMAKE_MACOSX_BUNDLE` if it is set when a target is created.
diff --git a/Help/prop_tgt/NO_SYSTEM_FROM_IMPORTED.rst b/Help/prop_tgt/NO_SYSTEM_FROM_IMPORTED.rst
index 070dd3018..880343de4 100644
--- a/Help/prop_tgt/NO_SYSTEM_FROM_IMPORTED.rst
+++ b/Help/prop_tgt/NO_SYSTEM_FROM_IMPORTED.rst
@@ -1,11 +1,15 @@
NO_SYSTEM_FROM_IMPORTED
-----------------------
-Do not treat includes from IMPORTED target interfaces as SYSTEM.
+Do not treat include directories from the interfaces of consumed
+:ref:`imported targets` as ``SYSTEM``.
-The contents of the INTERFACE_INCLUDE_DIRECTORIES of IMPORTED targets
-are treated as SYSTEM includes by default. If this property is
-enabled, the contents of the INTERFACE_INCLUDE_DIRECTORIES of IMPORTED
-targets are not treated as system includes. This property is
-initialized by the value of the variable CMAKE_NO_SYSTEM_FROM_IMPORTED
-if it is set when a target is created.
+The contents of the :prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` target property
+of imported targets are treated as ``SYSTEM`` includes by default. If this
+property is enabled on a target, compilation of sources in that target will
+not treat the contents of the ``INTERFACE_INCLUDE_DIRECTORIES`` of consumed
+imported targets as system includes.
+
+This property is initialized by the value of the
+:variable:`CMAKE_NO_SYSTEM_FROM_IMPORTED` variable if it is set when a target
+is created.
diff --git a/Help/prop_tgt/VS_DOTNET_REFERENCEPROP_refname_TAG_tagname.rst b/Help/prop_tgt/VS_DOTNET_REFERENCEPROP_refname_TAG_tagname.rst
new file mode 100644
index 000000000..ab311eaf6
--- /dev/null
+++ b/Help/prop_tgt/VS_DOTNET_REFERENCEPROP_refname_TAG_tagname.rst
@@ -0,0 +1,14 @@
+VS_DOTNET_REFERENCEPROP_<refname>_TAG_<tagname>
+-----------------------------------------------
+
+Defines an XML property ``<tagname>`` for a .NET reference
+``<refname>``.
+
+Reference properties can be set for .NET references which are
+defined by the target properties :prop_tgt:`VS_DOTNET_REFERENCES`,
+:prop_tgt:`VS_DOTNET_REFERENCE_<refname>`
+and also for project references to other C# targets which are
+established by :command:`target_link_libraries()`.
+
+This property is only applicable to C# targets and Visual Studio
+generators 2010 and later.
diff --git a/Help/release/3.10.rst b/Help/release/3.10.rst
new file mode 100644
index 000000000..35fe602ed
--- /dev/null
+++ b/Help/release/3.10.rst
@@ -0,0 +1,257 @@
+CMake 3.10 Release Notes
+************************
+
+.. only:: html
+
+ .. contents::
+
+Changes made since CMake 3.9 include the following.
+
+New Features
+============
+
+Platforms
+---------
+
+* The `flang`_ Fortran compiler is now supported, with compiler id ``Flang``.
+
+* A new minimal platform file for ``Midipix`` was added.
+
+* Support for the MSVC ARM64 architecture was added.
+ Visual Studio 2017 Update 4 and above offer an ARM64 toolchain.
+
+* Support for the IAR ARM Compiler was improved.
+
+.. _`flang`: https://github.com/flang-compiler/flang
+
+Generators
+----------
+
+* The :ref:`Makefile Generators` and the :generator:`Ninja` generator learned
+ to add compiler launcher tools like ccache along with the compiler for the
+ ``CUDA`` language (``C`` and ``CXX`` were supported previously). See the
+ :variable:`CMAKE_<LANG>_COMPILER_LAUNCHER` variable and
+ :prop_tgt:`<LANG>_COMPILER_LAUNCHER` target property for details.
+
+* The :generator:`CodeBlocks` extra generator learned to optionally exclude
+ files from outside the project root directory from the generated project.
+ See the :variable:`CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES` variable.
+
+Commands
+--------
+
+* The :command:`cmake_host_system_information` command learned more keys
+ to get information about the processor capabilities and the host OS
+ version.
+
+* The :command:`configure_file` command learned to support indented
+ ``# cmakedefine`` and ``# cmakedefine01``. Spaces and/or tabs between
+ the ``#`` character and the ``cmakedefine``/``cmakedefine01`` words
+ are now understood and preserved in the output.
+
+* The :command:`execute_process` command gained a ``RESULTS_VARIABLE``
+ option to collect a list of results from all children in a pipeline
+ of processes when multiple ``COMMAND`` arguments are given.
+
+* The :command:`include_guard` command was introduced to allow guarding
+ CMake scripts from being included more than once. The command supports
+ ``DIRECTORY`` and ``GLOBAL`` options to adjust the corresponding include guard
+ scope. If no options given, include guard is similar to basic variable-based
+ check.
+
+* The :command:`string` command learned a new ``PREPEND`` subcommand.
+
+* The :command:`string(TIMESTAMP)` command now supports ``%A``
+ for full weekday name and ``%B`` for full month name.
+
+Variables
+---------
+
+* A :variable:`CMAKE_DIRECTORY_LABELS` variable was added to specify
+ labels for all tests in a directory.
+
+Properties
+----------
+
+* A :prop_tgt:`<LANG>_CPPCHECK` target property and supporting
+ :variable:`CMAKE_<LANG>_CPPCHECK` variable were introduced to tell
+ the :ref:`Makefile Generators` and the :generator:`Ninja` generator to
+ run ``cppcheck`` with the compiler for ``C`` and ``CXX`` languages.
+
+* A :prop_dir:`LABELS` directory property was added to specify labels
+ for all targets and tests in a directory.
+
+* A :prop_dir:`TEST_INCLUDE_FILES` directory property was added to
+ list any number of files to be included when running tests with
+ :manual:`ctest(1)`. This generalizes the :prop_dir:`TEST_INCLUDE_FILE`
+ property.
+
+* The :prop_tgt:`VS_DOTNET_REFERENCEPROP_<refname>_TAG_<tagname>`
+ target property was added to support custom XML tags for reference
+ assemblies in C# targets.
+
+* Source file properties :prop_sf:`VS_SHADER_OUTPUT_HEADER_FILE` and
+ :prop_sf:`VS_SHADER_VARIABLE_NAME` have been added to specify more
+ details of ``.hlsl`` sources with :ref:`Visual Studio Generators`.
+
+Modules
+-------
+
+* The :module:`FindCurses` module gained a ``CURSES_NEED_WIDE`` option
+ to request the wide-character variant.
+
+* The :module:`FindEXPAT` module now provides imported targets.
+
+* The :module:`FindFreetype` module now provides imported targets.
+
+* :module:`FindMPI` gained a number of new features, including:
+
+ * Language-specific components have been added to the module.
+ * Many more MPI environments are now supported.
+ * The environmental support for Fortran has been improved.
+ * A user now has fine-grained control over the MPI selection process,
+ including passing custom parameters to the MPI compiler.
+ * The version of the implemented MPI standard is now being exposed.
+ * MPI-2 C++ bindings can now be detected and also suppressed if so desired.
+ * The available Fortran bindings are now being detected and verified.
+ * Various MPI-3 information can be requested, including the library version
+ and Fortran capabilities of the individual bindings.
+ * Statically linked MPI implementations are supported.
+
+* A :module:`FindOpenACC` module was added to detect compiler support
+ for OpenACC. Currently only supports PGI, GNU and Cray compilers.
+
+* The :module:`FindOpenGL` module gained support for GLVND on Linux.
+
+* The :module:`FindOpenMP` module gained support for
+ language-specific components.
+
+* A :module:`FindPatch` module was added to find the ``patch``
+ command-line executable.
+
+* The :module:`FindProtobuf` module :command:`protobuf_generate_cpp` command
+ gained a ``DESCRIPTORS`` option to generate descriptor files.
+
+* The :module:`GoogleTest` module gained a new command
+ :command:`gtest_discover_tests` implementing dynamic (build-time) test
+ discovery. Unlike the source parsing approach, dynamic discovery executes
+ the test (in 'list available tests' mode) at build time to discover tests.
+ This is robust against unusual ways of labeling tests, provides much better
+ support for advanced features such as parameterized tests, and does not
+ require re-running CMake to discover added or removed tests within a test
+ executable.
+
+* The :module:`InstallRequiredSystemLibraries` module gained support
+ for installing Intel compiler runtimes.
+
+Autogen
+-------
+
+* When using :prop_tgt:`AUTOMOC` or :prop_tgt:`AUTOUIC` with a
+ multi configuration generator (e.g. :generator:`Xcode`),
+ included ``*.moc``, ``moc_*.cpp`` and ``ui_*.h`` files are generated in
+ ``<AUTOGEN_BUILD_DIR>/include_<CONFIG>`` instead of
+ ``<AUTOGEN_BUILD_DIR>/include``.
+
+* When using :prop_tgt:`AUTOMOC` or :prop_tgt:`AUTOUIC`,
+ source files that are :prop_sf:`GENERATED` will be processed as well.
+ They were ignored by :prop_tgt:`AUTOMOC` and :prop_tgt:`AUTOUIC`
+ in earlier releases.
+ See policy :policy:`CMP0071`.
+
+* When using :prop_tgt:`AUTOMOC`, CMake searches for the strings ``Q_OBJECT``,
+ ``Q_GADGET`` or ``Q_NAMESPACE`` in a source file to determine if it needs
+ to be ``moc`` processed. The new :variable:`CMAKE_AUTOMOC_MACRO_NAMES`
+ variable and :prop_tgt:`AUTOMOC_MACRO_NAMES` target property may be set
+ to register additional strings (macro names) to search for.
+
+* When using :prop_tgt:`AUTOMOC`, the new
+ :variable:`CMAKE_AUTOMOC_COMPILER_PREDEFINES` variable and
+ :prop_tgt:`AUTOMOC_COMPILER_PREDEFINES` target property specify whether
+ to enable or disable the generation of the compiler pre definitions file
+ ``moc_predefs.h``.
+
+CTest
+-----
+
+* A :variable:`CTEST_LABELS_FOR_SUBPROJECTS` CTest module variable and CTest
+ script variable were added to specify a list of labels that should be
+ treated as subprojects by CDash. To use this value in both the CTest module
+ and the ctest command line :ref:`Dashboard Client` mode (e.g. ``ctest -S``)
+ set it in the ``CTestConfig.cmake`` config file.
+
+CPack
+-----
+
+* CPack gained a ``FREEBSD`` generator for FreeBSD ``pkg(8)``, configured
+ by the :module:`CPackFreeBSD` module.
+
+* The CPack ``DEB`` generator, configured by the :module:`CPackDeb` module,
+ was enabled on Windows. While not fully featured (due to the lack of
+ external UNIX tools) this will allow building basic cross-platform Debian
+ packages.
+
+* The :module:`CPackDeb` module learned to set package release version in
+ ``Version`` info property.
+ See the :variable:`CPACK_DEBIAN_PACKAGE_RELEASE` variable.
+
+* The :module:`CPackDeb` module learned more strict package version checking
+ that complies with Debian rules.
+
+* The :module:`CPackIFW` module :command:`cpack_ifw_configure_component` and
+ :command:`cpack_ifw_configure_component_group` commands gained a new
+ ``REPLACES`` and ``CHECKABLE`` options.
+
+* The :module:`CPackIFW` module gained new
+ :variable:`CPACK_IFW_PACKAGE_FILE_EXTENSION` variable to customize
+ target binary format.
+
+* The :module:`CPackIFW` module gained new
+ :variable:`CPACK_IFW_REPOSITORIES_DIRECTORIES` variable to specify
+ additional repositories dirs that will be used to resolve and
+ repack dependent components. This feature is only available when
+ using QtIFW 3.1 or later.
+
+* Modules :module:`CPackRPM` and :module:`CPackDeb` learned to set package epoch
+ version.
+ See :variable:`CPACK_RPM_PACKAGE_EPOCH` and
+ :variable:`CPACK_DEBIAN_PACKAGE_EPOCH` variables.
+
+Other
+-----
+
+* The :manual:`cmake(1)` ``-E`` mode gained support for ``sha1sum``,
+ ``sha224sum``, ``sha256sum``, ``sha384sum``, and ``sha512sum``.
+
+* The graphviz output now distinguishes among the different dependency types
+ ``PUBLIC``, ``PRIVATE`` and ``INTERFACE`` and represents them in the output
+ graph as solid, dashed and dotted edges.
+
+Deprecated and Removed Features
+===============================
+
+* Support for building CMake itself with C++98 compilers was dropped.
+ CMake is now implemented using C++11.
+
+* Support for building CMake on HP-UX has been dropped pending better
+ support for C++11 and a port of libuv. See `CMake Issue 17137`_.
+ Use CMake 3.9 or lower instead for HP-UX support.
+
+.. _`CMake Issue 17137`: https://gitlab.kitware.com/cmake/cmake/issues/17137
+
+Other Changes
+=============
+
+* On FreeBSD the C++ compiler named ``c++`` is now the preferred default.
+
+* The :command:`file(GENERATE)` command now interprets relative paths
+ given to its ``OUTPUT`` and ``INPUT`` arguments with respect to the
+ caller's current binary and source directories, respectively.
+ See policy :policy:`CMP0070`.
+
+* The :command:`get_filename_component` ``PROGRAM`` mode semantics
+ have been revised to not tolerate unquoted spaces in the path
+ to the program while also accepting arguments. While technically
+ incompatible with the old behavior, it is expected that behavior
+ under typical use cases with properly-quoted command-lines has
+ not changed.
diff --git a/Help/release/index.rst b/Help/release/index.rst
index 6af282cff..0c7572f8c 100644
--- a/Help/release/index.rst
+++ b/Help/release/index.rst
@@ -13,6 +13,7 @@ Releases
.. toctree::
:maxdepth: 1
+ 3.10 <3.10>
3.9 <3.9>
3.8 <3.8>
3.7 <3.7>
diff --git a/Help/variable/APPLE.rst b/Help/variable/APPLE.rst
index 75eecf183..810d5fc3a 100644
--- a/Help/variable/APPLE.rst
+++ b/Help/variable/APPLE.rst
@@ -1,6 +1,5 @@
APPLE
-----
-``True`` if running on OS X.
-
-Set to ``true`` on OS X.
+Set to ``True`` when the target system is an Apple platform
+(macOS, iOS, tvOS or watchOS).
diff --git a/Help/variable/CMAKE_AUTOMOC_COMPILER_PREDEFINES.rst b/Help/variable/CMAKE_AUTOMOC_COMPILER_PREDEFINES.rst
new file mode 100644
index 000000000..7e1c53d06
--- /dev/null
+++ b/Help/variable/CMAKE_AUTOMOC_COMPILER_PREDEFINES.rst
@@ -0,0 +1,8 @@
+CMAKE_AUTOMOC_COMPILER_PREDEFINES
+---------------------------------
+
+This variable is used to initialize the :prop_tgt:`AUTOMOC_COMPILER_PREDEFINES`
+property on all the targets. See that target property for additional
+information.
+
+By default it is ON.
diff --git a/Help/variable/CMAKE_AUTOMOC_MACRO_NAMES.rst b/Help/variable/CMAKE_AUTOMOC_MACRO_NAMES.rst
new file mode 100644
index 000000000..5b79c4020
--- /dev/null
+++ b/Help/variable/CMAKE_AUTOMOC_MACRO_NAMES.rst
@@ -0,0 +1,20 @@
+CMAKE_AUTOMOC_MACRO_NAMES
+----------------------------
+
+A :ref:`;-list <CMake Language Lists>` list of macro names used by
+:variable:`CMAKE_AUTOMOC` to determine if a C++ file needs to be
+processed by ``moc``.
+
+This variable is used to initialize the :prop_tgt:`AUTOMOC_MACRO_NAMES`
+property on all the targets. See that target property for additional
+information.
+
+The default value is ``Q_OBJECT;Q_GADGET;Q_NAMESPACE``.
+
+Example
+-------
+Let CMake know that source files that contain ``CUSTOM_MACRO`` must be ``moc``
+processed as well::
+
+ set(CMAKE_AUTOMOC ON)
+ list(APPEND CMAKE_AUTOMOC_MACRO_NAMES "CUSTOM_MACRO")
diff --git a/Help/variable/CMAKE_AUTORCC_OPTIONS.rst b/Help/variable/CMAKE_AUTORCC_OPTIONS.rst
index 298cb6be7..815d39d41 100644
--- a/Help/variable/CMAKE_AUTORCC_OPTIONS.rst
+++ b/Help/variable/CMAKE_AUTORCC_OPTIONS.rst
@@ -1,7 +1,16 @@
CMAKE_AUTORCC_OPTIONS
---------------------
-Whether to handle ``rcc`` automatically for Qt targets.
+Additional options for ``rcc`` when using :variable:`CMAKE_AUTORCC`.
This variable is used to initialize the :prop_tgt:`AUTORCC_OPTIONS` property on
all the targets. See that target property for additional information.
+
+EXAMPLE
+^^^^^^^
+
+.. code-block:: cmake
+
+ # ...
+ set(CMAKE_AUTORCC_OPTIONS "--compress;9")
+ # ...
diff --git a/Help/variable/CMAKE_AUTOUIC_OPTIONS.rst b/Help/variable/CMAKE_AUTOUIC_OPTIONS.rst
index 3c9b8c4f5..28fa92f16 100644
--- a/Help/variable/CMAKE_AUTOUIC_OPTIONS.rst
+++ b/Help/variable/CMAKE_AUTOUIC_OPTIONS.rst
@@ -1,7 +1,16 @@
CMAKE_AUTOUIC_OPTIONS
---------------------
-Whether to handle ``uic`` automatically for Qt targets.
+Additional options for ``uic`` when using :variable:`CMAKE_AUTOUIC`.
This variable is used to initialize the :prop_tgt:`AUTOUIC_OPTIONS` property on
all the targets. See that target property for additional information.
+
+EXAMPLE
+^^^^^^^
+
+.. code-block:: cmake
+
+ # ...
+ set_property(CMAKE_AUTOUIC_OPTIONS "--no-protection")
+ # ...
diff --git a/Help/variable/CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES.rst b/Help/variable/CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES.rst
new file mode 100644
index 000000000..80ffce3a7
--- /dev/null
+++ b/Help/variable/CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES.rst
@@ -0,0 +1,7 @@
+CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES
+---------------------------------------
+
+Change the way the CodeBlocks generator creates project files.
+
+If this variable evaluates to ``ON`` the generator excludes from
+the project file any files that are located outside the project root.
diff --git a/Help/variable/CMAKE_CUDA_HOST_COMPILER.rst b/Help/variable/CMAKE_CUDA_HOST_COMPILER.rst
new file mode 100644
index 000000000..72e8e66ac
--- /dev/null
+++ b/Help/variable/CMAKE_CUDA_HOST_COMPILER.rst
@@ -0,0 +1,7 @@
+CMAKE_CUDA_HOST_COMPILER
+------------------------
+
+Executable to use when compiling host code when compiling ``CUDA`` language
+files. Maps to the nvcc -ccbin option. Will only be used by CMake on the first
+configuration to determine a valid host compiler for ``CUDA``. After a valid
+host compiler has been found, this value is read-only.
diff --git a/Help/variable/CMAKE_DIRECTORY_LABELS.rst b/Help/variable/CMAKE_DIRECTORY_LABELS.rst
new file mode 100644
index 000000000..2a6c41000
--- /dev/null
+++ b/Help/variable/CMAKE_DIRECTORY_LABELS.rst
@@ -0,0 +1,6 @@
+CMAKE_DIRECTORY_LABELS
+-----------------------
+
+Specify labels for the current directory.
+
+This is used to initialize the :prop_dir:`LABELS` directory property.
diff --git a/Help/variable/CMAKE_FIND_NO_INSTALL_PREFIX.rst b/Help/variable/CMAKE_FIND_NO_INSTALL_PREFIX.rst
index c49d2641b..789dc99aa 100644
--- a/Help/variable/CMAKE_FIND_NO_INSTALL_PREFIX.rst
+++ b/Help/variable/CMAKE_FIND_NO_INSTALL_PREFIX.rst
@@ -1,15 +1,19 @@
CMAKE_FIND_NO_INSTALL_PREFIX
----------------------------
-Ignore the :variable:`CMAKE_INSTALL_PREFIX` when searching for assets.
+Exclude the values of the :variable:`CMAKE_INSTALL_PREFIX` and
+:variable:`CMAKE_STAGING_PREFIX` variables from
+:variable:`CMAKE_SYSTEM_PREFIX_PATH`. CMake adds these project-destination
+prefixes to :variable:`CMAKE_SYSTEM_PREFIX_PATH` by default in order to
+support building a series of dependent packages and installing them into
+a common prefix. Set ``CMAKE_FIND_NO_INSTALL_PREFIX`` to ``TRUE``
+to suppress this behavior.
-CMake adds the :variable:`CMAKE_INSTALL_PREFIX` and the
-:variable:`CMAKE_STAGING_PREFIX` variable to the
-:variable:`CMAKE_SYSTEM_PREFIX_PATH` by default. This variable may be set
-on the command line to control that behavior.
+The :variable:`CMAKE_SYSTEM_PREFIX_PATH` is initialized on the first call to a
+:command:`project` or :command:`enable_language` command. Therefore one must
+set ``CMAKE_FIND_NO_INSTALL_PREFIX`` before this in order to take effect. A
+user may set the variable as a cache entry on the command line to achieve this.
-Set ``CMAKE_FIND_NO_INSTALL_PREFIX`` to ``TRUE`` to tell
-:command:`find_package` not to search in the :variable:`CMAKE_INSTALL_PREFIX`
-or :variable:`CMAKE_STAGING_PREFIX` by default. Note that the
-prefix may still be searched for other reasons, such as being the same prefix
-as the CMake installation, or for being a built-in system prefix.
+Note that the prefix(es) may still be searched for other reasons, such as being
+the same prefix as the CMake installation, or for being a built-in system
+prefix.
diff --git a/Help/variable/CMAKE_LANG_COMPILER_ARCHITECTURE_ID.rst b/Help/variable/CMAKE_LANG_COMPILER_ARCHITECTURE_ID.rst
new file mode 100644
index 000000000..054c64884
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_COMPILER_ARCHITECTURE_ID.rst
@@ -0,0 +1,8 @@
+CMAKE_<LANG>_COMPILER_ARCHITECTURE_ID
+-------------------------------------
+
+An internal variable subject to change.
+
+This is used to identify the variant of a compiler based on its target
+architecture. For some compilers this is needed to determine the correct
+usage.
diff --git a/Help/variable/CMAKE_LANG_COMPILER_ID.rst b/Help/variable/CMAKE_LANG_COMPILER_ID.rst
index 0fab10ca8..226426970 100644
--- a/Help/variable/CMAKE_LANG_COMPILER_ID.rst
+++ b/Help/variable/CMAKE_LANG_COMPILER_ID.rst
@@ -20,12 +20,14 @@ include:
G95 = G95 Fortran (g95.org)
GNU = GNU Compiler Collection (gcc.gnu.org)
HP = Hewlett-Packard Compiler (hp.com)
+ IAR = IAR Systems (iar.com)
Intel = Intel Compiler (intel.com)
MIPSpro = SGI MIPSpro (sgi.com)
MSVC = Microsoft Visual Studio (microsoft.com)
NVIDIA = NVIDIA CUDA Compiler (nvidia.com)
OpenWatcom = Open Watcom (openwatcom.org)
PGI = The Portland Group (pgroup.com)
+ Flang = Flang Fortran Compiler
PathScale = PathScale (pathscale.com)
SDCC = Small Device C Compiler (sdcc.sourceforge.net)
SunPro = Oracle Solaris Studio (oracle.com)
diff --git a/Help/variable/CMAKE_LANG_COMPILER_LAUNCHER.rst b/Help/variable/CMAKE_LANG_COMPILER_LAUNCHER.rst
index 7961f609e..f4e2ba5fd 100644
--- a/Help/variable/CMAKE_LANG_COMPILER_LAUNCHER.rst
+++ b/Help/variable/CMAKE_LANG_COMPILER_LAUNCHER.rst
@@ -3,4 +3,4 @@ CMAKE_<LANG>_COMPILER_LAUNCHER
Default value for :prop_tgt:`<LANG>_COMPILER_LAUNCHER` target property.
This variable is used to initialize the property on each target as it is
-created. This is done only when ``<LANG>`` is ``C`` or ``CXX``.
+created. This is done only when ``<LANG>`` is ``C``, ``CXX``, or ``CUDA``.
diff --git a/Help/variable/CMAKE_LANG_COMPILER_PREDEFINES_COMMAND.rst b/Help/variable/CMAKE_LANG_COMPILER_PREDEFINES_COMMAND.rst
new file mode 100644
index 000000000..e050f43e6
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_COMPILER_PREDEFINES_COMMAND.rst
@@ -0,0 +1,8 @@
+CMAKE_<LANG>_COMPILER_PREDEFINES_COMMAND
+----------------------------------------
+
+Command that outputs the compiler pre definitions.
+
+See :prop_tgt:`AUTOMOC` which uses
+:variable:`CMAKE_CXX_COMPILER_PREDEFINES_COMMAND <CMAKE_<LANG>_COMPILER_PREDEFINES_COMMAND>`
+to generate the :prop_tgt:`AUTOMOC_COMPILER_PREDEFINES`.
diff --git a/Help/variable/CMAKE_LANG_COMPILER_VERSION_INTERNAL.rst b/Help/variable/CMAKE_LANG_COMPILER_VERSION_INTERNAL.rst
new file mode 100644
index 000000000..c3cd9801a
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_COMPILER_VERSION_INTERNAL.rst
@@ -0,0 +1,8 @@
+CMAKE_<LANG>_COMPILER_VERSION_INTERNAL
+--------------------------------------
+
+An internal variable subject to change.
+
+This is used to identify the variant of a compiler based on an internal
+version number. For some compilers this is needed to determine the
+correct usage.
diff --git a/Help/variable/CMAKE_LANG_CPPCHECK.rst b/Help/variable/CMAKE_LANG_CPPCHECK.rst
new file mode 100644
index 000000000..50b478fd0
--- /dev/null
+++ b/Help/variable/CMAKE_LANG_CPPCHECK.rst
@@ -0,0 +1,6 @@
+CMAKE_<LANG>_CPPCHECK
+---------------------
+
+Default value for :prop_tgt:`<LANG>_CPPCHECK` target property. This variable
+is used to initialize the property on each target as it is created. This
+is done only when ``<LANG>`` is ``C`` or ``CXX``.
diff --git a/Help/variable/CMAKE_MSVCIDE_RUN_PATH.rst b/Help/variable/CMAKE_MSVCIDE_RUN_PATH.rst
new file mode 100644
index 000000000..22e727f37
--- /dev/null
+++ b/Help/variable/CMAKE_MSVCIDE_RUN_PATH.rst
@@ -0,0 +1,10 @@
+CMAKE_MSVCIDE_RUN_PATH
+----------------------
+
+Extra PATH locations that should be used when executing
+:command:`add_custom_command` or :command:`add_custom_target` when using the
+:generator:`Visual Studio 9 2008` (or above) generator. This allows
+for running commands and using dll's that the IDE environment is not aware of.
+
+If not set explicitly the value is initialized by the ``CMAKE_MSVCIDE_RUN_PATH``
+environment variable, if set, and otherwise left empty.
diff --git a/Help/variable/CMAKE_SYSTEM_PREFIX_PATH.rst b/Help/variable/CMAKE_SYSTEM_PREFIX_PATH.rst
index e74dfad18..38b2f8dca 100644
--- a/Help/variable/CMAKE_SYSTEM_PREFIX_PATH.rst
+++ b/Help/variable/CMAKE_SYSTEM_PREFIX_PATH.rst
@@ -10,8 +10,11 @@ documentation.
By default this contains the standard directories for the current system, the
:variable:`CMAKE_INSTALL_PREFIX`, and the :variable:`CMAKE_STAGING_PREFIX`.
-It is *not* intended to be modified by the project; use
-:variable:`CMAKE_PREFIX_PATH` for this.
+The installation and staging prefixes may be excluded by setting
+the :variable:`CMAKE_FIND_NO_INSTALL_PREFIX` variable.
+
+``CMAKE_SYSTEM_PREFIX_PATH`` is *not* intended to be modified by the project;
+use :variable:`CMAKE_PREFIX_PATH` for this.
See also :variable:`CMAKE_SYSTEM_INCLUDE_PATH`,
:variable:`CMAKE_SYSTEM_LIBRARY_PATH`, :variable:`CMAKE_SYSTEM_PROGRAM_PATH`,
diff --git a/Help/variable/CTEST_LABELS_FOR_SUBPROJECTS.rst b/Help/variable/CTEST_LABELS_FOR_SUBPROJECTS.rst
new file mode 100644
index 000000000..959596bf3
--- /dev/null
+++ b/Help/variable/CTEST_LABELS_FOR_SUBPROJECTS.rst
@@ -0,0 +1,5 @@
+CTEST_LABELS_FOR_SUBPROJECTS
+----------------------------
+
+Specify the CTest ``LabelsForSubprojects`` setting
+in a :manual:`ctest(1)` dashboard client script.
diff --git a/Help/variable/MSVC_VERSION.rst b/Help/variable/MSVC_VERSION.rst
index 8932147c6..0a3a7a694 100644
--- a/Help/variable/MSVC_VERSION.rst
+++ b/Help/variable/MSVC_VERSION.rst
@@ -5,13 +5,15 @@ The version of Microsoft Visual C/C++ being used if any.
Known version numbers are::
- 1200 = VS 6.0
- 1300 = VS 7.0
- 1310 = VS 7.1
- 1400 = VS 8.0
- 1500 = VS 9.0
- 1600 = VS 10.0
- 1700 = VS 11.0
- 1800 = VS 12.0
- 1900 = VS 14.0
- 1910 = VS 15.0
+ 1200 = VS 6.0
+ 1300 = VS 7.0
+ 1310 = VS 7.1
+ 1400 = VS 8.0 (v80 toolset)
+ 1500 = VS 9.0 (v90 toolset)
+ 1600 = VS 10.0 (v100 toolset)
+ 1700 = VS 11.0 (v110 toolset)
+ 1800 = VS 12.0 (v120 toolset)
+ 1900 = VS 14.0 (v140 toolset)
+ 1910-1919 = VS 15.0 (v141 toolset)
+
+See also the :variable:`CMAKE_<LANG>_COMPILER_VERSION` variable.
diff --git a/Help/variable/UNIX.rst b/Help/variable/UNIX.rst
index 0877b7c07..49d866838 100644
--- a/Help/variable/UNIX.rst
+++ b/Help/variable/UNIX.rst
@@ -1,7 +1,7 @@
UNIX
----
-``True`` for UNIX and UNIX like operating systems.
-
-Set to ``true`` when the target system is UNIX or UNIX like (i.e.
-:variable:`APPLE` and :variable:`CYGWIN`).
+Set to ``True`` when the target system is UNIX or UNIX-like
+(e.g. :variable:`APPLE` and :variable:`CYGWIN`). The
+:variable:`CMAKE_SYSTEM_NAME` variable should be queried if
+a more specific understanding of the target system is required.
diff --git a/Help/variable/WIN32.rst b/Help/variable/WIN32.rst
index 218906955..78ab77279 100644
--- a/Help/variable/WIN32.rst
+++ b/Help/variable/WIN32.rst
@@ -1,6 +1,4 @@
WIN32
-----
-``True`` on Windows systems, including Win64.
-
-Set to ``true`` when the target system is Windows.
+Set to ``True`` when the target system is Windows, including Win64.
diff --git a/Modules/AutogenInfo.cmake.in b/Modules/AutogenInfo.cmake.in
index 4e85474d3..7f4b398b6 100644
--- a/Modules/AutogenInfo.cmake.in
+++ b/Modules/AutogenInfo.cmake.in
@@ -1,23 +1,27 @@
+# Meta
+set(AM_MULTI_CONFIG @_multi_config@)
# Directories and files
set(AM_CMAKE_BINARY_DIR "@CMAKE_BINARY_DIR@/")
set(AM_CMAKE_SOURCE_DIR "@CMAKE_SOURCE_DIR@/")
set(AM_CMAKE_CURRENT_SOURCE_DIR "@CMAKE_CURRENT_SOURCE_DIR@/")
set(AM_CMAKE_CURRENT_BINARY_DIR "@CMAKE_CURRENT_BINARY_DIR@/")
set(AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE "@CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE@")
-set(AM_BUILD_DIR @_autogen_build_dir@)
+set(AM_BUILD_DIR @_build_dir@)
set(AM_SOURCES @_sources@)
set(AM_HEADERS @_headers@)
# Qt environment
set(AM_QT_VERSION_MAJOR @_qt_version_major@)
+set(AM_QT_VERSION_MINOR @_qt_version_minor@)
set(AM_QT_MOC_EXECUTABLE @_qt_moc_executable@)
set(AM_QT_UIC_EXECUTABLE @_qt_uic_executable@)
set(AM_QT_RCC_EXECUTABLE @_qt_rcc_executable@)
# MOC settings
set(AM_MOC_SKIP @_moc_skip@)
set(AM_MOC_DEFINITIONS @_moc_compile_defs@)
-set(AM_MOC_INCLUDES @_moc_incs@)
+set(AM_MOC_INCLUDES @_moc_include_dirs@)
set(AM_MOC_OPTIONS @_moc_options@)
set(AM_MOC_RELAXED_MODE @_moc_relaxed_mode@)
+set(AM_MOC_MACRO_NAMES @_moc_macro_names@)
set(AM_MOC_DEPEND_FILTERS @_moc_depend_filters@)
set(AM_MOC_PREDEFS_CMD @_moc_predefs_cmd@)
# UIC settings
@@ -27,7 +31,7 @@ set(AM_UIC_OPTIONS_FILES @_qt_uic_options_files@)
set(AM_UIC_OPTIONS_OPTIONS @_qt_uic_options_options@)
set(AM_UIC_SEARCH_PATHS @_uic_search_paths@)
# RCC settings
-set(AM_RCC_SOURCES @_rcc_files@ )
+set(AM_RCC_SOURCES @_rcc_files@)
+set(AM_RCC_BUILDS @_rcc_builds@)
+set(AM_RCC_OPTIONS @_rcc_options@)
set(AM_RCC_INPUTS @_rcc_inputs@)
-set(AM_RCC_OPTIONS_FILES @_rcc_options_files@)
-set(AM_RCC_OPTIONS_OPTIONS @_rcc_options_options@)
diff --git a/Modules/CMakeASMCompiler.cmake.in b/Modules/CMakeASMCompiler.cmake.in
index 7b94d0f6e..a6465f695 100644
--- a/Modules/CMakeASMCompiler.cmake.in
+++ b/Modules/CMakeASMCompiler.cmake.in
@@ -7,8 +7,11 @@ set(CMAKE_ASM@ASM_DIALECT@_COMPILER_RANLIB "@_CMAKE_ASM_COMPILER_RANLIB@")
set(CMAKE_LINKER "@CMAKE_LINKER@")
set(CMAKE_ASM@ASM_DIALECT@_COMPILER_LOADED 1)
set(CMAKE_ASM@ASM_DIALECT@_COMPILER_ID "@_CMAKE_ASM_COMPILER_ID@")
+set(CMAKE_ASM@ASM_DIALECT@_COMPILER_VERSION "@_CMAKE_ASM_COMPILER_VERSION@")
set(CMAKE_ASM@ASM_DIALECT@_COMPILER_ENV_VAR "@_CMAKE_ASM_COMPILER_ENV_VAR@")
+@_SET_CMAKE_ASM_COMPILER_ARCHITECTURE_ID@
set(CMAKE_ASM@ASM_DIALECT@_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC)
set(CMAKE_ASM@ASM_DIALECT@_LINKER_PREFERENCE 0)
+@CMAKE_ASM_COMPILER_CUSTOM_CODE@
diff --git a/Modules/CMakeCCompiler.cmake.in b/Modules/CMakeCCompiler.cmake.in
index 974a57927..8ad0c01d2 100644
--- a/Modules/CMakeCCompiler.cmake.in
+++ b/Modules/CMakeCCompiler.cmake.in
@@ -2,6 +2,7 @@ set(CMAKE_C_COMPILER "@CMAKE_C_COMPILER@")
set(CMAKE_C_COMPILER_ARG1 "@CMAKE_C_COMPILER_ARG1@")
set(CMAKE_C_COMPILER_ID "@CMAKE_C_COMPILER_ID@")
set(CMAKE_C_COMPILER_VERSION "@CMAKE_C_COMPILER_VERSION@")
+set(CMAKE_C_COMPILER_VERSION_INTERNAL "@CMAKE_C_COMPILER_VERSION_INTERNAL@")
set(CMAKE_C_COMPILER_WRAPPER "@CMAKE_C_COMPILER_WRAPPER@")
set(CMAKE_C_STANDARD_COMPUTED_DEFAULT "@CMAKE_C_STANDARD_COMPUTED_DEFAULT@")
set(CMAKE_C_COMPILE_FEATURES "@CMAKE_C_COMPILE_FEATURES@")
@@ -12,6 +13,7 @@ set(CMAKE_C11_COMPILE_FEATURES "@CMAKE_C11_COMPILE_FEATURES@")
set(CMAKE_C_PLATFORM_ID "@CMAKE_C_PLATFORM_ID@")
set(CMAKE_C_SIMULATE_ID "@CMAKE_C_SIMULATE_ID@")
set(CMAKE_C_SIMULATE_VERSION "@CMAKE_C_SIMULATE_VERSION@")
+@_SET_CMAKE_C_COMPILER_ARCHITECTURE_ID@
@SET_MSVC_C_ARCHITECTURE_ID@
@SET_CMAKE_XCODE_CURRENT_ARCH@
set(CMAKE_AR "@CMAKE_AR@")
diff --git a/Modules/CMakeCCompilerId.c.in b/Modules/CMakeCCompilerId.c.in
index 95184c982..10f7318a6 100644
--- a/Modules/CMakeCCompilerId.c.in
+++ b/Modules/CMakeCCompilerId.c.in
@@ -67,6 +67,9 @@ int main(int argc, char* argv[])
#ifdef COMPILER_VERSION_MAJOR
require += info_version[argc];
#endif
+#ifdef COMPILER_VERSION_INTERNAL
+ require += info_version_internal[argc];
+#endif
#ifdef SIMULATE_ID
require += info_simulate[argc];
#endif
diff --git a/Modules/CMakeCSharpInformation.cmake b/Modules/CMakeCSharpInformation.cmake
index f71dcefe9..25f869c9b 100644
--- a/Modules/CMakeCSharpInformation.cmake
+++ b/Modules/CMakeCSharpInformation.cmake
@@ -10,7 +10,7 @@ get_filename_component(CMAKE_BASE_NAME "${CMAKE_CSharp_COMPILER}" NAME_WE)
set(CMAKE_BUILD_TYPE_INIT Debug)
-set(CMAKE_CSharp_FLAGS_INIT "/define:TRACE /langversion:3 /nowin32manifest")
+set(CMAKE_CSharp_FLAGS_INIT "/define:TRACE /langversion:3")
set(CMAKE_CSharp_FLAGS_DEBUG_INIT "/debug:full /optimize- /warn:3 /errorreport:prompt /define:DEBUG")
set(CMAKE_CSharp_FLAGS_RELEASE_INIT "/debug:none /optimize /warn:1 /errorreport:queue")
set(CMAKE_CSharp_FLAGS_RELWITHDEBINFO_INIT "/debug:full /optimize-")
diff --git a/Modules/CMakeCXXCompiler.cmake.in b/Modules/CMakeCXXCompiler.cmake.in
index fda79508b..df57a4faa 100644
--- a/Modules/CMakeCXXCompiler.cmake.in
+++ b/Modules/CMakeCXXCompiler.cmake.in
@@ -2,6 +2,7 @@ set(CMAKE_CXX_COMPILER "@CMAKE_CXX_COMPILER@")
set(CMAKE_CXX_COMPILER_ARG1 "@CMAKE_CXX_COMPILER_ARG1@")
set(CMAKE_CXX_COMPILER_ID "@CMAKE_CXX_COMPILER_ID@")
set(CMAKE_CXX_COMPILER_VERSION "@CMAKE_CXX_COMPILER_VERSION@")
+set(CMAKE_CXX_COMPILER_VERSION_INTERNAL "@CMAKE_CXX_COMPILER_VERSION_INTERNAL@")
set(CMAKE_CXX_COMPILER_WRAPPER "@CMAKE_CXX_COMPILER_WRAPPER@")
set(CMAKE_CXX_STANDARD_COMPUTED_DEFAULT "@CMAKE_CXX_STANDARD_COMPUTED_DEFAULT@")
set(CMAKE_CXX_COMPILE_FEATURES "@CMAKE_CXX_COMPILE_FEATURES@")
@@ -13,6 +14,7 @@ set(CMAKE_CXX17_COMPILE_FEATURES "@CMAKE_CXX17_COMPILE_FEATURES@")
set(CMAKE_CXX_PLATFORM_ID "@CMAKE_CXX_PLATFORM_ID@")
set(CMAKE_CXX_SIMULATE_ID "@CMAKE_CXX_SIMULATE_ID@")
set(CMAKE_CXX_SIMULATE_VERSION "@CMAKE_CXX_SIMULATE_VERSION@")
+@_SET_CMAKE_CXX_COMPILER_ARCHITECTURE_ID@
@SET_MSVC_CXX_ARCHITECTURE_ID@
@SET_CMAKE_XCODE_CURRENT_ARCH@
set(CMAKE_AR "@CMAKE_AR@")
diff --git a/Modules/CMakeCXXCompilerId.cpp.in b/Modules/CMakeCXXCompilerId.cpp.in
index 9aa096dbb..4cb22676e 100644
--- a/Modules/CMakeCXXCompilerId.cpp.in
+++ b/Modules/CMakeCXXCompilerId.cpp.in
@@ -27,12 +27,18 @@ char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]";
@CMAKE_CXX_COMPILER_ID_PLATFORM_CONTENT@
@CMAKE_CXX_COMPILER_ID_ERROR_FOR_TEST@
+#if defined(_MSC_VER) && defined(_MSVC_LANG)
+#define CXX_STD _MSVC_LANG
+#else
+#define CXX_STD __cplusplus
+#endif
+
const char* info_language_dialect_default = "INFO" ":" "dialect_default["
-#if __cplusplus > 201402L
+#if CXX_STD > 201402L
"17"
-#elif __cplusplus >= 201402L
+#elif CXX_STD >= 201402L
"14"
-#elif __cplusplus >= 201103L
+#elif CXX_STD >= 201103L
"11"
#else
"98"
@@ -49,6 +55,9 @@ int main(int argc, char* argv[])
#ifdef COMPILER_VERSION_MAJOR
require += info_version[argc];
#endif
+#ifdef COMPILER_VERSION_INTERNAL
+ require += info_version_internal[argc];
+#endif
#ifdef SIMULATE_ID
require += info_simulate[argc];
#endif
diff --git a/Modules/CMakeDetermineASMCompiler.cmake b/Modules/CMakeDetermineASMCompiler.cmake
index 87c6b2872..f7cf54a8d 100644
--- a/Modules/CMakeDetermineASMCompiler.cmake
+++ b/Modules/CMakeDetermineASMCompiler.cmake
@@ -84,7 +84,7 @@ if(NOT CMAKE_ASM${ASM_DIALECT}_COMPILER_ID)
set(CMAKE_ASM${ASM_DIALECT}_COMPILER_ID_VENDOR_FLAGS_TI "-h")
set(CMAKE_ASM${ASM_DIALECT}_COMPILER_ID_VENDOR_REGEX_TI "Texas Instruments")
- list(APPEND CMAKE_ASM${ASM_DIALECT}_COMPILER_ID_VENDORS GNU IAR)
+ list(APPEND CMAKE_ASM${ASM_DIALECT}_COMPILER_ID_VENDORS IAR)
set(CMAKE_ASM${ASM_DIALECT}_COMPILER_ID_VENDOR_FLAGS_IAR )
set(CMAKE_ASM${ASM_DIALECT}_COMPILER_ID_VENDOR_REGEX_IAR "IAR Assembler")
@@ -103,10 +103,31 @@ if(NOT CMAKE_ASM${ASM_DIALECT}_COMPILER_ID)
include(CMakeDetermineCompilerId)
set(userflags)
CMAKE_DETERMINE_COMPILER_ID_VENDOR(ASM${ASM_DIALECT} "${userflags}")
+ 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
+ # Cut out identification first, newline handling is a pain
+ string(REGEX MATCH "IAR Assembler[^\r\n]*" _compileid "${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID_OUTPUT}")
+ if("${_compileid}" MATCHES "V([0-9]+\\.[0-9]+\\.[0-9]+)")
+ set(CMAKE_ASM${ASM_DIALECT}_COMPILER_VERSION ${CMAKE_MATCH_1})
+ endif()
+ if("${_compileid}" MATCHES "for[ ]+([A-Za-z0-9]+)")
+ set(CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID ${CMAKE_MATCH_1})
+ endif()
+ endif()
+ unset(CMAKE_ASM${ASM_DIALECT}_COMPILER_ID_OUTPUT)
+ unset(_compileid)
endif()
+
if(CMAKE_ASM${ASM_DIALECT}_COMPILER_ID)
- message(STATUS "The ASM${ASM_DIALECT} compiler identification is ${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}")
+ if(CMAKE_ASM${ASM_DIALECT}_COMPILER_VERSION)
+ set(_version " ${CMAKE_ASM${ASM_DIALECT}_COMPILER_VERSION}")
+ else()
+ set(_version "")
+ endif()
+ message(STATUS "The ASM${ASM_DIALECT} compiler identification is ${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}${_version}")
+ unset(_version)
else()
message(STATUS "The ASM${ASM_DIALECT} compiler identification is unknown")
endif()
@@ -143,6 +164,9 @@ endif ()
include(CMakeFindBinUtils)
+set(_CMAKE_PROCESSING_LANGUAGE "ASM")
+include(Compiler/${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}-FindBinUtils OPTIONAL)
+unset(_CMAKE_PROCESSING_LANGUAGE)
set(CMAKE_ASM${ASM_DIALECT}_COMPILER_ENV_VAR "ASM${ASM_DIALECT}")
@@ -152,20 +176,37 @@ else()
message(STATUS "Didn't find assembler")
endif()
-
-set(_CMAKE_ASM_COMPILER "${CMAKE_ASM${ASM_DIALECT}_COMPILER}")
-set(_CMAKE_ASM_COMPILER_ID "${CMAKE_ASM${ASM_DIALECT}_COMPILER_ID}")
-set(_CMAKE_ASM_COMPILER_ARG1 "${CMAKE_ASM${ASM_DIALECT}_COMPILER_ARG1}")
-set(_CMAKE_ASM_COMPILER_ENV_VAR "${CMAKE_ASM${ASM_DIALECT}_COMPILER_ENV_VAR}")
-set(_CMAKE_ASM_COMPILER_AR "${CMAKE_ASM${ASM_DIALECT}_COMPILER_AR}")
-set(_CMAKE_ASM_COMPILER_RANLIB "${CMAKE_ASM${ASM_DIALECT}_COMPILER_RANLIB}")
+foreach(_var
+ COMPILER
+ COMPILER_ID
+ COMPILER_ARG1
+ COMPILER_ENV_VAR
+ COMPILER_AR
+ COMPILER_RANLIB
+ COMPILER_VERSION
+ )
+ set(_CMAKE_ASM_${_var} "${CMAKE_ASM${ASM_DIALECT}_${_var}}")
+endforeach()
+
+if(CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID)
+ set(_SET_CMAKE_ASM_COMPILER_ARCHITECTURE_ID
+ "set(CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID ${CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID})")
+else()
+ set(_SET_CMAKE_ASM_COMPILER_ARCHITECTURE_ID "")
+endif()
# configure variables set in this file for fast reload later on
configure_file(${CMAKE_ROOT}/Modules/CMakeASMCompiler.cmake.in
${CMAKE_PLATFORM_INFO_DIR}/CMakeASM${ASM_DIALECT}Compiler.cmake @ONLY)
-set(_CMAKE_ASM_COMPILER)
-set(_CMAKE_ASM_COMPILER_ARG1)
-set(_CMAKE_ASM_COMPILER_ENV_VAR)
-set(_CMAKE_ASM_COMPILER_AR)
-set(_CMAKE_ASM_COMPILER_RANLIB)
+foreach(_var
+ COMPILER
+ COMPILER_ID
+ COMPILER_ARG1
+ COMPILER_ENV_VAR
+ COMPILER_AR
+ COMPILER_RANLIB
+ COMPILER_VERSION
+ )
+ unset(_CMAKE_ASM_${_var})
+endforeach()
diff --git a/Modules/CMakeDetermineCCompiler.cmake b/Modules/CMakeDetermineCCompiler.cmake
index 3caccdeab..4e56ce1cf 100644
--- a/Modules/CMakeDetermineCCompiler.cmake
+++ b/Modules/CMakeDetermineCCompiler.cmake
@@ -110,6 +110,7 @@ if(NOT CMAKE_C_COMPILER_ID_RUN)
include(${CMAKE_ROOT}/Modules/CMakeDetermineCompilerId.cmake)
CMAKE_DETERMINE_COMPILER_ID(C CFLAGS CMakeCCompilerId.c)
+ CMAKE_DIAGNOSE_UNSUPPORTED_CLANG(C CC)
# Set old compiler and platform id variables.
if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
@@ -170,6 +171,13 @@ set(_CMAKE_PROCESSING_LANGUAGE "C")
include(Compiler/${CMAKE_C_COMPILER_ID}-FindBinUtils OPTIONAL)
unset(_CMAKE_PROCESSING_LANGUAGE)
+if(CMAKE_C_COMPILER_ARCHITECTURE_ID)
+ set(_SET_CMAKE_C_COMPILER_ARCHITECTURE_ID
+ "set(CMAKE_C_COMPILER_ARCHITECTURE_ID ${CMAKE_C_COMPILER_ARCHITECTURE_ID})")
+else()
+ set(_SET_CMAKE_C_COMPILER_ARCHITECTURE_ID "")
+endif()
+
if(MSVC_C_ARCHITECTURE_ID)
set(SET_MSVC_C_ARCHITECTURE_ID
"set(MSVC_C_ARCHITECTURE_ID ${MSVC_C_ARCHITECTURE_ID})")
diff --git a/Modules/CMakeDetermineCSharpCompiler.cmake b/Modules/CMakeDetermineCSharpCompiler.cmake
index 55b2fb303..eb825a508 100644
--- a/Modules/CMakeDetermineCSharpCompiler.cmake
+++ b/Modules/CMakeDetermineCSharpCompiler.cmake
@@ -23,7 +23,7 @@ if(NOT CMAKE_CSharp_COMPILER_ID_RUN)
include(${CMAKE_ROOT}/Modules/CMakeDetermineCompilerId.cmake)
CMAKE_DETERMINE_COMPILER_ID(CSharp CSFLAGS CMakeCSharpCompilerId.cs)
- execute_process(COMMAND "${CMAKE_CSharp_COMPILER}" "/help" OUTPUT_VARIABLE output)
+ execute_process(COMMAND "${CMAKE_CSharp_COMPILER}" "/help /preferreduilang:en-US" OUTPUT_VARIABLE output)
string(REPLACE "\n" ";" output "${output}")
foreach(line ${output})
string(TOUPPER ${line} line)
diff --git a/Modules/CMakeDetermineCUDACompiler.cmake b/Modules/CMakeDetermineCUDACompiler.cmake
index 89ac9fa67..c9cd7e29b 100644
--- a/Modules/CMakeDetermineCUDACompiler.cmake
+++ b/Modules/CMakeDetermineCUDACompiler.cmake
@@ -87,6 +87,15 @@ if(${CMAKE_GENERATOR} MATCHES "Visual Studio")
elseif(CMAKE_CUDA_COMPILER_ID STREQUAL NVIDIA)
set(_nvcc_log "")
string(REPLACE "\r" "" _nvcc_output_orig "${CMAKE_CUDA_COMPILER_PRODUCED_OUTPUT}")
+ if(_nvcc_output_orig MATCHES "#\\\$ +PATH= *([^\n]*)\n")
+ set(_nvcc_path "${CMAKE_MATCH_1}")
+ string(APPEND _nvcc_log " found 'PATH=' string: [${_nvcc_path}]\n")
+ string(REPLACE ":" ";" _nvcc_path "${_nvcc_path}")
+ else()
+ set(_nvcc_path "")
+ string(REPLACE "\n" "\n " _nvcc_output_log "\n${_nvcc_output_orig}")
+ string(APPEND _nvcc_log " no 'PATH=' string found in nvcc output:${_nvcc_output_log}\n")
+ endif()
if(_nvcc_output_orig MATCHES "#\\\$ +LIBRARIES= *([^\n]*)\n")
set(_nvcc_libraries "${CMAKE_MATCH_1}")
string(APPEND _nvcc_log " found 'LIBRARIES=' string: [${_nvcc_libraries}]\n")
@@ -131,7 +140,26 @@ elseif(CMAKE_CUDA_COMPILER_ID STREQUAL NVIDIA)
else()
#extract the compiler that is being used for linking
separate_arguments(_nvcc_link_line_args UNIX_COMMAND "${_nvcc_link_line}")
- list(GET _nvcc_link_line_args 0 CMAKE_CUDA_HOST_LINK_LAUNCHER)
+ list(GET _nvcc_link_line_args 0 _nvcc_host_link_launcher)
+ if(IS_ABSOLUTE "${_nvcc_host_link_launcher}")
+ string(APPEND _nvcc_log " extracted link launcher absolute path: [${_nvcc_host_link_launcher}]\n")
+ set(CMAKE_CUDA_HOST_LINK_LAUNCHER "${_nvcc_host_link_launcher}")
+ else()
+ string(APPEND _nvcc_log " extracted link launcher name: [${_nvcc_host_link_launcher}]\n")
+ find_program(_nvcc_find_host_link_launcher
+ NAMES ${_nvcc_host_link_launcher}
+ PATHS ${_nvcc_path} NO_DEFAULT_PATH)
+ find_program(_nvcc_find_host_link_launcher
+ NAMES ${_nvcc_host_link_launcher})
+ if(_nvcc_find_host_link_launcher)
+ string(APPEND _nvcc_log " found link launcher absolute path: [${_nvcc_find_host_link_launcher}]\n")
+ set(CMAKE_CUDA_HOST_LINK_LAUNCHER "${_nvcc_find_host_link_launcher}")
+ else()
+ string(APPEND _nvcc_log " could not find link launcher absolute path\n")
+ set(CMAKE_CUDA_HOST_LINK_LAUNCHER "${_nvcc_host_link_launcher}")
+ endif()
+ unset(_nvcc_find_host_link_launcher CACHE)
+ endif()
endif()
#prefix the line with cuda-fake-ld so that implicit link info believes it is
diff --git a/Modules/CMakeDetermineCXXCompiler.cmake b/Modules/CMakeDetermineCXXCompiler.cmake
index 9150962d9..454184429 100644
--- a/Modules/CMakeDetermineCXXCompiler.cmake
+++ b/Modules/CMakeDetermineCXXCompiler.cmake
@@ -73,6 +73,9 @@ else()
set(CMAKE_CXX_COMPILER_ID_TEST_FLAGS
# Try compiling to an object file only.
"-c"
+ # IAR does not detect language automatically
+ "--c++"
+ "--ec++"
)
endif()
@@ -102,6 +105,7 @@ if(NOT CMAKE_CXX_COMPILER_ID_RUN)
include(${CMAKE_ROOT}/Modules/CMakeDetermineCompilerId.cmake)
CMAKE_DETERMINE_COMPILER_ID(CXX CXXFLAGS CMakeCXXCompilerId.cpp)
+ CMAKE_DIAGNOSE_UNSUPPORTED_CLANG(CXX CXX)
# Set old compiler and platform id variables.
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
@@ -165,6 +169,13 @@ set(_CMAKE_PROCESSING_LANGUAGE "CXX")
include(Compiler/${CMAKE_CXX_COMPILER_ID}-FindBinUtils OPTIONAL)
unset(_CMAKE_PROCESSING_LANGUAGE)
+if(CMAKE_CXX_COMPILER_ARCHITECTURE_ID)
+ set(_SET_CMAKE_CXX_COMPILER_ARCHITECTURE_ID
+ "set(CMAKE_CXX_COMPILER_ARCHITECTURE_ID ${CMAKE_CXX_COMPILER_ARCHITECTURE_ID})")
+else()
+ set(_SET_CMAKE_CXX_COMPILER_ARCHITECTURE_ID "")
+endif()
+
if(MSVC_CXX_ARCHITECTURE_ID)
set(SET_MSVC_CXX_ARCHITECTURE_ID
"set(MSVC_CXX_ARCHITECTURE_ID ${MSVC_CXX_ARCHITECTURE_ID})")
diff --git a/Modules/CMakeDetermineCompilerId.cmake b/Modules/CMakeDetermineCompilerId.cmake
index 7588f63b7..347106e78 100644
--- a/Modules/CMakeDetermineCompilerId.cmake
+++ b/Modules/CMakeDetermineCompilerId.cmake
@@ -102,11 +102,13 @@ function(CMAKE_DETERMINE_COMPILER_ID lang flagvar src)
set(CMAKE_${lang}_COMPILER_ID "${CMAKE_${lang}_COMPILER_ID}" PARENT_SCOPE)
set(CMAKE_${lang}_PLATFORM_ID "${CMAKE_${lang}_PLATFORM_ID}" PARENT_SCOPE)
+ set(CMAKE_${lang}_COMPILER_ARCHITECTURE_ID "${CMAKE_${lang}_COMPILER_ARCHITECTURE_ID}" PARENT_SCOPE)
set(MSVC_${lang}_ARCHITECTURE_ID "${MSVC_${lang}_ARCHITECTURE_ID}"
PARENT_SCOPE)
set(CMAKE_${lang}_XCODE_CURRENT_ARCH "${CMAKE_${lang}_XCODE_CURRENT_ARCH}" PARENT_SCOPE)
set(CMAKE_${lang}_CL_SHOWINCLUDES_PREFIX "${CMAKE_${lang}_CL_SHOWINCLUDES_PREFIX}" PARENT_SCOPE)
set(CMAKE_${lang}_COMPILER_VERSION "${CMAKE_${lang}_COMPILER_VERSION}" PARENT_SCOPE)
+ set(CMAKE_${lang}_COMPILER_VERSION_INTERNAL "${CMAKE_${lang}_COMPILER_VERSION_INTERNAL}" PARENT_SCOPE)
set(CMAKE_${lang}_COMPILER_WRAPPER "${CMAKE_${lang}_COMPILER_WRAPPER}" PARENT_SCOPE)
set(CMAKE_${lang}_SIMULATE_ID "${CMAKE_${lang}_SIMULATE_ID}" PARENT_SCOPE)
set(CMAKE_${lang}_SIMULATE_VERSION "${CMAKE_${lang}_SIMULATE_VERSION}" PARENT_SCOPE)
@@ -219,7 +221,9 @@ Id flags: ${testflags} ${CMAKE_${lang}_COMPILER_ID_FLAGS_ALWAYS}
if(CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION)
set(id_WindowsTargetPlatformVersion "<WindowsTargetPlatformVersion>${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}</WindowsTargetPlatformVersion>")
endif()
- if(id_platform STREQUAL ARM)
+ if(id_platform STREQUAL ARM64)
+ set(id_WindowsSDKDesktopARMSupport "<WindowsSDKDesktopARM64Support>true</WindowsSDKDesktopARM64Support>")
+ elseif(id_platform STREQUAL ARM)
set(id_WindowsSDKDesktopARMSupport "<WindowsSDKDesktopARMSupport>true</WindowsSDKDesktopARMSupport>")
else()
set(id_WindowsSDKDesktopARMSupport "")
@@ -318,12 +322,19 @@ Id flags: ${testflags} ${CMAKE_${lang}_COMPILER_ID_FLAGS_ALWAYS}
set(id_product_type "com.apple.product-type.tool")
if(CMAKE_OSX_SYSROOT)
set(id_sdkroot "SDKROOT = \"${CMAKE_OSX_SYSROOT}\";")
- if(CMAKE_OSX_SYSROOT MATCHES "(^|/)[Ii][Pp][Hh][Oo][Nn][Ee]")
+ if(CMAKE_OSX_SYSROOT MATCHES "(^|/)[Ii][Pp][Hh][Oo][Nn][Ee]" OR
+ CMAKE_OSX_SYSROOT MATCHES "(^|/)[Aa][Pp][Pp][Ll][Ee][Tt][Vv]")
set(id_product_type "com.apple.product-type.bundle.unit-test")
endif()
else()
set(id_sdkroot "")
endif()
+ if(CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM)
+ set(id_development_team
+ "DEVELOPMENT_TEAM = \"${CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM}\";")
+ else()
+ set(id_development_team "")
+ endif()
configure_file(${CMAKE_ROOT}/Modules/CompilerId/Xcode-3.pbxproj.in
${id_dir}/CompilerId${lang}.xcodeproj/project.pbxproj @ONLY)
unset(_ENV_MACOSX_DEPLOYMENT_TARGET)
@@ -463,6 +474,7 @@ function(CMAKE_DETERMINE_COMPILER_ID_CHECK lang file)
set(COMPILER_VERSION_MINOR 0)
set(COMPILER_VERSION_PATCH 0)
set(COMPILER_VERSION_TWEAK 0)
+ set(COMPILER_VERSION_INTERNAL "")
set(HAVE_COMPILER_VERSION_MAJOR 0)
set(HAVE_COMPILER_VERSION_MINOR 0)
set(HAVE_COMPILER_VERSION_PATCH 0)
@@ -504,6 +516,10 @@ function(CMAKE_DETERMINE_COMPILER_ID_CHECK lang file)
string(REGEX REPLACE "^0+([0-9])" "\\1" COMPILER_VERSION "${CMAKE_MATCH_1}")
string(REGEX REPLACE "\\.0+([0-9])" ".\\1" COMPILER_VERSION "${COMPILER_VERSION}")
endif()
+ if("${info}" MATCHES "INFO:compiler_version_internal\\[([^]\"]*)\\]")
+ string(REGEX REPLACE "^0+([0-9])" "\\1" COMPILER_VERSION_INTERNAL "${CMAKE_MATCH_1}")
+ string(REGEX REPLACE "\\.0+([0-9])" ".\\1" COMPILER_VERSION_INTERNAL "${COMPILER_VERSION_INTERNAL}")
+ endif()
foreach(comp MAJOR MINOR PATCH TWEAK)
foreach(digit 1 2 3 4 5 6 7 8 9)
if("${info}" MATCHES "INFO:compiler_version_${comp}_digit_${digit}\\[([0-9])\\]")
@@ -576,8 +592,10 @@ function(CMAKE_DETERMINE_COMPILER_ID_CHECK lang file)
if(COMPILER_ID AND NOT COMPILER_ID_TWICE)
set(CMAKE_${lang}_COMPILER_ID "${COMPILER_ID}")
set(CMAKE_${lang}_PLATFORM_ID "${PLATFORM_ID}")
+ set(CMAKE_${lang}_COMPILER_ARCHITECTURE_ID "${ARCHITECTURE_ID}")
set(MSVC_${lang}_ARCHITECTURE_ID "${ARCHITECTURE_ID}")
set(CMAKE_${lang}_COMPILER_VERSION "${COMPILER_VERSION}")
+ set(CMAKE_${lang}_COMPILER_VERSION_INTERNAL "${COMPILER_VERSION_INTERNAL}")
set(CMAKE_${lang}_SIMULATE_ID "${SIMULATE_ID}")
set(CMAKE_${lang}_SIMULATE_VERSION "${SIMULATE_VERSION}")
endif()
@@ -625,9 +643,11 @@ function(CMAKE_DETERMINE_COMPILER_ID_CHECK lang file)
# Return the information extracted.
set(CMAKE_${lang}_COMPILER_ID "${CMAKE_${lang}_COMPILER_ID}" PARENT_SCOPE)
set(CMAKE_${lang}_PLATFORM_ID "${CMAKE_${lang}_PLATFORM_ID}" PARENT_SCOPE)
+ set(CMAKE_${lang}_COMPILER_ARCHITECTURE_ID "${CMAKE_${lang}_COMPILER_ARCHITECTURE_ID}" PARENT_SCOPE)
set(MSVC_${lang}_ARCHITECTURE_ID "${MSVC_${lang}_ARCHITECTURE_ID}"
PARENT_SCOPE)
set(CMAKE_${lang}_COMPILER_VERSION "${CMAKE_${lang}_COMPILER_VERSION}" PARENT_SCOPE)
+ set(CMAKE_${lang}_COMPILER_VERSION_INTERNAL "${CMAKE_${lang}_COMPILER_VERSION_INTERNAL}" PARENT_SCOPE)
set(CMAKE_${lang}_COMPILER_WRAPPER "${COMPILER_WRAPPER}" PARENT_SCOPE)
set(CMAKE_${lang}_SIMULATE_ID "${CMAKE_${lang}_SIMULATE_ID}" PARENT_SCOPE)
set(CMAKE_${lang}_SIMULATE_VERSION "${CMAKE_${lang}_SIMULATE_VERSION}" PARENT_SCOPE)
@@ -675,6 +695,7 @@ function(CMAKE_DETERMINE_COMPILER_ID_VENDOR lang userflags)
"Checking whether the ${lang} compiler is ${vendor} using \"${flags}\" "
"matched \"${regex}\":\n${output}")
set(CMAKE_${lang}_COMPILER_ID "${vendor}" PARENT_SCOPE)
+ set(CMAKE_${lang}_COMPILER_ID_OUTPUT "${output}" PARENT_SCOPE)
break()
else()
if("${result}" MATCHES "timeout")
@@ -714,3 +735,38 @@ function(CMAKE_DETERMINE_MSVC_SHOWINCLUDES_PREFIX lang userflags)
set(CMAKE_${lang}_CL_SHOWINCLUDES_PREFIX "" PARENT_SCOPE)
endif()
endfunction()
+
+function(CMAKE_DIAGNOSE_UNSUPPORTED_CLANG lang envvar)
+ if(NOT CMAKE_HOST_WIN32 OR CMAKE_GENERATOR MATCHES "Visual Studio" OR
+ NOT "${CMAKE_${lang}_COMPILER_ID};${CMAKE_${lang}_SIMULATE_ID}" STREQUAL "Clang;MSVC")
+ return()
+ endif()
+
+ # Test whether a GNU-like command-line option works.
+ execute_process(COMMAND "${CMAKE_${lang}_COMPILER}" --version
+ RESULT_VARIABLE _clang_result
+ OUTPUT_VARIABLE _clang_stdout
+ ERROR_VARIABLE _clang_stderr)
+ if(NOT _clang_result EQUAL 0)
+ return()
+ endif()
+
+ # Help the user configure the environment to use the MSVC-like Clang.
+ string(CONCAT _msg
+ "The Clang compiler tool\n"
+ " \"${CMAKE_${lang}_COMPILER}\"\n"
+ "targets the MSVC ABI but has a GNU-like command-line interface. "
+ "This is not supported. "
+ "Use 'clang-cl' instead, e.g. by setting '${envvar}=clang-cl' in the environment."
+ )
+ execute_process(COMMAND rc -help
+ RESULT_VARIABLE _rc_result
+ OUTPUT_VARIABLE _rc_stdout
+ ERROR_VARIABLE _rc_stderr)
+ if(NOT _rc_result EQUAL 0)
+ string(APPEND _msg " "
+ "Furthermore, use the MSVC command-line environment."
+ )
+ endif()
+ message(FATAL_ERROR "${_msg}")
+endfunction()
diff --git a/Modules/CMakeDetermineFortranCompiler.cmake b/Modules/CMakeDetermineFortranCompiler.cmake
index d5220b4de..2549c22b8 100644
--- a/Modules/CMakeDetermineFortranCompiler.cmake
+++ b/Modules/CMakeDetermineFortranCompiler.cmake
@@ -52,6 +52,7 @@ else()
# frt: Fujitsu F77 compiler
# pathf90/pathf95/pathf2003: PathScale Fortran compiler
# pgf77/pgf90/pgf95/pgfortran: Portland Group F77/F90/F95 compilers
+ # flang: Flang Fortran compiler
# xlf/xlf90/xlf95: IBM (AIX) F77/F90/F95 compilers
# lf95: Lahey-Fujitsu F95 compiler
# fl32: Microsoft Fortran 77 "PowerStation" compiler
@@ -68,7 +69,7 @@ else()
set(CMAKE_Fortran_COMPILER_LIST
ftn
ifort ifc af95 af90 efc f95 pathf2003 pathf95 pgf95 pgfortran lf95 xlf95
- fort gfortran gfortran-4 g95 f90 pathf90 pgf90 xlf90 epcf90 fort77
+ fort flang gfortran gfortran-4 g95 f90 pathf90 pgf90 xlf90 epcf90 fort77
frt pgf77 xlf fl32 af77 g77 f77 nag
)
@@ -77,10 +78,11 @@ else()
set(_Fortran_COMPILER_NAMES_Intel ifort ifc efc)
set(_Fortran_COMPILER_NAMES_Absoft af95 af90 af77)
set(_Fortran_COMPILER_NAMES_PGI pgf95 pgfortran pgf90 pgf77)
+ set(_Fortran_COMPILER_NAMES_Flang flang)
set(_Fortran_COMPILER_NAMES_PathScale pathf2003 pathf95 pathf90)
set(_Fortran_COMPILER_NAMES_XL xlf)
set(_Fortran_COMPILER_NAMES_VisualAge xlf95 xlf90 xlf)
- set(_Fortran_COMPILER_NAMES_NAG nagfor)
+ set(_Fortran_COMPILER_NAMES_NAG nagfor)
endif()
_cmake_find_compiler(Fortran)
@@ -261,6 +263,13 @@ set(_CMAKE_PROCESSING_LANGUAGE "Fortran")
include(Compiler/${CMAKE_Fortran_COMPILER_ID}-FindBinUtils OPTIONAL)
unset(_CMAKE_PROCESSING_LANGUAGE)
+if(CMAKE_Fortran_COMPILER_ARCHITECTURE_ID)
+ set(_SET_CMAKE_Fortran_COMPILER_ARCHITECTURE_ID
+ "set(CMAKE_Fortran_COMPILER_ARCHITECTURE_ID ${CMAKE_Fortran_COMPILER_ARCHITECTURE_ID})")
+else()
+ set(_SET_CMAKE_Fortran_COMPILER_ARCHITECTURE_ID "")
+endif()
+
if(MSVC_Fortran_ARCHITECTURE_ID)
set(SET_MSVC_Fortran_ARCHITECTURE_ID
"set(MSVC_Fortran_ARCHITECTURE_ID ${MSVC_Fortran_ARCHITECTURE_ID})")
diff --git a/Modules/CMakeFindDependencyMacro.cmake b/Modules/CMakeFindDependencyMacro.cmake
index 81606cef6..6a89fff2a 100644
--- a/Modules/CMakeFindDependencyMacro.cmake
+++ b/Modules/CMakeFindDependencyMacro.cmake
@@ -1,23 +1,34 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
-#.rst:
-# CMakeFindDependencyMacro
-# -------------------------
-#
-# ::
-#
-# find_dependency(<dep> [...])
-#
-#
-# ``find_dependency()`` wraps a :command:`find_package` call for a package
-# dependency. It is designed to be used in a <package>Config.cmake file, and it
-# forwards the correct parameters for QUIET and REQUIRED which were passed to
-# the original :command:`find_package` call. It also sets an informative
-# diagnostic message if the dependency could not be found.
-#
-# Any additional arguments specified are forwarded to :command:`find_package`.
-#
+#[=======================================================================[.rst:
+CMakeFindDependencyMacro
+-------------------------
+
+.. command:: find_dependency
+
+ The ``find_dependency()`` macro wraps a :command:`find_package` call for
+ a package dependency::
+
+ find_dependency(<dep> [...])
+
+ It is designed to be used in a
+ :ref:`Package Configuration File <Config File Packages>`
+ (``<package>Config.cmake``). ``find_dependency`` forwards the correct
+ parameters for ``QUIET`` and ``REQUIRED`` which were passed to
+ the original :command:`find_package` call. Any additional arguments
+ specified are forwarded to :command:`find_package`.
+
+ If the dependency could not be found it sets an informative diagnostic
+ message and calls :command:`return` to end processing of the calling
+ package configuration file and return to the :command:`find_package`
+ command that loaded it.
+
+ .. note::
+
+ The call to :command:`return` makes this macro unsuitable to call
+ from :ref:`Find Modules`.
+#]=======================================================================]
macro(find_dependency dep)
if (NOT ${dep}_FOUND)
diff --git a/Modules/CMakeFortranCompiler.cmake.in b/Modules/CMakeFortranCompiler.cmake.in
index d52119050..2e34cbbdf 100644
--- a/Modules/CMakeFortranCompiler.cmake.in
+++ b/Modules/CMakeFortranCompiler.cmake.in
@@ -6,6 +6,7 @@ set(CMAKE_Fortran_COMPILER_WRAPPER "@CMAKE_Fortran_COMPILER_WRAPPER@")
set(CMAKE_Fortran_PLATFORM_ID "@CMAKE_Fortran_PLATFORM_ID@")
set(CMAKE_Fortran_SIMULATE_ID "@CMAKE_Fortran_SIMULATE_ID@")
set(CMAKE_Fortran_SIMULATE_VERSION "@CMAKE_Fortran_SIMULATE_VERSION@")
+@_SET_CMAKE_Fortran_COMPILER_ARCHITECTURE_ID@
@SET_MSVC_Fortran_ARCHITECTURE_ID@
set(CMAKE_AR "@CMAKE_AR@")
set(CMAKE_Fortran_COMPILER_AR "@CMAKE_Fortran_COMPILER_AR@")
diff --git a/Modules/CMakeFortranCompilerId.F.in b/Modules/CMakeFortranCompilerId.F.in
index 26b2ed656..49789f197 100644
--- a/Modules/CMakeFortranCompilerId.F.in
+++ b/Modules/CMakeFortranCompilerId.F.in
@@ -90,6 +90,13 @@
# if defined(__PGIC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__)
# endif
+#elif defined(__FLANG)
+ PRINT *, 'INFO:compiler[Flang]'
+# define COMPILER_VERSION_MAJOR DEC(__FLANG_MAJOR__)
+# define COMPILER_VERSION_MINOR DEC(__FLANG_MINOR__)
+# if defined(__FLANG_PATCHLEVEL__)
+# define COMPILER_VERSION_PATCH DEC(__FLANG_PATCHLEVEL__)
+# endif
#elif defined(_SGI_COMPILER_VERSION) || defined(_COMPILER_VERSION)
PRINT *, 'INFO:compiler[MIPSpro]'
# if 0
diff --git a/Modules/CMakeGenericSystem.cmake b/Modules/CMakeGenericSystem.cmake
index cd052376b..324a27939 100644
--- a/Modules/CMakeGenericSystem.cmake
+++ b/Modules/CMakeGenericSystem.cmake
@@ -23,6 +23,8 @@ set(CMAKE_DL_LIBS "dl")
set(CMAKE_FIND_LIBRARY_PREFIXES "lib")
set(CMAKE_FIND_LIBRARY_SUFFIXES ".so" ".a")
+set(CMAKE_AUTOMOC_COMPILER_PREDEFINES ON)
+set(CMAKE_AUTOMOC_MACRO_NAMES "Q_OBJECT" "Q_GADGET" "Q_NAMESPACE")
# basically all general purpose OSs support shared libs
set_property(GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS TRUE)
@@ -76,6 +78,8 @@ function(GetDefaultWindowsPrefixBase var)
#
if("${CMAKE_GENERATOR}" MATCHES "(Win64|IA64)")
set(arch_hint "x64")
+ elseif("${CMAKE_GENERATOR_PLATFORM}" MATCHES "ARM64")
+ set(arch_hint "ARM64")
elseif("${CMAKE_GENERATOR}" MATCHES "ARM")
set(arch_hint "ARM")
elseif("${CMAKE_SIZEOF_VOID_P}" STREQUAL "8")
diff --git a/Modules/CMakeGraphVizOptions.cmake b/Modules/CMakeGraphVizOptions.cmake
index 420e3a9e7..0d7f1d979 100644
--- a/Modules/CMakeGraphVizOptions.cmake
+++ b/Modules/CMakeGraphVizOptions.cmake
@@ -11,19 +11,22 @@
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# CMake
-# can generate graphviz files, showing the dependencies between the
+# can generate `graphviz <http://www.graphviz.org/>`_ files, showing the dependencies between the
# targets in a project and also external libraries which are linked
-# against. When CMake is run with the --graphviz=foo.dot option, it will
+# against. When CMake is run with the ``--graphviz=foo.dot`` option, it will
# produce:
#
-# * a foo.dot file showing all dependencies in the project
-# * a foo.dot.<target> file for each target, file showing on which other targets the respective target depends
-# * a foo.dot.<target>.dependers file, showing which other targets depend on the respective target
+# * a ``foo.dot`` file showing all dependencies in the project
+# * a ``foo.dot.<target>`` file for each target, file showing on which other targets the respective target depends
+# * a ``foo.dot.<target>.dependers`` file, showing which other targets depend on the respective target
+#
+# The different dependency types ``PUBLIC``, ``PRIVATE`` and ``INTERFACE``
+# are represented as solid, dashed and dotted edges.
#
# This can result in huge graphs. Using the file
-# CMakeGraphVizOptions.cmake the look and content of the generated
+# ``CMakeGraphVizOptions.cmake`` the look and content of the generated
# graphs can be influenced. This file is searched first in
-# ${CMAKE_BINARY_DIR} and then in ${CMAKE_SOURCE_DIR}. If found, it is
+# :variable:`CMAKE_BINARY_DIR` and then in :variable:`CMAKE_SOURCE_DIR`. If found, it is
# read and the variables set in it are used to adjust options for the
# generated graphviz files.
#
diff --git a/Modules/CMakePlatformId.h.in b/Modules/CMakePlatformId.h.in
index 47eb00a39..dd77379c3 100644
--- a/Modules/CMakePlatformId.h.in
+++ b/Modules/CMakePlatformId.h.in
@@ -114,6 +114,9 @@
# elif defined(_M_IX86)
# define ARCHITECTURE_ID "X86"
+# elif defined(_M_ARM64)
+# define ARCHITECTURE_ID "ARM64"
+
# elif defined(_M_ARM)
# if _M_ARM == 4
# define ARCHITECTURE_ID "ARMV4I"
@@ -144,6 +147,16 @@
# define ARCHITECTURE_ID ""
# endif
+#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC)
+# if defined(__ICCARM__)
+# define ARCHITECTURE_ID "ARM"
+
+# elif defined(__ICCAVR__)
+# define ARCHITECTURE_ID "AVR"
+
+# else /* unknown architecture */
+# define ARCHITECTURE_ID ""
+# endif
#else
# define ARCHITECTURE_ID
#endif
@@ -188,6 +201,15 @@ char const info_version[] = {
']','\0'};
#endif
+/* Construct a string literal encoding the internal version number. */
+#ifdef COMPILER_VERSION_INTERNAL
+char const info_version_internal[] = {
+ 'I', 'N', 'F', 'O', ':',
+ 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_',
+ 'i','n','t','e','r','n','a','l','[',
+ COMPILER_VERSION_INTERNAL,']','\0'};
+#endif
+
/* Construct a string literal encoding the version number components. */
#ifdef SIMULATE_VERSION_MAJOR
char const info_simulate_version[] = {
diff --git a/Modules/CMakePushCheckState.cmake b/Modules/CMakePushCheckState.cmake
index 2a527d5bd..98eea0532 100644
--- a/Modules/CMakePushCheckState.cmake
+++ b/Modules/CMakePushCheckState.cmake
@@ -62,7 +62,7 @@ macro(CMAKE_PUSH_CHECK_STATE)
set(_CMAKE_REQUIRED_FLAGS_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER} ${CMAKE_REQUIRED_FLAGS})
set(_CMAKE_REQUIRED_QUIET_SAVE_${_CMAKE_PUSH_CHECK_STATE_COUNTER} ${CMAKE_REQUIRED_QUIET})
- if (ARGC GREATER 0 AND ARGV0 STREQUAL "RESET")
+ if (${ARGC} GREATER 0 AND "${ARGV0}" STREQUAL "RESET")
cmake_reset_check_state()
endif()
diff --git a/Modules/CMakeTestCCompiler.cmake b/Modules/CMakeTestCCompiler.cmake
index 7f199699e..e34ae756d 100644
--- a/Modules/CMakeTestCCompiler.cmake
+++ b/Modules/CMakeTestCCompiler.cmake
@@ -48,9 +48,10 @@ if(NOT CMAKE_C_COMPILER_WORKS)
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"Determining if the C compiler works failed with "
"the following output:\n${__CMAKE_C_COMPILER_OUTPUT}\n\n")
- message(FATAL_ERROR "The C compiler \"${CMAKE_C_COMPILER}\" "
+ string(REPLACE "\n" "\n " _output "${__CMAKE_C_COMPILER_OUTPUT}")
+ message(FATAL_ERROR "The C compiler\n \"${CMAKE_C_COMPILER}\"\n"
"is not able to compile a simple test program.\nIt fails "
- "with the following output:\n ${__CMAKE_C_COMPILER_OUTPUT}\n\n"
+ "with the following output:\n ${_output}\n\n"
"CMake will not be able to correctly generate this project.")
else()
if(C_TEST_WAS_RUN)
diff --git a/Modules/CMakeTestCSharpCompiler.cmake b/Modules/CMakeTestCSharpCompiler.cmake
index 1a8bf32e0..f3b95fd0e 100644
--- a/Modules/CMakeTestCSharpCompiler.cmake
+++ b/Modules/CMakeTestCSharpCompiler.cmake
@@ -42,9 +42,10 @@ if(NOT CMAKE_CSharp_COMPILER_WORKS)
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"Determining if the C# compiler works failed with "
"the following output:\n${__CMAKE_CSharp_COMPILER_OUTPUT}\n\n")
- message(FATAL_ERROR "The C# compiler \"${CMAKE_CSharp_COMPILER}\" "
+ string(REPLACE "\n" "\n " _output "${__CMAKE_CSharp_COMPILER_OUTPUT}")
+ message(FATAL_ERROR "The C# compiler\n \"${CMAKE_CSharp_COMPILER}\"\n"
"is not able to compile a simple test program.\nIt fails "
- "with the following output:\n ${__CMAKE_CSharp_COMPILER_OUTPUT}\n\n"
+ "with the following output:\n ${_output}\n\n"
"CMake will not be able to correctly generate this project.")
else()
if(CSharp_TEST_WAS_RUN)
diff --git a/Modules/CMakeTestCUDACompiler.cmake b/Modules/CMakeTestCUDACompiler.cmake
index 80113cb4a..df5ec726a 100644
--- a/Modules/CMakeTestCUDACompiler.cmake
+++ b/Modules/CMakeTestCUDACompiler.cmake
@@ -42,9 +42,10 @@ if(NOT CMAKE_CUDA_COMPILER_WORKS)
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"Determining if the CUDA compiler works failed with "
"the following output:\n${__CMAKE_CUDA_COMPILER_OUTPUT}\n\n")
- message(FATAL_ERROR "The CUDA compiler \"${CMAKE_CUDA_COMPILER}\" "
+ string(REPLACE "\n" "\n " _output "${__CMAKE_CUDA_COMPILER_OUTPUT}")
+ message(FATAL_ERROR "The CUDA compiler\n \"${CMAKE_CUDA_COMPILER}\"\n"
"is not able to compile a simple test program.\nIt fails "
- "with the following output:\n ${__CMAKE_CUDA_COMPILER_OUTPUT}\n\n"
+ "with the following output:\n ${_output}\n\n"
"CMake will not be able to correctly generate this project.")
else()
if(CUDA_TEST_WAS_RUN)
diff --git a/Modules/CMakeTestCXXCompiler.cmake b/Modules/CMakeTestCXXCompiler.cmake
index a31067b60..7b80dc093 100644
--- a/Modules/CMakeTestCXXCompiler.cmake
+++ b/Modules/CMakeTestCXXCompiler.cmake
@@ -41,9 +41,10 @@ if(NOT CMAKE_CXX_COMPILER_WORKS)
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"Determining if the CXX compiler works failed with "
"the following output:\n${__CMAKE_CXX_COMPILER_OUTPUT}\n\n")
- message(FATAL_ERROR "The C++ compiler \"${CMAKE_CXX_COMPILER}\" "
+ string(REPLACE "\n" "\n " _output "${__CMAKE_CXX_COMPILER_OUTPUT}")
+ message(FATAL_ERROR "The C++ compiler\n \"${CMAKE_CXX_COMPILER}\"\n"
"is not able to compile a simple test program.\nIt fails "
- "with the following output:\n ${__CMAKE_CXX_COMPILER_OUTPUT}\n\n"
+ "with the following output:\n ${_output}\n\n"
"CMake will not be able to correctly generate this project.")
else()
if(CXX_TEST_WAS_RUN)
diff --git a/Modules/CMakeTestFortranCompiler.cmake b/Modules/CMakeTestFortranCompiler.cmake
index c81694ef9..3c150a8ed 100644
--- a/Modules/CMakeTestFortranCompiler.cmake
+++ b/Modules/CMakeTestFortranCompiler.cmake
@@ -41,9 +41,10 @@ if(NOT CMAKE_Fortran_COMPILER_WORKS)
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"Determining if the Fortran compiler works failed with "
"the following output:\n${OUTPUT}\n\n")
- message(FATAL_ERROR "The Fortran compiler \"${CMAKE_Fortran_COMPILER}\" "
+ string(REPLACE "\n" "\n " _output "${OUTPUT}")
+ message(FATAL_ERROR "The Fortran compiler\n \"${CMAKE_Fortran_COMPILER}\"\n"
"is not able to compile a simple test program.\nIt fails "
- "with the following output:\n ${OUTPUT}\n\n"
+ "with the following output:\n ${_output}\n\n"
"CMake will not be able to correctly generate this project.")
else()
if(FORTRAN_TEST_WAS_RUN)
diff --git a/Modules/CMakeTestSwiftCompiler.cmake b/Modules/CMakeTestSwiftCompiler.cmake
index 6393f44a0..bcd5c33dc 100644
--- a/Modules/CMakeTestSwiftCompiler.cmake
+++ b/Modules/CMakeTestSwiftCompiler.cmake
@@ -39,9 +39,10 @@ if(NOT CMAKE_Swift_COMPILER_WORKS)
file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"Determining if the Swift compiler works failed with "
"the following output:\n${__CMAKE_Swift_COMPILER_OUTPUT}\n\n")
- message(FATAL_ERROR "The Swift compiler \"${CMAKE_Swift_COMPILER}\" "
+ string(REPLACE "\n" "\n " _output "${__CMAKE_Swift_COMPILER_OUTPUT}")
+ message(FATAL_ERROR "The Swift compiler\n \"${CMAKE_Swift_COMPILER}\"\n"
"is not able to compile a simple test program.\nIt fails "
- "with the following output:\n ${__CMAKE_Swift_COMPILER_OUTPUT}\n\n"
+ "with the following output:\n ${_output}\n\n"
"CMake will not be able to correctly generate this project.")
else()
if(Swift_TEST_WAS_RUN)
diff --git a/Modules/CPack.STGZ_Header.sh.in b/Modules/CPack.STGZ_Header.sh.in
index c61585136..70f63d2d6 100755
--- a/Modules/CPack.STGZ_Header.sh.in
+++ b/Modules/CPack.STGZ_Header.sh.in
@@ -7,9 +7,11 @@ cpack_usage()
Usage: $0 [options]
Options: [defaults in brackets after descriptions]
--help print this message
+ --version print cmake installer version
--prefix=dir directory in which to install
--include-subdir include the @CPACK_PACKAGE_FILE_NAME@ subdirectory
--exclude-subdir exclude the @CPACK_PACKAGE_FILE_NAME@ subdirectory
+ --skip-license accept license
EOF
exit 1
}
diff --git a/Modules/CPack.cmake b/Modules/CPack.cmake
index a63fc8325..391594381 100644
--- a/Modules/CPack.cmake
+++ b/Modules/CPack.cmake
@@ -471,6 +471,7 @@ if(NOT CPACK_GENERATOR)
option(CPACK_BINARY_TZ "Enable to build TZ packages" ON)
endif()
option(CPACK_BINARY_DEB "Enable to build Debian packages" OFF)
+ option(CPACK_BINARY_FREEBSD "Enable to build FreeBSD packages" OFF)
option(CPACK_BINARY_NSIS "Enable to build NSIS packages" OFF)
option(CPACK_BINARY_RPM "Enable to build RPM packages" OFF)
option(CPACK_BINARY_STGZ "Enable to build STGZ packages" ON)
@@ -491,6 +492,7 @@ if(NOT CPACK_GENERATOR)
cpack_optional_append(CPACK_GENERATOR CPACK_BINARY_CYGWIN CygwinBinary)
cpack_optional_append(CPACK_GENERATOR CPACK_BINARY_DEB DEB)
cpack_optional_append(CPACK_GENERATOR CPACK_BINARY_DRAGNDROP DragNDrop)
+ cpack_optional_append(CPACK_GENERATOR CPACK_BINARY_FREEBSD FREEBSD)
cpack_optional_append(CPACK_GENERATOR CPACK_BINARY_IFW IFW)
cpack_optional_append(CPACK_GENERATOR CPACK_BINARY_NSIS NSIS)
cpack_optional_append(CPACK_GENERATOR CPACK_BINARY_OSXX11 OSXX11)
@@ -542,6 +544,7 @@ mark_as_advanced(
CPACK_BINARY_CYGWIN
CPACK_BINARY_DEB
CPACK_BINARY_DRAGNDROP
+ CPACK_BINARY_FREEBSD
CPACK_BINARY_IFW
CPACK_BINARY_NSIS
CPACK_BINARY_OSXX11
diff --git a/Modules/CPackComponent.cmake b/Modules/CPackComponent.cmake
index 3a10b9930..2374fbda8 100644
--- a/Modules/CPackComponent.cmake
+++ b/Modules/CPackComponent.cmake
@@ -37,6 +37,16 @@
# components defined by the project. The user may set it to only include the
# specified components.
#
+# Instead of specifying all the desired components, it is possible to obtain a
+# list of all defined components and then remove the unwanted ones from the
+# list. The :command:`get_cmake_property` command can be used to obtain the
+# ``COMPONENTS`` property, then the :command:`list(REMOVE_ITEM)` command can be
+# used to remove the unwanted ones. For example, to use all defined components
+# except ``foo`` and ``bar``::
+#
+# get_cmake_property(CPACK_COMPONENTS_ALL COMPONENTS)
+# list(REMOVE_ITEM CPACK_COMPONENTS_ALL "foo" "bar")
+#
# .. variable:: CPACK_<GENNAME>_COMPONENT_INSTALL
#
# Enable/Disable component install for CPack generator <GENNAME>.
diff --git a/Modules/CPackDeb.cmake b/Modules/CPackDeb.cmake
index ddf8b23ee..187982701 100644
--- a/Modules/CPackDeb.cmake
+++ b/Modules/CPackDeb.cmake
@@ -73,7 +73,8 @@
#
# <PackageName>_<VersionNumber>-<DebianRevisionNumber>_<DebianArchitecture>.deb
#
-# Alternatively provided package file name must end with ``.deb`` suffix.
+# Alternatively provided package file name must end
+# with either ``.deb`` or ``.ipk`` suffix.
#
# .. note::
#
@@ -87,6 +88,16 @@
# get overwritten and it is up to the packager to set the variables in a
# manner that will prevent such errors.
#
+# .. variable:: CPACK_DEBIAN_PACKAGE_EPOCH
+#
+# The Debian package epoch
+#
+# * Mandatory : No
+# * Default : -
+#
+# Optional number that should be incremented when changing versioning schemas
+# or fixing mistakes in the version numbers of older packages.
+#
# .. variable:: CPACK_DEBIAN_PACKAGE_VERSION
#
# The Debian package version
@@ -94,12 +105,25 @@
# * Mandatory : YES
# * Default : :variable:`CPACK_PACKAGE_VERSION`
#
+# This variable may contain only alphanumerics (A-Za-z0-9) and the characters
+# . + - ~ (full stop, plus, hyphen, tilde) and should start with a digit. If
+# :variable:`CPACK_DEBIAN_PACKAGE_RELEASE` is not set then hyphens are not
+# allowed.
+#
+# .. note::
+#
+# For backward compatibility with CMake 3.9 and lower a failed test of this
+# variable's content is not a hard error when both
+# :variable:`CPACK_DEBIAN_PACKAGE_RELEASE` and
+# :variable:`CPACK_DEBIAN_PACKAGE_EPOCH` variables are not set. An author
+# warning is reported instead.
+#
# .. variable:: CPACK_DEBIAN_PACKAGE_RELEASE
#
# The Debian package release - Debian revision number.
#
-# * Mandatory : YES
-# * Default : 1
+# * Mandatory : No
+# * Default : -
#
# This is the numbering of the DEB package itself, i.e. the version of the
# packaging and not the version of the content (see
@@ -497,6 +521,16 @@
#
# This value is not interpreted. It is possible to pass an optional
# revision number of the referenced source package as well.
+#
+# Building Debian packages on Windows
+# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+#
+# To communicate UNIX file permissions from the install stage
+# to the CPack DEB generator the "cmake_mode_t" NTFS
+# alternate data stream (ADT) is used.
+#
+# When a filesystem without ADT support is used only owner read/write
+# permissions can be preserved.
# CPack script for creating Debian package
# Author: Mathieu Malaterre
@@ -507,10 +541,6 @@ if(CMAKE_BINARY_DIR)
message(FATAL_ERROR "CPackDeb.cmake may only be used by CPack internally.")
endif()
-if(NOT UNIX)
- message(FATAL_ERROR "CPackDeb.cmake may only be used under UNIX.")
-endif()
-
function(cpack_deb_variable_fallback OUTPUT_VAR_NAME)
set(FALLBACK_VAR_NAMES ${ARGN})
@@ -731,6 +761,51 @@ function(cpack_deb_prepare_package_vars)
set(CPACK_DEBIAN_PACKAGE_VERSION ${CPACK_PACKAGE_VERSION})
endif()
+ if(DEFINED CPACK_DEBIAN_PACKAGE_RELEASE OR DEFINED CPACK_DEBIAN_PACKAGE_EPOCH)
+ # only test the version format if CPACK_DEBIAN_PACKAGE_RELEASE or
+ # CPACK_DEBIAN_PACKAGE_EPOCH is set
+ if(NOT CPACK_DEBIAN_PACKAGE_VERSION MATCHES "^[0-9][A-Za-z0-9.+~-]*$")
+ message(FATAL_ERROR
+ "CPackDeb: Debian package version must confirm to \"^[0-9][A-Za-z0-9.+~-]*$\" regex!")
+ endif()
+ else()
+ # before CMake 3.10 version format was not tested so only warn to preserve
+ # backward compatibility
+ if(NOT CPACK_DEBIAN_PACKAGE_VERSION MATCHES "^([0-9]+:)?[0-9][A-Za-z0-9.+~-]*$")
+ message(AUTHOR_WARNING
+ "CPackDeb: Debian package versioning ([<epoch>:]<version>[-<release>])"
+ " should confirm to \"^([0-9]+:)?[0-9][A-Za-z0-9.+~-]*$\" regex in"
+ " order to satisfy Debian packaging rules.")
+ endif()
+ endif()
+
+ if(CPACK_DEBIAN_PACKAGE_RELEASE)
+ if(NOT CPACK_DEBIAN_PACKAGE_RELEASE MATCHES "^[A-Za-z0-9.+~]+$")
+ message(FATAL_ERROR
+ "CPackDeb: Debian package release must confirm to \"^[A-Za-z0-9.+~]+$\" regex!")
+ endif()
+ string(APPEND CPACK_DEBIAN_PACKAGE_VERSION
+ "-${CPACK_DEBIAN_PACKAGE_RELEASE}")
+ elseif(DEFINED CPACK_DEBIAN_PACKAGE_EPOCH)
+ # only test the version format if CPACK_DEBIAN_PACKAGE_RELEASE or
+ # CPACK_DEBIAN_PACKAGE_EPOCH is set - versions CPack/Deb generator before
+ # CMake 3.10 did not check for version format so we have to preserve
+ # backward compatibility
+ if(CPACK_DEBIAN_PACKAGE_VERSION MATCHES ".*-.*")
+ message(FATAL_ERROR
+ "CPackDeb: Debian package version must not contain hyphens when CPACK_DEBIAN_PACKAGE_RELEASE is not provided!")
+ endif()
+ endif()
+
+ if(CPACK_DEBIAN_PACKAGE_EPOCH)
+ if(NOT CPACK_DEBIAN_PACKAGE_EPOCH MATCHES "^[0-9]+$")
+ message(FATAL_ERROR
+ "CPackDeb: Debian package epoch must confirm to \"^[0-9]+$\" regex!")
+ endif()
+ set(CPACK_DEBIAN_PACKAGE_VERSION
+ "${CPACK_DEBIAN_PACKAGE_EPOCH}:${CPACK_DEBIAN_PACKAGE_VERSION}")
+ endif()
+
# Architecture: (mandatory)
if(CPACK_DEB_PACKAGE_COMPONENT AND CPACK_DEBIAN_${_local_component_name}_PACKAGE_ARCHITECTURE)
set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "${CPACK_DEBIAN_${_local_component_name}_PACKAGE_ARCHITECTURE}")
@@ -954,11 +1029,6 @@ function(cpack_deb_prepare_package_vars)
set(CPACK_DEBIAN_GENERATE_POSTRM 0)
endif()
- if(NOT CPACK_DEBIAN_PACKAGE_RELEASE)
- set(CPACK_DEBIAN_PACKAGE_RELEASE 1)
- endif()
-
-
cpack_deb_variable_fallback("CPACK_DEBIAN_FILE_NAME"
"CPACK_DEBIAN_${_local_component_name}_FILE_NAME"
"CPACK_DEBIAN_FILE_NAME")
@@ -967,13 +1037,13 @@ function(cpack_deb_prepare_package_vars)
# Patch package file name to be in corrent debian format:
# <foo>_<VersionNumber>-<DebianRevisionNumber>_<DebianArchitecture>.deb
set(CPACK_OUTPUT_FILE_NAME
- "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_DEBIAN_PACKAGE_VERSION}-${CPACK_DEBIAN_PACKAGE_RELEASE}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}.deb")
+ "${CPACK_DEBIAN_PACKAGE_NAME}_${CPACK_DEBIAN_PACKAGE_VERSION}_${CPACK_DEBIAN_PACKAGE_ARCHITECTURE}.deb")
else()
cmake_policy(PUSH)
cmake_policy(SET CMP0010 NEW)
- if(NOT CPACK_DEBIAN_FILE_NAME MATCHES ".*\\.deb")
+ if(NOT CPACK_DEBIAN_FILE_NAME MATCHES ".*\\.(deb|ipk)")
cmake_policy(POP)
- message(FATAL_ERROR "'${CPACK_DEBIAN_FILE_NAME}' is not a valid DEB package file name as it must end with '.deb'!")
+ message(FATAL_ERROR "'${CPACK_DEBIAN_FILE_NAME}' is not a valid DEB package file name as it must end with '.deb' or '.ipk'!")
endif()
cmake_policy(POP)
diff --git a/Modules/CPackFreeBSD.cmake b/Modules/CPackFreeBSD.cmake
new file mode 100644
index 000000000..7fec78a35
--- /dev/null
+++ b/Modules/CPackFreeBSD.cmake
@@ -0,0 +1,246 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+CPackFreeBSD
+------------
+
+The built in (binary) CPack FreeBSD (pkg) generator (Unix only)
+
+Variables specific to CPack FreeBSD (pkg) generator
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+CPackFreeBSD may be used to create pkg(8) packages -- these may be used
+on FreeBSD, DragonflyBSD, NetBSD, OpenBSD, but also on Linux or OSX,
+depending on the installed package-management tools -- using :module:`CPack`.
+
+CPackFreeBSD is a :module:`CPack` generator and uses the ``CPACK_XXX``
+variables used by :module:`CPack`. It tries to re-use packaging information
+that may already be specified for Debian packages for the :module:`CPackDeb`
+generator. it also tries to re-use RPM packaging information when Debian
+does not specify.
+
+CPackFreeBSD generator should work on any host with libpkg installed. The
+packages it produces are specific to the host architecture and ABI.
+
+CPackFreeBSD sets package-metadata through :code:`CPACK_FREEBSD_XXX` variables.
+CPackFreeBSD, unlike CPackDeb, does not specially support componentized
+packages; a single package is created from all the software artifacts
+created through CMake.
+
+All of the variables can be set specifically for FreeBSD packaging in
+the CPackConfig file or in CMakeLists.txt, but most of them have defaults
+that use general settings (e.g. CMAKE_PROJECT_NAME) or Debian-specific
+variables when those make sense (e.g. the homepage of an upstream project
+is usually unchanged by the flavor of packaging). When there is no Debian
+information to fall back on, but the RPM packaging has it, fall back to
+the RPM information (e.g. package license).
+
+.. variable:: CPACK_FREEBSD_PACKAGE_NAME
+
+ Sets the package name (in the package manifest, but also affects the
+ output filename).
+
+ * Mandatory: YES
+ * Default:
+
+ - :variable:`CPACK_PACKAGE_NAME` (this is always set by CPack itself,
+ based on CMAKE_PROJECT_NAME).
+
+.. variable:: CPACK_FREEBSD_PACKAGE_COMMENT
+
+ Sets the package comment. This is the short description displayed by
+ pkg(8) in standard "pkg info" output.
+
+ * Mandatory: YES
+ * Default:
+
+ - :variable:`CPACK_PACKAGE_DESCRIPTION_SUMMARY` (this is always set
+ by CPack itself, if nothing else sets it explicitly).
+ - :variable:`PROJECT_DESCRIPTION` (this can be set with the DESCRIPTION
+ parameter for :command:`project`).
+
+.. variable:: CPACK_FREEBSD_PACKAGE_DESCRIPTION
+
+ Sets the package description. This is the long description of the package,
+ given by "pkg info" with a specific package as argument.
+
+ * Mandatory: YES
+ * Default:
+
+ - :variable:`CPACK_DEBIAN_PACKAGE_DESCRIPTION` (this may be set already
+ for Debian packaging, so we may as well re-use it).
+
+.. variable:: CPACK_FREEBSD_PACKAGE_WWW
+
+ The URL of the web site for this package, preferably (when applicable) the
+ site from which the original source can be obtained and any additional
+ upstream documentation or information may be found.
+
+ * Mandatory: YES
+ * Default:
+
+ - :variable:`CPACK_DEBIAN_PACKAGE_HOMEPAGE` (this may be set already
+ for Debian packaging, so we may as well re-use it).
+
+.. variable:: CPACK_FREEBSD_PACKAGE_LICENSE
+
+ The license, or licenses, which apply to this software package. This must
+ be one or more license-identifiers that pkg recognizes as acceptable license
+ identifiers (e.g. "GPLv2").
+
+ * Mandatory: YES
+ * Default:
+
+ - :variable:`CPACK_RPM_PACKAGE_LICENSE`
+
+.. variable:: CPACK_FREEBSD_PACKAGE_LICENSE_LOGIC
+
+ This variable is only of importance if there is more than one license.
+ The default is "single", which is only applicable to a single license.
+ Other acceptable values are determined by pkg -- those are "dual" or "multi" --
+ meaning choice (OR) or simultaneous (AND) application of the licenses.
+
+ * Mandatory: NO
+ * Default: single
+
+.. variable:: CPACK_FREEBSD_PACKAGE_MAINTAINER
+
+ The FreeBSD maintainer (e.g. kde@freebsd.org) of this package.
+
+ * Mandatory: YES
+ * Default: none
+
+.. variable:: CPACK_FREEBSD_PACKAGE_ORIGIN
+
+ The origin (ports label) of this package; for packages built by CPack
+ outside of the ports system this is of less importance. The default
+ puts the package somewhere under misc/, as a stopgap.
+
+ * Mandatory: YES
+ * Default: misc/<package name>
+
+.. variable:: CPACK_FREEBSD_PACKAGE_CATEGORIES
+
+ The ports categories where this package lives (if it were to be built
+ from ports). If none is set a single category is determined based on
+ the package origin.
+
+ * Mandatory: YES
+ * Default: derived from ORIGIN
+
+.. variable:: CPACK_FREEBSD_PACKAGE_DEPS
+
+ A list of package origins that should be added as package dependencies.
+ These are in the form <category>/<packagename>, e.g. x11/libkonq.
+ No version information needs to be provided (this is not included
+ in the manifest).
+
+ * Mandatory: NO
+ * Default: empty
+#]=======================================================================]
+
+
+
+if(CMAKE_BINARY_DIR)
+ message(FATAL_ERROR "CPackFreeBSD.cmake may only be used by CPack internally.")
+endif()
+
+if(NOT UNIX)
+ message(FATAL_ERROR "CPackFreeBSD.cmake may only be used under UNIX.")
+endif()
+
+
+###
+#
+# These bits are copied from the Debian packaging file; slightly modified.
+# They are used for filling in FreeBSD-packaging variables that can take
+# on values from elsewhere -- e.g. the package description may as well be
+# copied from Debian.
+#
+function(_cpack_freebsd_fallback_var OUTPUT_VAR_NAME)
+ set(FALLBACK_VAR_NAMES ${ARGN})
+
+ set(VALUE "${${OUTPUT_VAR_NAME}}")
+ if(VALUE)
+ return()
+ endif()
+
+ foreach(variable_name IN LISTS FALLBACK_VAR_NAMES)
+ if(${variable_name})
+ set(${OUTPUT_VAR_NAME} "${${variable_name}}" PARENT_SCOPE)
+ set(VALUE "${${variable_name}}")
+ break()
+ endif()
+ endforeach()
+ if(NOT VALUE)
+ message(WARNING "Variable ${OUTPUT_VAR_NAME} could not be given a fallback value from any variable ${FALLBACK_VAR_NAMES}.")
+ endif()
+endfunction()
+
+function(check_required_var VAR_NAME)
+ if(NOT ${VAR_NAME})
+ message(FATAL_ERROR "Variable ${VAR_NAME} is not set.")
+ endif()
+endfunction()
+
+set(_cpack_freebsd_fallback_origin "misc/bogus")
+
+_cpack_freebsd_fallback_var("CPACK_FREEBSD_PACKAGE_NAME"
+ "CPACK_PACKAGE_NAME"
+ "CMAKE_PROJECT_NAME"
+ )
+
+set(_cpack_freebsd_fallback_www "http://example.com/?pkg=${CPACK_FREEBSD_PACKAGE_NAME}")
+
+_cpack_freebsd_fallback_var("CPACK_FREEBSD_PACKAGE_COMMENT"
+ "CPACK_PACKAGE_DESCRIPTION_SUMMARY"
+ )
+
+# TODO: maybe read the PACKAGE_DESCRIPTION file for the longer
+# FreeBSD pkg-descr?
+_cpack_freebsd_fallback_var("CPACK_FREEBSD_PACKAGE_DESCRIPTION"
+ "CPACK_DEBIAN_PACKAGE_DESCRIPTION"
+ "CPACK_PACKAGE_DESCRIPTION_SUMMARY"
+ "PACKAGE_DESCRIPTION"
+ )
+
+# There's really only one homepage for a project, so
+# re-use the Debian setting if it's there.
+_cpack_freebsd_fallback_var("CPACK_FREEBSD_PACKAGE_WWW"
+ "CPACK_DEBIAN_PACKAGE_HOMEPAGE"
+ "_cpack_freebsd_fallback_www"
+ )
+
+_cpack_freebsd_fallback_var("CPACK_FREEBSD_PACKAGE_VERSION"
+ "CMAKE_PROJECT_VERSION"
+ "${CMAKE_PROJECT_NAME}_VERSION"
+ "PROJECT_VERSION"
+ "CPACK_PACKAGE_VERSION"
+ "CPACK_PACKAGE_VERSION"
+ )
+
+_cpack_freebsd_fallback_var("CPACK_FREEBSD_PACKAGE_MAINTAINER"
+ "CPACK_PACKAGE_CONTACT"
+ )
+
+_cpack_freebsd_fallback_var("CPACK_FREEBSD_PACKAGE_LICENSE"
+ "CPACK_RPM_PACKAGE_LICENSE"
+ )
+
+_cpack_freebsd_fallback_var("CPACK_FREEBSD_PACKAGE_ORIGIN"
+ "_cpack_freebsd_fallback_origin"
+ )
+
+if(NOT CPACK_FREEBSD_PACKAGE_CATEGORIES)
+ string(REGEX REPLACE "/.*" "" CPACK_FREEBSD_PACKAGE_CATEGORIES ${CPACK_FREEBSD_PACKAGE_ORIGIN})
+endif()
+
+check_required_var("CPACK_FREEBSD_PACKAGE_NAME")
+check_required_var("CPACK_FREEBSD_PACKAGE_ORIGIN")
+check_required_var("CPACK_FREEBSD_PACKAGE_VERSION")
+check_required_var("CPACK_FREEBSD_PACKAGE_MAINTAINER")
+check_required_var("CPACK_FREEBSD_PACKAGE_COMMENT")
+check_required_var("CPACK_FREEBSD_PACKAGE_DESCRIPTION")
+check_required_var("CPACK_FREEBSD_PACKAGE_WWW")
+check_required_var("CPACK_FREEBSD_PACKAGE_LICENSE")
diff --git a/Modules/CPackIFW.cmake b/Modules/CPackIFW.cmake
index c1cb52f16..8d8b07072 100644
--- a/Modules/CPackIFW.cmake
+++ b/Modules/CPackIFW.cmake
@@ -221,6 +221,19 @@
# You can use :command:`cpack_ifw_add_package_resources` command to resolve
# relative paths.
#
+# .. variable:: CPACK_IFW_PACKAGE_FILE_EXTENSION
+#
+# The target binary extension.
+#
+# On Linux, the name of the target binary is automatically extended with
+# '.run', if you do not specify the extension.
+#
+# On Windows, the target is created as an application with the extension
+# '.exe', which is automatically added, if not supplied.
+#
+# On Mac, the target is created as an DMG disk image with the extension
+# '.dmg', which is automatically added, if not supplied.
+#
# .. variable:: CPACK_IFW_REPOSITORIES_ALL
#
# The list of remote repositories.
@@ -247,6 +260,12 @@
# Additional prepared packages dirs that will be used to resolve
# dependent components.
#
+# .. variable:: CPACK_IFW_REPOSITORIES_DIRECTORIES
+#
+# Additional prepared repository dirs that will be used to resolve and
+# repack dependent components. This feature available only
+# since QtIFW_ 3.1.
+#
# Tools
# """""
#
@@ -304,7 +323,9 @@
# [LICENSES <display_name> <file_path> ...]
# [DEFAULT <value>]
# [USER_INTERFACES <file_path> <file_path> ...]
-# [TRANSLATIONS <file_path> <file_path> ...])
+# [TRANSLATIONS <file_path> <file_path> ...]
+# [REPLACES <comp_id> ...]
+# [CHECKABLE <value>])
#
# This command should be called after :command:`cpack_add_component` command.
#
@@ -385,6 +406,15 @@
# ``TRANSLATIONS``
# is a list of <file_path> ('.qm' files) representing translations to load.
#
+# ``REPLACES``
+# list of identifiers of component or component group to replace.
+#
+# ``CHECKABLE``
+# Possible values are: TRUE, FALSE.
+# Set to FALSE if you want to hide the checkbox for an item.
+# This is useful when only a few subcomponents should be selected
+# instead of all.
+#
#
# .. command:: cpack_ifw_configure_component_group
#
@@ -407,7 +437,9 @@
# [LICENSES <display_name> <file_path> ...]
# [DEFAULT <value>]
# [USER_INTERFACES <file_path> <file_path> ...]
-# [TRANSLATIONS <file_path> <file_path> ...])
+# [TRANSLATIONS <file_path> <file_path> ...]
+# [REPLACES <comp_id> ...]
+# [CHECKABLE <value>])
#
# This command should be called after :command:`cpack_add_component_group`
# command.
@@ -480,6 +512,15 @@
# ``TRANSLATIONS``
# is a list of <file_path> ('.qm' files) representing translations to load.
#
+# ``REPLACES``
+# list of identifiers of component or component group to replace.
+#
+# ``CHECKABLE``
+# Possible values are: TRUE, FALSE.
+# Set to FALSE if you want to hide the checkbox for an item.
+# This is useful when only a few subcomponents should be selected
+# instead of all.
+#
#
# .. command:: cpack_ifw_add_repository
#
@@ -863,8 +904,8 @@ macro(cpack_ifw_configure_component compname)
string(TOUPPER ${compname} _CPACK_IFWCOMP_UNAME)
set(_IFW_OPT COMMON ESSENTIAL VIRTUAL FORCED_INSTALLATION REQUIRES_ADMIN_RIGHTS)
- set(_IFW_ARGS NAME VERSION RELEASE_DATE SCRIPT PRIORITY SORTING_PRIORITY UPDATE_TEXT DEFAULT)
- set(_IFW_MULTI_ARGS DISPLAY_NAME DESCRIPTION DEPENDS DEPENDENCIES AUTO_DEPEND_ON LICENSES USER_INTERFACES TRANSLATIONS)
+ set(_IFW_ARGS NAME VERSION RELEASE_DATE SCRIPT PRIORITY SORTING_PRIORITY UPDATE_TEXT DEFAULT CHECKABLE)
+ set(_IFW_MULTI_ARGS DISPLAY_NAME DESCRIPTION DEPENDS DEPENDENCIES AUTO_DEPEND_ON LICENSES USER_INTERFACES TRANSLATIONS REPLACES)
cmake_parse_arguments(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME} "${_IFW_OPT}" "${_IFW_ARGS}" "${_IFW_MULTI_ARGS}" ${ARGN})
_cpack_ifw_resolve_script(CPACK_IFW_COMPONENT_${_CPACK_IFWCOMP_UNAME}_SCRIPT)
@@ -904,8 +945,8 @@ macro(cpack_ifw_configure_component_group grpname)
string(TOUPPER ${grpname} _CPACK_IFWGRP_UNAME)
set(_IFW_OPT VIRTUAL FORCED_INSTALLATION REQUIRES_ADMIN_RIGHTS)
- set(_IFW_ARGS NAME VERSION RELEASE_DATE SCRIPT PRIORITY SORTING_PRIORITY UPDATE_TEXT DEFAULT)
- set(_IFW_MULTI_ARGS DISPLAY_NAME DESCRIPTION DEPENDS DEPENDENCIES AUTO_DEPEND_ON LICENSES USER_INTERFACES TRANSLATIONS)
+ set(_IFW_ARGS NAME VERSION RELEASE_DATE SCRIPT PRIORITY SORTING_PRIORITY UPDATE_TEXT DEFAULT CHECKABLE)
+ set(_IFW_MULTI_ARGS DISPLAY_NAME DESCRIPTION DEPENDS DEPENDENCIES AUTO_DEPEND_ON LICENSES USER_INTERFACES TRANSLATIONS REPLACES)
cmake_parse_arguments(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME} "${_IFW_OPT}" "${_IFW_ARGS}" "${_IFW_MULTI_ARGS}" ${ARGN})
_cpack_ifw_resolve_script(CPACK_IFW_COMPONENT_GROUP_${_CPACK_IFWGRP_UNAME}_SCRIPT)
diff --git a/Modules/CPackRPM.cmake b/Modules/CPackRPM.cmake
index fa2a6e409..9f77ec3c7 100644
--- a/Modules/CPackRPM.cmake
+++ b/Modules/CPackRPM.cmake
@@ -106,6 +106,16 @@
# group rpm package is generated without component suffix in filename and
# package name.
#
+# .. variable:: CPACK_RPM_PACKAGE_EPOCH
+#
+# The RPM package epoch
+#
+# * Mandatory : No
+# * Default : -
+#
+# Optional number that should be incremented when changing versioning schemas
+# or fixing mistakes in the version numbers of older packages.
+#
# .. variable:: CPACK_RPM_PACKAGE_VERSION
#
# The RPM package version.
@@ -530,7 +540,9 @@
# list of path to be excluded.
#
# * Mandatory : NO
-# * Default : /etc /etc/init.d /usr /usr/share /usr/share/doc /usr/bin /usr/lib /usr/lib64 /usr/include
+# * Default : /etc /etc/init.d /usr /usr/bin /usr/include /usr/lib
+# /usr/libx32 /usr/lib64 /usr/share /usr/share/aclocal
+# /usr/share/doc
#
# May be used to exclude path (directories or files) from the auto-generated
# list of paths discovered by CPack RPM. The defaut value contains a
@@ -1083,7 +1095,9 @@ function(cpack_rpm_prepare_content_list)
endif()
if(NOT DEFINED CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST)
- set(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST /etc /etc/init.d /usr /usr/share /usr/share/doc /usr/bin /usr/lib /usr/lib64 /usr/libx32 /usr/include)
+ set(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST /etc /etc/init.d /usr /usr/bin
+ /usr/include /usr/lib /usr/libx32 /usr/lib64
+ /usr/share /usr/share/aclocal /usr/share/doc )
if(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION)
if(CPACK_RPM_PACKAGE_DEBUG)
message("CPackRPM:Debug: Adding ${CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION} to builtin omit list.")
@@ -1891,11 +1905,16 @@ function(cpack_rpm_generate_package)
OUTPUT_STRIP_TRAILING_WHITESPACE)
string(REPLACE "\n" ";" RPMBUILD_TAG_LIST "${RPMBUILD_TAG_LIST}")
+ if(CPACK_RPM_PACKAGE_EPOCH)
+ set(TMP_RPM_EPOCH "Epoch: ${CPACK_RPM_PACKAGE_EPOCH}")
+ endif()
+
# Check if additional fields for RPM spec header are given
# There may be some COMPONENT specific variables as well
# If component specific var is not provided we use the global one
# for each component
foreach(_RPM_SPEC_HEADER URL REQUIRES SUGGESTS PROVIDES OBSOLETES PREFIX CONFLICTS AUTOPROV AUTOREQ AUTOREQPROV REQUIRES_PRE REQUIRES_POST REQUIRES_PREUN REQUIRES_POSTUN)
+
if(CPACK_RPM_PACKAGE_DEBUG)
message("CPackRPM:Debug: processing ${_RPM_SPEC_HEADER}")
endif()
@@ -2422,7 +2441,11 @@ mv *.rpm %_rpmdir"
set(RPMBUILD_FLAGS "-bs")
file(WRITE ${CPACK_RPM_BINARY_SPECFILE}.in
- "# -*- rpm-spec -*-
+ "# Restore old style debuginfo creation for rpm >= 4.14.
+%undefine _debugsource_packages
+%undefine _debuginfo_subpackages
+
+# -*- rpm-spec -*-
BuildRoot: %_topdir/\@CPACK_PACKAGE_FILE_NAME\@
Summary: \@CPACK_RPM_PACKAGE_SUMMARY\@
Name: \@CPACK_RPM_PACKAGE_NAME\@
@@ -2497,6 +2520,7 @@ Vendor: \@CPACK_RPM_PACKAGE_VENDOR\@
\@TMP_RPM_AUTOREQPROV\@
\@TMP_RPM_BUILDARCH\@
\@TMP_RPM_PREFIXES\@
+\@TMP_RPM_EPOCH\@
%description -n \@CPACK_RPM_PACKAGE_NAME\@
\@CPACK_RPM_PACKAGE_DESCRIPTION\@
@@ -2527,7 +2551,11 @@ Vendor: \@CPACK_RPM_PACKAGE_VENDOR\@
if(CPACK_RPM_GENERATE_USER_BINARY_SPECFILE_TEMPLATE OR NOT CPACK_RPM_USER_BINARY_SPECFILE)
file(WRITE ${CPACK_RPM_BINARY_SPECFILE}.in
- "# -*- rpm-spec -*-
+ "# Restore old style debuginfo creation for rpm >= 4.14.
+%undefine _debugsource_packages
+%undefine _debuginfo_subpackages
+
+# -*- rpm-spec -*-
BuildRoot: %_topdir/\@CPACK_PACKAGE_FILE_NAME\@\@CPACK_RPM_PACKAGE_COMPONENT_PART_PATH\@
Summary: \@CPACK_RPM_PACKAGE_SUMMARY\@
Name: \@CPACK_RPM_PACKAGE_NAME\@
@@ -2552,6 +2580,7 @@ Vendor: \@CPACK_RPM_PACKAGE_VENDOR\@
\@TMP_RPM_AUTOREQPROV\@
\@TMP_RPM_BUILDARCH\@
\@TMP_RPM_PREFIXES\@
+\@TMP_RPM_EPOCH\@
\@TMP_RPM_DEBUGINFO\@
diff --git a/Modules/CheckCCompilerFlag.cmake b/Modules/CheckCCompilerFlag.cmake
index 1ba67fca3..5a7298b81 100644
--- a/Modules/CheckCCompilerFlag.cmake
+++ b/Modules/CheckCCompilerFlag.cmake
@@ -1,26 +1,36 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
-#.rst:
-# CheckCCompilerFlag
-# ------------------
-#
-# Check whether the C compiler supports a given flag.
-#
-# CHECK_C_COMPILER_FLAG(<flag> <var>)
-#
-# ::
-#
-# <flag> - the compiler flag
-# <var> - variable to store the result
-# Will be created as an internal cache variable.
-#
-# This internally calls the check_c_source_compiles macro and sets
-# CMAKE_REQUIRED_DEFINITIONS to <flag>. See help for
-# CheckCSourceCompiles for a listing of variables that can otherwise
-# modify the build. The result only tells that the compiler does not
-# give an error message when it encounters the flag. If the flag has
-# any effect or even a specific one is beyond the scope of this module.
+#[=======================================================================[.rst:
+CheckCCompilerFlag
+------------------
+
+Check whether the C compiler supports a given flag.
+
+.. command:: check_c_compiler_flag
+
+ ::
+
+ check_c_compiler_flag(<flag> <var>)
+
+ Check that the ``<flag>`` is accepted by the compiler without
+ a diagnostic. Stores the result in an internal cache entry
+ named ``<var>``.
+
+This command temporarily sets the ``CMAKE_REQUIRED_DEFINITIONS`` variable
+and calls the ``check_c_source_compiles`` macro from the
+:module:`CheckCSourceCompiles` module. See documentation of that
+module for a listing of variables that can otherwise modify the build.
+
+A positive result from this check indicates only that the compiler did not
+issue a diagnostic message when given the flag. Whether the flag has any
+effect or even a specific one is beyond the scope of this module.
+
+.. note::
+ Since the :command:`try_compile` command forwards flags from variables
+ like :variable:`CMAKE_C_FLAGS <CMAKE_<LANG>_FLAGS>`, unknown flags
+ in such variables may cause a false negative for this check.
+#]=======================================================================]
include(CheckCSourceCompiles)
include(CMakeCheckCompilerFlagCommonPatterns)
diff --git a/Modules/CheckCSourceCompiles.cmake b/Modules/CheckCSourceCompiles.cmake
index ac2c6c583..56e68d5b1 100644
--- a/Modules/CheckCSourceCompiles.cmake
+++ b/Modules/CheckCSourceCompiles.cmake
@@ -1,31 +1,65 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
-#.rst:
-# CheckCSourceCompiles
-# --------------------
-#
-# Check if given C source compiles and links into an executable
-#
-# CHECK_C_SOURCE_COMPILES(<code> <var> [FAIL_REGEX <fail-regex>])
-#
-# ::
-#
-# <code> - source code to try to compile, must define 'main'
-# <var> - variable to store whether the source code compiled
-# Will be created as an internal cache variable.
-# <fail-regex> - fail if test output matches this regex
-#
-# The following variables may be set before calling this macro to modify
-# the way the check is run:
-#
-# ::
-#
-# CMAKE_REQUIRED_FLAGS = string of compile command line flags
-# CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
-# CMAKE_REQUIRED_INCLUDES = list of include directories
-# CMAKE_REQUIRED_LIBRARIES = list of libraries to link
-# CMAKE_REQUIRED_QUIET = execute quietly without messages
+#[=======================================================================[.rst:
+CheckCSourceCompiles
+--------------------
+
+Check if given C source compiles and links into an executable.
+
+.. command:: check_c_source_compiles
+
+ ::
+
+ check_c_source_compiles(code resultVar [FAIL_REGEX regex1 [regex2...]])
+
+ Check that the source supplied in ``code`` can be compiled as a C source
+ file and linked as an executable (so it must contain at least a ``main()``
+ function). The result will be stored in the internal cache variable specified
+ by ``resultVar``, with a boolean true value for success and boolean false for
+ failure. If ``FAIL_REGEX`` is provided, then failure is determined by
+ checking if anything in the output matches any of the specified regular
+ expressions.
+
+ The underlying check is performed by the :command:`try_compile` command. The
+ compile and link commands can be influenced by setting any of the following
+ variables prior to calling ``check_c_source_compiles()``:
+
+ ``CMAKE_REQUIRED_FLAGS``
+ Additional flags to pass to the compiler. Note that the contents of
+ :variable:`CMAKE_C_FLAGS <CMAKE_<LANG>_FLAGS>` and its associated
+ configuration-specific variable are automatically added to the compiler
+ command before the contents of ``CMAKE_REQUIRED_FLAGS``.
+
+ ``CMAKE_REQUIRED_DEFINITIONS``
+ A :ref:`;-list <CMake Language Lists>` of compiler definitions of the form
+ ``-DFOO`` or ``-DFOO=bar``. A definition for the name specified by
+ ``resultVar`` will also be added automatically.
+
+ ``CMAKE_REQUIRED_INCLUDES``
+ A :ref:`;-list <CMake Language Lists>` of header search paths to pass to
+ the compiler. These will be the only header search paths used by
+ ``try_compile()``, i.e. the contents of the :prop_dir:`INCLUDE_DIRECTORIES`
+ directory property will be ignored.
+
+ ``CMAKE_REQUIRED_LIBRARIES``
+ A :ref:`;-list <CMake Language Lists>` of libraries to add to the link
+ command. These can be the name of system libraries or they can be
+ :ref:`Imported Targets <Imported Targets>` (see :command:`try_compile` for
+ further details).
+
+ ``CMAKE_REQUIRED_QUIET``
+ If this variable evaluates to a boolean true value, all status messages
+ associated with the check will be suppressed.
+
+ The check is only performed once, with the result cached in the variable
+ named by ``resultVar``. Every subsequent CMake run will re-use this cached
+ value rather than performing the check again, even if the ``code`` changes.
+ In order to force the check to be re-evaluated, the variable named by
+ ``resultVar`` must be manually removed from the cache.
+
+#]=======================================================================]
+
macro(CHECK_C_SOURCE_COMPILES SOURCE VAR)
if(NOT DEFINED "${VAR}")
diff --git a/Modules/CheckCSourceRuns.cmake b/Modules/CheckCSourceRuns.cmake
index 70aa9fd2d..8da9f1ea9 100644
--- a/Modules/CheckCSourceRuns.cmake
+++ b/Modules/CheckCSourceRuns.cmake
@@ -1,31 +1,64 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
-#.rst:
-# CheckCSourceRuns
-# ----------------
-#
-# Check if the given C source code compiles and runs.
-#
-# CHECK_C_SOURCE_RUNS(<code> <var>)
-#
-# ::
-#
-# <code> - source code to try to compile
-# <var> - variable to store the result
-# (1 for success, empty for failure)
-# Will be created as an internal cache variable.
-#
-# The following variables may be set before calling this macro to modify
-# the way the check is run:
-#
-# ::
-#
-# CMAKE_REQUIRED_FLAGS = string of compile command line flags
-# CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
-# CMAKE_REQUIRED_INCLUDES = list of include directories
-# CMAKE_REQUIRED_LIBRARIES = list of libraries to link
-# CMAKE_REQUIRED_QUIET = execute quietly without messages
+#[=======================================================================[.rst:
+CheckCSourceRuns
+----------------
+
+Check if given C source compiles and links into an executable and can
+subsequently be run.
+
+.. command:: check_c_source_runs
+
+ ::
+
+ check_c_source_runs(code resultVar)
+
+ Check that the source supplied in ``code`` can be compiled as a C source
+ file, linked as an executable and then run. The ``code`` must contain at
+ least a ``main()`` function. If the code could be built and run successfully,
+ the internal cache variable specified by ``resultVar`` will be set to 1,
+ otherwise it will be set to an value that evaluates to boolean false (e.g.
+ an empty string or an error message).
+
+ The underlying check is performed by the :command:`try_run` command. The
+ compile and link commands can be influenced by setting any of the following
+ variables prior to calling ``check_c_source_runs()``:
+
+ ``CMAKE_REQUIRED_FLAGS``
+ Additional flags to pass to the compiler. Note that the contents of
+ :variable:`CMAKE_C_FLAGS <CMAKE_<LANG>_FLAGS>` and its associated
+ configuration-specific variable are automatically added to the compiler
+ command before the contents of ``CMAKE_REQUIRED_FLAGS``.
+
+ ``CMAKE_REQUIRED_DEFINITIONS``
+ A :ref:`;-list <CMake Language Lists>` of compiler definitions of the form
+ ``-DFOO`` or ``-DFOO=bar``. A definition for the name specified by
+ ``resultVar`` will also be added automatically.
+
+ ``CMAKE_REQUIRED_INCLUDES``
+ A :ref:`;-list <CMake Language Lists>` of header search paths to pass to
+ the compiler. These will be the only header search paths used by
+ ``try_run()``, i.e. the contents of the :prop_dir:`INCLUDE_DIRECTORIES`
+ directory property will be ignored.
+
+ ``CMAKE_REQUIRED_LIBRARIES``
+ A :ref:`;-list <CMake Language Lists>` of libraries to add to the link
+ command. These can be the name of system libraries or they can be
+ :ref:`Imported Targets <Imported Targets>` (see :command:`try_run` for
+ further details).
+
+ ``CMAKE_REQUIRED_QUIET``
+ If this variable evaluates to a boolean true value, all status messages
+ associated with the check will be suppressed.
+
+ The check is only performed once, with the result cached in the variable
+ named by ``resultVar``. Every subsequent CMake run will re-use this cached
+ value rather than performing the check again, even if the ``code`` changes.
+ In order to force the check to be re-evaluated, the variable named by
+ ``resultVar`` must be manually removed from the cache.
+
+#]=======================================================================]
macro(CHECK_C_SOURCE_RUNS SOURCE VAR)
if(NOT DEFINED "${VAR}")
diff --git a/Modules/CheckCXXCompilerFlag.cmake b/Modules/CheckCXXCompilerFlag.cmake
index afbb23128..f731b7048 100644
--- a/Modules/CheckCXXCompilerFlag.cmake
+++ b/Modules/CheckCXXCompilerFlag.cmake
@@ -1,25 +1,36 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
-#.rst:
-# CheckCXXCompilerFlag
-# --------------------
-#
-# Check whether the CXX compiler supports a given flag.
-#
-# CHECK_CXX_COMPILER_FLAG(<flag> <var>)
-#
-# ::
-#
-# <flag> - the compiler flag
-# <var> - variable to store the result
-#
-# This internally calls the check_cxx_source_compiles macro and sets
-# CMAKE_REQUIRED_DEFINITIONS to <flag>. See help for
-# CheckCXXSourceCompiles for a listing of variables that can otherwise
-# modify the build. The result only tells that the compiler does not
-# give an error message when it encounters the flag. If the flag has
-# any effect or even a specific one is beyond the scope of this module.
+#[=======================================================================[.rst:
+CheckCXXCompilerFlag
+------------------------
+
+Check whether the CXX compiler supports a given flag.
+
+.. command:: check_cxx_compiler_flag
+
+ ::
+
+ check_cxx_compiler_flag(<flag> <var>)
+
+ Check that the ``<flag>`` is accepted by the compiler without
+ a diagnostic. Stores the result in an internal cache entry
+ named ``<var>``.
+
+This command temporarily sets the ``CMAKE_REQUIRED_DEFINITIONS`` variable
+and calls the ``check_cxx_source_compiles`` macro from the
+:module:`CheckCXXSourceCompiles` module. See documentation of that
+module for a listing of variables that can otherwise modify the build.
+
+A positive result from this check indicates only that the compiler did not
+issue a diagnostic message when given the flag. Whether the flag has any
+effect or even a specific one is beyond the scope of this module.
+
+.. note::
+ Since the :command:`try_compile` command forwards flags from variables
+ like :variable:`CMAKE_CXX_FLAGS <CMAKE_<LANG>_FLAGS>`, unknown flags
+ in such variables may cause a false negative for this check.
+#]=======================================================================]
include(CheckCXXSourceCompiles)
include(CMakeCheckCompilerFlagCommonPatterns)
diff --git a/Modules/CheckCXXSourceCompiles.cmake b/Modules/CheckCXXSourceCompiles.cmake
index e54d09e61..4634a7bd9 100644
--- a/Modules/CheckCXXSourceCompiles.cmake
+++ b/Modules/CheckCXXSourceCompiles.cmake
@@ -1,31 +1,64 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
-#.rst:
-# CheckCXXSourceCompiles
-# ----------------------
-#
-# Check if given C++ source compiles and links into an executable
-#
-# CHECK_CXX_SOURCE_COMPILES(<code> <var> [FAIL_REGEX <fail-regex>])
-#
-# ::
-#
-# <code> - source code to try to compile, must define 'main'
-# <var> - variable to store whether the source code compiled
-# Will be created as an internal cache variable.
-# <fail-regex> - fail if test output matches this regex
-#
-# The following variables may be set before calling this macro to modify
-# the way the check is run:
-#
-# ::
-#
-# CMAKE_REQUIRED_FLAGS = string of compile command line flags
-# CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
-# CMAKE_REQUIRED_INCLUDES = list of include directories
-# CMAKE_REQUIRED_LIBRARIES = list of libraries to link
-# CMAKE_REQUIRED_QUIET = execute quietly without messages
+#[=======================================================================[.rst:
+CheckCXXSourceCompiles
+----------------------
+
+Check if given C++ source compiles and links into an executable.
+
+.. command:: check_cxx_source_compiles
+
+ ::
+
+ check_cxx_source_compiles(code resultVar [FAIL_REGEX regex1 [regex2...]])
+
+ Check that the source supplied in ``code`` can be compiled as a C++ source
+ file and linked as an executable (so it must contain at least a ``main()``
+ function). The result will be stored in the internal cache variable specified
+ by ``resultVar``, with a boolean true value for success and boolean false for
+ failure. If ``FAIL_REGEX`` is provided, then failure is determined by
+ checking if anything in the output matches any of the specified regular
+ expressions.
+
+ The underlying check is performed by the :command:`try_compile` command. The
+ compile and link commands can be influenced by setting any of the following
+ variables prior to calling ``check_cxx_source_compiles()``:
+
+ ``CMAKE_REQUIRED_FLAGS``
+ Additional flags to pass to the compiler. Note that the contents of
+ :variable:`CMAKE_CXX_FLAGS <CMAKE_<LANG>_FLAGS>` and its associated
+ configuration-specific variable are automatically added to the compiler
+ command before the contents of ``CMAKE_REQUIRED_FLAGS``.
+
+ ``CMAKE_REQUIRED_DEFINITIONS``
+ A :ref:`;-list <CMake Language Lists>` of compiler definitions of the form
+ ``-DFOO`` or ``-DFOO=bar``. A definition for the name specified by
+ ``resultVar`` will also be added automatically.
+
+ ``CMAKE_REQUIRED_INCLUDES``
+ A :ref:`;-list <CMake Language Lists>` of header search paths to pass to
+ the compiler. These will be the only header search paths used by
+ ``try_compile()``, i.e. the contents of the :prop_dir:`INCLUDE_DIRECTORIES`
+ directory property will be ignored.
+
+ ``CMAKE_REQUIRED_LIBRARIES``
+ A :ref:`;-list <CMake Language Lists>` of libraries to add to the link
+ command. These can be the name of system libraries or they can be
+ :ref:`Imported Targets <Imported Targets>` (see :command:`try_compile` for
+ further details).
+
+ ``CMAKE_REQUIRED_QUIET``
+ If this variable evaluates to a boolean true value, all status messages
+ associated with the check will be suppressed.
+
+ The check is only performed once, with the result cached in the variable
+ named by ``resultVar``. Every subsequent CMake run will re-use this cached
+ value rather than performing the check again, even if the ``code`` changes.
+ In order to force the check to be re-evaluated, the variable named by
+ ``resultVar`` must be manually removed from the cache.
+
+#]=======================================================================]
macro(CHECK_CXX_SOURCE_COMPILES SOURCE VAR)
if(NOT DEFINED "${VAR}")
diff --git a/Modules/CheckCXXSourceRuns.cmake b/Modules/CheckCXXSourceRuns.cmake
index e08365950..558708c8f 100644
--- a/Modules/CheckCXXSourceRuns.cmake
+++ b/Modules/CheckCXXSourceRuns.cmake
@@ -1,31 +1,64 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
-#.rst:
-# CheckCXXSourceRuns
-# ------------------
-#
-# Check if the given C++ source code compiles and runs.
-#
-# CHECK_CXX_SOURCE_RUNS(<code> <var>)
-#
-# ::
-#
-# <code> - source code to try to compile
-# <var> - variable to store the result
-# (1 for success, empty for failure)
-# Will be created as an internal cache variable.
-#
-# The following variables may be set before calling this macro to modify
-# the way the check is run:
-#
-# ::
-#
-# CMAKE_REQUIRED_FLAGS = string of compile command line flags
-# CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
-# CMAKE_REQUIRED_INCLUDES = list of include directories
-# CMAKE_REQUIRED_LIBRARIES = list of libraries to link
-# CMAKE_REQUIRED_QUIET = execute quietly without messages
+#[=======================================================================[.rst:
+CheckCXXSourceRuns
+------------------
+
+Check if given C++ source compiles and links into an executable and can
+subsequently be run.
+
+.. command:: check_cxx_source_runs
+
+ ::
+
+ check_cxx_source_runs(code resultVar)
+
+ Check that the source supplied in ``code`` can be compiled as a C++ source
+ file, linked as an executable and then run. The ``code`` must contain at
+ least a ``main()`` function. If the code could be built and run successfully,
+ the internal cache variable specified by ``resultVar`` will be set to 1,
+ otherwise it will be set to an value that evaluates to boolean false (e.g.
+ an empty string or an error message).
+
+ The underlying check is performed by the :command:`try_run` command. The
+ compile and link commands can be influenced by setting any of the following
+ variables prior to calling ``check_cxx_source_runs()``:
+
+ ``CMAKE_REQUIRED_FLAGS``
+ Additional flags to pass to the compiler. Note that the contents of
+ :variable:`CMAKE_CXX_FLAGS <CMAKE_<LANG>_FLAGS>` and its associated
+ configuration-specific variable are automatically added to the compiler
+ command before the contents of ``CMAKE_REQUIRED_FLAGS``.
+
+ ``CMAKE_REQUIRED_DEFINITIONS``
+ A :ref:`;-list <CMake Language Lists>` of compiler definitions of the form
+ ``-DFOO`` or ``-DFOO=bar``. A definition for the name specified by
+ ``resultVar`` will also be added automatically.
+
+ ``CMAKE_REQUIRED_INCLUDES``
+ A :ref:`;-list <CMake Language Lists>` of header search paths to pass to
+ the compiler. These will be the only header search paths used by
+ ``try_run()``, i.e. the contents of the :prop_dir:`INCLUDE_DIRECTORIES`
+ directory property will be ignored.
+
+ ``CMAKE_REQUIRED_LIBRARIES``
+ A :ref:`;-list <CMake Language Lists>` of libraries to add to the link
+ command. These can be the name of system libraries or they can be
+ :ref:`Imported Targets <Imported Targets>` (see :command:`try_run` for
+ further details).
+
+ ``CMAKE_REQUIRED_QUIET``
+ If this variable evaluates to a boolean true value, all status messages
+ associated with the check will be suppressed.
+
+ The check is only performed once, with the result cached in the variable
+ named by ``resultVar``. Every subsequent CMake run will re-use this cached
+ value rather than performing the check again, even if the ``code`` changes.
+ In order to force the check to be re-evaluated, the variable named by
+ ``resultVar`` must be manually removed from the cache.
+
+#]=======================================================================]
macro(CHECK_CXX_SOURCE_RUNS SOURCE VAR)
if(NOT DEFINED "${VAR}")
diff --git a/Modules/CheckCXXSymbolExists.cmake b/Modules/CheckCXXSymbolExists.cmake
index 354eea3d2..855215407 100644
--- a/Modules/CheckCXXSymbolExists.cmake
+++ b/Modules/CheckCXXSymbolExists.cmake
@@ -35,5 +35,5 @@
include(CheckSymbolExists)
macro(CHECK_CXX_SYMBOL_EXISTS SYMBOL FILES VARIABLE)
- _CHECK_SYMBOL_EXISTS("${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckSymbolExists.cxx" "${SYMBOL}" "${FILES}" "${VARIABLE}" )
+ __CHECK_SYMBOL_EXISTS_IMPL("${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckSymbolExists.cxx" "${SYMBOL}" "${FILES}" "${VARIABLE}" )
endmacro()
diff --git a/Modules/CheckForPthreads.c b/Modules/CheckForPthreads.c
index 6fc6f2634..e70ceb1da 100644
--- a/Modules/CheckForPthreads.c
+++ b/Modules/CheckForPthreads.c
@@ -1,41 +1,15 @@
#include <pthread.h>
-#include <stdio.h>
-#include <unistd.h>
-void* runner(void*);
-
-int res = 0;
-#ifdef __CLASSIC_C__
-int main()
-{
- int ac;
- char* av[];
-#else
-int main(int ac, char* av[])
+void* start_routine(void* args)
{
-#endif
- pthread_t tid[2];
- pthread_create(&tid[0], 0, runner, (void*)1);
- pthread_create(&tid[1], 0, runner, (void*)2);
-
-#if defined(__BEOS__) && !defined(__ZETA__) /* (no usleep on BeOS 5.) */
- usleep(1); /* for strange behavior on single-processor sun */
-#endif
-
- pthread_join(tid[0], 0);
- pthread_join(tid[1], 0);
- if (ac > 1000) {
- return *av[0];
- }
- return res;
+ return args;
}
-void* runner(void* args)
+int main(void)
{
- int cc;
- for (cc = 0; cc < 10; cc++) {
- printf("%p CC: %d\n", args, cc);
- }
- res++;
+ /* This is a compile and link test, no code to actually run things. */
+ pthread_t thread;
+ pthread_create(&thread, 0, start_routine, 0);
+ pthread_join(thread, 0);
return 0;
}
diff --git a/Modules/CheckFortranCompilerFlag.cmake b/Modules/CheckFortranCompilerFlag.cmake
index 8519fccf7..8a1a8b9cd 100644
--- a/Modules/CheckFortranCompilerFlag.cmake
+++ b/Modules/CheckFortranCompilerFlag.cmake
@@ -1,27 +1,36 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
-#.rst:
-# CheckFortranCompilerFlag
-# ------------------------
-#
-# Check whether the Fortran compiler supports a given flag.
-#
-# CHECK_Fortran_COMPILER_FLAG(<flag> <var>)
-#
-# ::
-#
-# <flag> - the compiler flag
-# <var> - variable to store the result
-# Will be created as an internal cache variable.
-#
-# This internally calls the check_fortran_source_compiles macro and
-# sets CMAKE_REQUIRED_DEFINITIONS to <flag>. See help for
-# CheckFortranSourceCompiles for a listing of variables that can
-# otherwise modify the build. The result only tells that the compiler
-# does not give an error message when it encounters the flag. If the
-# flag has any effect or even a specific one is beyond the scope of
-# this module.
+#[=======================================================================[.rst:
+CheckFortranCompilerFlag
+------------------------
+
+Check whether the Fortran compiler supports a given flag.
+
+.. command:: check_fortran_compiler_flag
+
+ ::
+
+ check_fortran_compiler_flag(<flag> <var>)
+
+ Check that the ``<flag>`` is accepted by the compiler without
+ a diagnostic. Stores the result in an internal cache entry
+ named ``<var>``.
+
+This command temporarily sets the ``CMAKE_REQUIRED_DEFINITIONS`` variable
+and calls the ``check_fortran_source_compiles`` macro from the
+:module:`CheckFortranSourceCompiles` module. See documentation of that
+module for a listing of variables that can otherwise modify the build.
+
+A positive result from this check indicates only that the compiler did not
+issue a diagnostic message when given the flag. Whether the flag has any
+effect or even a specific one is beyond the scope of this module.
+
+.. note::
+ Since the :command:`try_compile` command forwards flags from variables
+ like :variable:`CMAKE_Fortran_FLAGS <CMAKE_<LANG>_FLAGS>`, unknown flags
+ in such variables may cause a false negative for this check.
+#]=======================================================================]
include(CheckFortranSourceCompiles)
include(CMakeCheckCompilerFlagCommonPatterns)
diff --git a/Modules/CheckFortranSourceCompiles.cmake b/Modules/CheckFortranSourceCompiles.cmake
index c42254cd9..4df17e352 100644
--- a/Modules/CheckFortranSourceCompiles.cmake
+++ b/Modules/CheckFortranSourceCompiles.cmake
@@ -1,35 +1,71 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
-#.rst:
-# CheckFortranSourceCompiles
-# --------------------------
-#
-# Check if given Fortran source compiles and links into an executable::
-#
-# CHECK_Fortran_SOURCE_COMPILES(<code> <var> [FAIL_REGEX <fail-regex>]
-# [SRC_EXT <ext>])
-#
-# The arguments are:
-#
-# ``<code>``
-# Source code to try to compile. It must define a PROGRAM entry point.
-# ``<var>``
-# Variable to store whether the source code compiled.
-# Will be created as an internal cache variable.
-# ``FAIL_REGEX <fail-regex>``
-# Fail if test output matches this regex.
-# ``SRC_EXT <ext>``
-# Use source extension ``.<ext>`` instead of the default ``.F``.
-#
-# The following variables may be set before calling this macro to modify
-# the way the check is run::
-#
-# CMAKE_REQUIRED_FLAGS = string of compile command line flags
-# CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
-# CMAKE_REQUIRED_INCLUDES = list of include directories
-# CMAKE_REQUIRED_LIBRARIES = list of libraries to link
-# CMAKE_REQUIRED_QUIET = execute quietly without messages
+#[=======================================================================[.rst:
+CheckFortranSourceCompiles
+--------------------------
+
+Check if given Fortran source compiles and links into an executable.
+
+.. command:: check_fortran_source_compiles
+
+ ::
+
+ check_fortran_source_compiles(code resultVar
+ [FAIL_REGEX regex1 [regex2...]]
+ [SRC_EXT ext]
+ )
+
+ Check that the source supplied in ``code`` can be compiled as a Fortran
+ source file and linked as an executable (so it must contain at least a
+ ``PROGRAM`` entry point). The result will be stored in the internal cache
+ variable specified by ``resultVar``, with a boolean true value for success
+ and boolean false for failure. If ``FAIL_REGEX`` is provided, then failure is
+ determined by checking if anything in the output matches any of the specified
+ regular expressions.
+
+ By default, the test source file will be given a ``.F`` file extension. The
+ ``SRC_EXT`` option can be used to override this with ``.ext`` instead.
+
+ The underlying check is performed by the :command:`try_compile` command. The
+ compile and link commands can be influenced by setting any of the following
+ variables prior to calling ``check_fortran_source_compiles()``:
+
+ ``CMAKE_REQUIRED_FLAGS``
+ Additional flags to pass to the compiler. Note that the contents of
+ :variable:`CMAKE_Fortran_FLAGS <CMAKE_<LANG>_FLAGS>` and its associated
+ configuration-specific variable are automatically added to the compiler
+ command before the contents of ``CMAKE_REQUIRED_FLAGS``.
+
+ ``CMAKE_REQUIRED_DEFINITIONS``
+ A :ref:`;-list <CMake Language Lists>` of compiler definitions of the form
+ ``-DFOO`` or ``-DFOO=bar``. A definition for the name specified by
+ ``resultVar`` will also be added automatically.
+
+ ``CMAKE_REQUIRED_INCLUDES``
+ A :ref:`;-list <CMake Language Lists>` of header search paths to pass to
+ the compiler. These will be the only header search paths used by
+ ``try_compile()``, i.e. the contents of the :prop_dir:`INCLUDE_DIRECTORIES`
+ directory property will be ignored.
+
+ ``CMAKE_REQUIRED_LIBRARIES``
+ A :ref:`;-list <CMake Language Lists>` of libraries to add to the link
+ command. These can be the name of system libraries or they can be
+ :ref:`Imported Targets <Imported Targets>` (see :command:`try_compile` for
+ further details).
+
+ ``CMAKE_REQUIRED_QUIET``
+ If this variable evaluates to a boolean true value, all status messages
+ associated with the check will be suppressed.
+
+ The check is only performed once, with the result cached in the variable
+ named by ``resultVar``. Every subsequent CMake run will re-use this cached
+ value rather than performing the check again, even if the ``code`` changes.
+ In order to force the check to be re-evaluated, the variable named by
+ ``resultVar`` must be manually removed from the cache.
+
+#]=======================================================================]
+
macro(CHECK_Fortran_SOURCE_COMPILES SOURCE VAR)
if(NOT DEFINED "${VAR}")
diff --git a/Modules/CheckSymbolExists.cmake b/Modules/CheckSymbolExists.cmake
index 6f1afcfda..6d52d56c9 100644
--- a/Modules/CheckSymbolExists.cmake
+++ b/Modules/CheckSymbolExists.cmake
@@ -45,15 +45,15 @@ the way the check is run:
macro(CHECK_SYMBOL_EXISTS SYMBOL FILES VARIABLE)
if(CMAKE_C_COMPILER_LOADED)
- _CHECK_SYMBOL_EXISTS("${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckSymbolExists.c" "${SYMBOL}" "${FILES}" "${VARIABLE}" )
+ __CHECK_SYMBOL_EXISTS_IMPL("${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckSymbolExists.c" "${SYMBOL}" "${FILES}" "${VARIABLE}" )
elseif(CMAKE_CXX_COMPILER_LOADED)
- _CHECK_SYMBOL_EXISTS("${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckSymbolExists.cxx" "${SYMBOL}" "${FILES}" "${VARIABLE}" )
+ __CHECK_SYMBOL_EXISTS_IMPL("${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckSymbolExists.cxx" "${SYMBOL}" "${FILES}" "${VARIABLE}" )
else()
message(FATAL_ERROR "CHECK_SYMBOL_EXISTS needs either C or CXX language enabled")
endif()
endmacro()
-macro(_CHECK_SYMBOL_EXISTS SOURCEFILE SYMBOL FILES VARIABLE)
+macro(__CHECK_SYMBOL_EXISTS_IMPL SOURCEFILE SYMBOL FILES VARIABLE)
if(NOT DEFINED "${VARIABLE}" OR "x${${VARIABLE}}" STREQUAL "x${VARIABLE}")
set(CMAKE_CONFIGURABLE_FILE_CONTENT "/* */\n")
set(MACRO_CHECK_SYMBOL_EXISTS_FLAGS ${CMAKE_REQUIRED_FLAGS})
diff --git a/Modules/CheckTypeSize.c.in b/Modules/CheckTypeSize.c.in
index b6c368801..2303c4e05 100644
--- a/Modules/CheckTypeSize.c.in
+++ b/Modules/CheckTypeSize.c.in
@@ -9,6 +9,12 @@
# define KEY '_','_','p','p','c','_','_'
#elif defined(__ppc64__)
# define KEY '_','_','p','p','c','6','4','_','_'
+#elif defined(__aarch64__)
+# define KEY '_','_','a','a','r','c','h','6','4','_','_'
+#elif defined(__ARM_ARCH_7A__)
+# define KEY '_','_','A','R','M','_','A','R','C','H','_','7','A','_','_'
+#elif defined(__ARM_ARCH_7S__)
+# define KEY '_','_','A','R','M','_','A','R','C','H','_','7','S','_','_'
#endif
#define SIZE (sizeof(@type@))
diff --git a/Modules/Compiler/Clang-C.cmake b/Modules/Compiler/Clang-C.cmake
index b881e2b03..a07ae4019 100644
--- a/Modules/Compiler/Clang-C.cmake
+++ b/Modules/Compiler/Clang-C.cmake
@@ -2,19 +2,35 @@ include(Compiler/Clang)
__compiler_clang(C)
cmake_policy(GET CMP0025 appleClangPolicy)
-if(WIN32 OR (APPLE AND NOT appleClangPolicy STREQUAL NEW))
+if(APPLE AND NOT appleClangPolicy STREQUAL NEW)
return()
endif()
if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 3.4)
- set(CMAKE_C90_STANDARD_COMPILE_OPTION "-std=c90")
- set(CMAKE_C90_EXTENSION_COMPILE_OPTION "-std=gnu90")
+ if(NOT "x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC")
+ set(CMAKE_C90_STANDARD_COMPILE_OPTION "-std=c90")
+ set(CMAKE_C90_EXTENSION_COMPILE_OPTION "-std=gnu90")
- set(CMAKE_C99_STANDARD_COMPILE_OPTION "-std=c99")
- set(CMAKE_C99_EXTENSION_COMPILE_OPTION "-std=gnu99")
+ set(CMAKE_C99_STANDARD_COMPILE_OPTION "-std=c99")
+ set(CMAKE_C99_EXTENSION_COMPILE_OPTION "-std=gnu99")
- set(CMAKE_C11_STANDARD_COMPILE_OPTION "-std=c11")
- set(CMAKE_C11_EXTENSION_COMPILE_OPTION "-std=gnu11")
+ set(CMAKE_C11_STANDARD_COMPILE_OPTION "-std=c11")
+ set(CMAKE_C11_EXTENSION_COMPILE_OPTION "-std=gnu11")
+ else()
+ # clang-cl doesn't have any of these
+ set(CMAKE_C90_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_C90_EXTENSION_COMPILE_OPTION "")
+
+ set(CMAKE_C99_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_C99_EXTENSION_COMPILE_OPTION "")
+
+ set(CMAKE_C11_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_C11_EXTENSION_COMPILE_OPTION "")
+ endif()
endif()
-__compiler_check_default_language_standard(C 3.4 99 3.6 11)
+if(NOT "x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC")
+ __compiler_check_default_language_standard(C 3.4 99 3.6 11)
+else()
+ set(CMAKE_C_STANDARD_DEFAULT "")
+endif()
diff --git a/Modules/Compiler/Clang-CXX.cmake b/Modules/Compiler/Clang-CXX.cmake
index d3707eed8..efc68b3e4 100644
--- a/Modules/Compiler/Clang-CXX.cmake
+++ b/Modules/Compiler/Clang-CXX.cmake
@@ -10,30 +10,46 @@ if(APPLE AND NOT appleClangPolicy STREQUAL NEW)
return()
endif()
-if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 2.1)
- set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "-std=c++98")
- set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "-std=gnu++98")
-endif()
+if(NOT "x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC")
+ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 2.1)
+ set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "-std=c++98")
+ set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "-std=gnu++98")
+ endif()
-if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.1)
- set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "-std=c++11")
- set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-std=gnu++11")
-elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 2.1)
- set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "-std=c++0x")
- set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-std=gnu++0x")
-endif()
+ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.1)
+ set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "-std=c++11")
+ set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-std=gnu++11")
+ elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 2.1)
+ set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "-std=c++0x")
+ set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "-std=gnu++0x")
+ endif()
-if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.5)
- set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++14")
- set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++14")
-elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4)
- set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++1y")
- set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++1y")
-endif()
+ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.5)
+ set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++14")
+ set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++14")
+ elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4)
+ set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std=c++1y")
+ set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std=gnu++1y")
+ endif()
-if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.5)
- set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std=c++1z")
- set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std=gnu++1z")
+ if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.5)
+ set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std=c++1z")
+ set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std=gnu++1z")
+ endif()
+else()
+ # clang-cl does not know these options because it behaves like cl.exe
+ set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "")
+ set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "")
+ set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "")
+ set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "")
endif()
-__compiler_check_default_language_standard(CXX 2.1 98)
+if(NOT "x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC")
+ __compiler_check_default_language_standard(CXX 2.1 98)
+else()
+ set(CMAKE_CXX_STANDARD_DEFAULT "")
+endif()
diff --git a/Modules/Compiler/Clang.cmake b/Modules/Compiler/Clang.cmake
index 7d476f965..9f5e92181 100644
--- a/Modules/Compiler/Clang.cmake
+++ b/Modules/Compiler/Clang.cmake
@@ -69,15 +69,15 @@ else()
endif()
set(CMAKE_${lang}_ARCHIVE_CREATE_IPO
- "${__ar} cr <TARGET> <LINK_FLAGS> <OBJECTS>"
+ "\"${__ar}\" cr <TARGET> <LINK_FLAGS> <OBJECTS>"
)
set(CMAKE_${lang}_ARCHIVE_APPEND_IPO
- "${__ar} r <TARGET> <LINK_FLAGS> <OBJECTS>"
+ "\"${__ar}\" r <TARGET> <LINK_FLAGS> <OBJECTS>"
)
set(CMAKE_${lang}_ARCHIVE_FINISH_IPO
- "${__ranlib} <TARGET>"
+ "\"${__ranlib}\" <TARGET>"
)
endmacro()
endif()
diff --git a/Modules/Compiler/Flang-FindBinUtils.cmake b/Modules/Compiler/Flang-FindBinUtils.cmake
new file mode 100644
index 000000000..e721c8708
--- /dev/null
+++ b/Modules/Compiler/Flang-FindBinUtils.cmake
@@ -0,0 +1 @@
+include(Compiler/Clang-FindBinUtils)
diff --git a/Modules/Compiler/Flang-Fortran.cmake b/Modules/Compiler/Flang-Fortran.cmake
new file mode 100644
index 000000000..a1051f489
--- /dev/null
+++ b/Modules/Compiler/Flang-Fortran.cmake
@@ -0,0 +1,10 @@
+include(Compiler/Clang)
+__compiler_clang(Fortran)
+
+set(CMAKE_Fortran_PREPROCESS_SOURCE
+ "<CMAKE_Fortran_COMPILER> -cpp <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> -o <PREPROCESSED_SOURCE>")
+
+set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-ffixed-form")
+set(CMAKE_Fortran_FORMAT_FREE_FLAG "-ffree-form")
+
+set(CMAKE_Fortran_MODDIR_FLAG "-J")
diff --git a/Modules/Compiler/GNU-Fortran.cmake b/Modules/Compiler/GNU-Fortran.cmake
index 94dc2755a..c333d500b 100644
--- a/Modules/Compiler/GNU-Fortran.cmake
+++ b/Modules/Compiler/GNU-Fortran.cmake
@@ -7,6 +7,8 @@ set(CMAKE_Fortran_PREPROCESS_SOURCE
set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-ffixed-form")
set(CMAKE_Fortran_FORMAT_FREE_FLAG "-ffree-form")
+set(CMAKE_Fortran_POSTPROCESS_FLAG "-fpreprocessed")
+
# No -DNDEBUG for Fortran.
string(APPEND CMAKE_Fortran_FLAGS_MINSIZEREL_INIT " -Os")
string(APPEND CMAKE_Fortran_FLAGS_RELEASE_INIT " -O3")
diff --git a/Modules/Compiler/GNU.cmake b/Modules/Compiler/GNU.cmake
index 675e50534..d96268869 100644
--- a/Modules/Compiler/GNU.cmake
+++ b/Modules/Compiler/GNU.cmake
@@ -75,15 +75,15 @@ macro(__compiler_gnu lang)
#
# [1]: https://gcc.gnu.org/onlinedocs/gcc-4.9.4/gcc/Optimize-Options.html
set(CMAKE_${lang}_ARCHIVE_CREATE_IPO
- "${CMAKE_${lang}_COMPILER_AR} cr <TARGET> <LINK_FLAGS> <OBJECTS>"
+ "\"${CMAKE_${lang}_COMPILER_AR}\" cr <TARGET> <LINK_FLAGS> <OBJECTS>"
)
set(CMAKE_${lang}_ARCHIVE_APPEND_IPO
- "${CMAKE_${lang}_COMPILER_AR} r <TARGET> <LINK_FLAGS> <OBJECTS>"
+ "\"${CMAKE_${lang}_COMPILER_AR}\" r <TARGET> <LINK_FLAGS> <OBJECTS>"
)
set(CMAKE_${lang}_ARCHIVE_FINISH_IPO
- "${CMAKE_${lang}_COMPILER_RANLIB} <TARGET>"
+ "\"${CMAKE_${lang}_COMPILER_RANLIB}\" <TARGET>"
)
endif()
endmacro()
diff --git a/Modules/Compiler/IAR-ASM.cmake b/Modules/Compiler/IAR-ASM.cmake
index 844c30e50..651bc3ae1 100644
--- a/Modules/Compiler/IAR-ASM.cmake
+++ b/Modules/Compiler/IAR-ASM.cmake
@@ -2,13 +2,20 @@
include(Compiler/IAR)
-set(CMAKE_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT>")
-
-if("${IAR_TARGET_ARCHITECTURE}" STREQUAL "ARM")
+if("${CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM")
+set(CMAKE_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> -S <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT>")
+ __compiler_iar_ARM(ASM)
set(CMAKE_ASM_SOURCE_FILE_EXTENSIONS s;asm;msa)
-endif()
+ string(APPEND CMAKE_ASM_FLAGS_INIT " ")
+ string(APPEND CMAKE_ASM_FLAGS_DEBUG_INIT " -r")
+ string(APPEND CMAKE_ASM_FLAGS_MINSIZEREL_INIT " -DNDEBUG")
+ string(APPEND CMAKE_ASM_FLAGS_RELEASE_INIT " -DNDEBUG")
+ string(APPEND CMAKE_ASM_FLAGS_RELWITHDEBINFO_INIT " -r -DNDEBUG")
-if("${IAR_TARGET_ARCHITECTURE}" STREQUAL "AVR")
+elseif("${CMAKE_ASM${ASM_DIALECT}_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR")
+ set(CMAKE_ASM_COMPILE_OBJECT "<CMAKE_ASM_COMPILER> -S <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT>")
+ __compiler_iar_AVR(ASM)
set(CMAKE_ASM_SOURCE_FILE_EXTENSIONS s90;asm;msa)
+
endif()
diff --git a/Modules/Compiler/IAR-C.cmake b/Modules/Compiler/IAR-C.cmake
index f65b0c7da..55e019ec7 100644
--- a/Modules/Compiler/IAR-C.cmake
+++ b/Modules/Compiler/IAR-C.cmake
@@ -1,25 +1,32 @@
# This file is processed when the IAR compiler is used for a C file
-
include(Compiler/IAR)
-
-set(CMAKE_C_COMPILE_OBJECT "<CMAKE_C_COMPILER> <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT>")
-set(CMAKE_C_CREATE_PREPROCESSED_SOURCE "<CMAKE_C_COMPILER> <SOURCE> <DEFINES> <INCLUDES> <FLAGS> --preprocess=cnl <PREPROCESSED_SOURCE>")
-set(CMAKE_C_CREATE_ASSEMBLY_SOURCE "<CMAKE_C_COMPILER> <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -lAH <ASSEMBLY_SOURCE> -o <OBJECT>.dummy")
-
-set(CMAKE_C_RESPONSE_FILE_LINK_FLAG "-f ")
-set(CMAKE_DEPFILE_FLAGS_C "--dependencies=ns <DEPFILE>")
+include(Compiler/CMakeCommonCompilerMacros)
# The toolchains for ARM and AVR are quite different:
-if("${IAR_TARGET_ARCHITECTURE}" STREQUAL "ARM")
+if("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM")
- set(CMAKE_C_LINK_EXECUTABLE "<CMAKE_LINKER> <OBJECTS> <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES> -o <TARGET>")
- set(CMAKE_C_CREATE_STATIC_LIBRARY "<CMAKE_AR> <TARGET> --create <LINK_FLAGS> <OBJECTS> ")
+ set(CMAKE_C_EXTENSION_COMPILE_OPTION -e)
-endif()
+ set(CMAKE_C90_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_C90_EXTENSION_COMPILE_OPTION -e)
+ if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 6.10)
+ set(CMAKE_C90_STANDARD_COMPILE_OPTION --c89)
+ set(CMAKE_C90_EXTENSION_COMPILE_OPTION --c89 -e)
+ set(CMAKE_C99_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_C99_EXTENSION_COMPILE_OPTION -e)
+ endif()
+ if(NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 8.10)
+ set(CMAKE_C11_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_C11_EXTENSION_COMPILE_OPTION -e)
+ endif()
-if("${IAR_TARGET_ARCHITECTURE}" STREQUAL "AVR")
+ __compiler_iar_ARM(C)
+ __compiler_check_default_language_standard(C 1.10 90 6.10 99 8.10 11)
+
+elseif("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR")
+ __compiler_iar_AVR(C)
set(CMAKE_C_OUTPUT_EXTENSION ".r90")
if(NOT CMAKE_C_LINK_FLAGS)
@@ -29,9 +36,8 @@ if("${IAR_TARGET_ARCHITECTURE}" STREQUAL "AVR")
set(CMAKE_C_LINK_EXECUTABLE "<CMAKE_LINKER> <OBJECTS> <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES> -o <TARGET>")
set(CMAKE_C_CREATE_STATIC_LIBRARY "<CMAKE_AR> -o <TARGET> <OBJECTS> ")
+ # add the target specific include directory:
+ get_filename_component(_compilerDir "${CMAKE_C_COMPILER}" PATH)
+ get_filename_component(_compilerDir "${_compilerDir}" PATH)
+ include_directories("${_compilerDir}/inc" )
endif()
-
-# add the target specific include directory:
-get_filename_component(_compilerDir "${CMAKE_C_COMPILER}" PATH)
-get_filename_component(_compilerDir "${_compilerDir}" PATH)
-include_directories("${_compilerDir}/inc" )
diff --git a/Modules/Compiler/IAR-CXX.cmake b/Modules/Compiler/IAR-CXX.cmake
index f49968e90..8d86100a5 100644
--- a/Modules/Compiler/IAR-CXX.cmake
+++ b/Modules/Compiler/IAR-CXX.cmake
@@ -1,24 +1,41 @@
# This file is processed when the IAR compiler is used for a C++ file
include(Compiler/IAR)
+include(Compiler/CMakeCommonCompilerMacros)
+
+if("${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM")
+ # "(extended) embedded C++" Mode
+ # old version: --ec++ or --eec++
+ # since 8.10: --c++ --no_exceptions --no_rtti
+ #
+ # --c++ is full C++ and supported since 6.10
+ if(NOT CMAKE_IAR_CXX_FLAG)
+ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 6.10)
+ set(CMAKE_IAR_CXX_FLAG --c++)
+ else()
+ set(CMAKE_IAR_CXX_FLAG --eec++)
+ endif()
+ endif()
-set(CMAKE_CXX_COMPILE_OBJECT "<CMAKE_CXX_COMPILER> <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT>")
-
-set(CMAKE_CXX_CREATE_PREPROCESSED_SOURCE "<CMAKE_CXX_COMPILER> <SOURCE> <DEFINES> <INCLUDES> <FLAGS> --preprocess=cnl <PREPROCESSED_SOURCE>")
-set(CMAKE_CXX_CREATE_ASSEMBLY_SOURCE "<CMAKE_CXX_COMPILER> <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -lAH <ASSEMBLY_SOURCE> -o <OBJECT>.dummy")
-
-set(CMAKE_CXX_RESPONSE_FILE_LINK_FLAG "-f ")
-set(CMAKE_DEPFILE_FLAGS_CXX "--dependencies=ns <DEPFILE>")
-
-if("${IAR_TARGET_ARCHITECTURE}" STREQUAL "ARM")
+ set(CMAKE_CXX_EXTENSION_COMPILE_OPTION -e)
- set(CMAKE_CXX_LINK_EXECUTABLE "<CMAKE_LINKER> <OBJECTS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES> -o <TARGET>")
- set(CMAKE_CXX_CREATE_STATIC_LIBRARY "<CMAKE_AR> <TARGET> --create <LINK_FLAGS> <OBJECTS> ")
+ set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION -e)
-endif()
+ if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 8.10)
+ set(CMAKE_CXX03_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX03_EXTENSION_COMPILE_OPTION -e)
+ set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION -e)
+ set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION -e)
+ endif()
+ __compiler_iar_ARM(CXX)
+ __compiler_check_default_language_standard(CXX 6.10 98 8.10 14)
-if("${IAR_TARGET_ARCHITECTURE}" STREQUAL "AVR")
+elseif("${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR")
+ __compiler_iar_AVR(CXX)
set(CMAKE_CXX_OUTPUT_EXTENSION ".r90")
if(NOT CMAKE_CXX_LINK_FLAGS)
set(CMAKE_CXX_LINK_FLAGS "-Fmotorola")
@@ -27,9 +44,8 @@ if("${IAR_TARGET_ARCHITECTURE}" STREQUAL "AVR")
set(CMAKE_CXX_LINK_EXECUTABLE "<CMAKE_LINKER> <OBJECTS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES> -o <TARGET>")
set(CMAKE_CXX_CREATE_STATIC_LIBRARY "<CMAKE_AR> -o <TARGET> <OBJECTS> ")
+ # add the target specific include directory:
+ get_filename_component(_compilerDir "${CMAKE_C_COMPILER}" PATH)
+ get_filename_component(_compilerDir "${_compilerDir}" PATH)
+ include_directories("${_compilerDir}/inc")
endif()
-
-# add the target specific include directory:
-get_filename_component(_compilerDir "${CMAKE_C_COMPILER}" PATH)
-get_filename_component(_compilerDir "${_compilerDir}" PATH)
-include_directories("${_compilerDir}/inc")
diff --git a/Modules/Compiler/IAR-DetermineCompiler.cmake b/Modules/Compiler/IAR-DetermineCompiler.cmake
index c39810a24..a1bffebdb 100644
--- a/Modules/Compiler/IAR-DetermineCompiler.cmake
+++ b/Modules/Compiler/IAR-DetermineCompiler.cmake
@@ -1,4 +1,21 @@
-
# IAR Systems compiler for embedded systems.
# http://www.iar.com
-set(_compiler_id_pp_test "defined(__IAR_SYSTEMS_ICC__ ) || defined(__IAR_SYSTEMS_ICC)")
+# http://supp.iar.com/FilesPublic/UPDINFO/004916/arm/doc/EWARM_DevelopmentGuide.ENU.pdf
+#
+# __IAR_SYSTEMS_ICC__ An integer that identifies the IAR compiler platform:
+# 9 and higher means C11 and C++14 as language default
+# 8 means C99 and C++03 as language default
+# 7 and lower means C89 and EC++ as language default.
+# __ICCARM__ An integer that is set to 1 when the code is compiled with the IAR C/C++ Compiler for ARM
+# __VER__ An integer that identifies the version number of the IAR compiler in use. For example,
+# version 5.11.3 is returned as 5011003.
+
+set(_compiler_id_pp_test "defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC)")
+
+set(_compiler_id_version_compute "
+# if defined(__VER__)
+# define @PREFIX@COMPILER_VERSION_MAJOR @MACRO_DEC@((__VER__) / 1000000)
+# define @PREFIX@COMPILER_VERSION_MINOR @MACRO_DEC@(((__VER__) / 1000) % 1000)
+# define @PREFIX@COMPILER_VERSION_PATCH @MACRO_DEC@((__VER__) % 1000)
+# define @PREFIX@COMPILER_VERSION_INTERNAL @MACRO_DEC@(__IAR_SYSTEMS_ICC__)
+# endif")
diff --git a/Modules/Compiler/IAR-FindBinUtils.cmake b/Modules/Compiler/IAR-FindBinUtils.cmake
new file mode 100644
index 000000000..2b0479507
--- /dev/null
+++ b/Modules/Compiler/IAR-FindBinUtils.cmake
@@ -0,0 +1,54 @@
+if(NOT DEFINED _CMAKE_PROCESSING_LANGUAGE OR _CMAKE_PROCESSING_LANGUAGE STREQUAL "")
+ message(FATAL_ERROR "Internal error: _CMAKE_PROCESSING_LANGUAGE is not set")
+endif()
+
+# Try to find tools in the same directory as Clang itself
+get_filename_component(__iar_hint_1 "${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER}" REALPATH)
+get_filename_component(__iar_hint_1 "${__iar_hint_1}" DIRECTORY)
+
+get_filename_component(__iar_hint_2 "${CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER}" DIRECTORY)
+
+set(__iar_hints "${__iar_hint_1}" "${__iar_hint_2}")
+
+if("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "ARM")
+ # could allow using normal binutils ar, since objects are normal ELF files?
+ find_program(CMAKE_IAR_LINKARM ilinkarm.exe HINTS ${__iar_hints}
+ DOC "The IAR ARM linker")
+ find_program(CMAKE_IAR_ARCHIVE iarchive.exe HINTS ${__iar_hints}
+ DOC "The IAR archiver")
+
+ # find auxillary tools
+ find_program(CMAKE_IAR_ELFTOOL ielftool.exe HINTS ${__iar_hints}
+ DOC "The IAR ELF Tool")
+ find_program(CMAKE_IAR_ELFDUMP ielfdumparm.exe HINTS ${__iar_hints}
+ DOC "The IAR ELF Dumper")
+ find_program(CMAKE_IAR_OBJMANIP iobjmanip.exe HINTS ${__iar_hints}
+ DOC "The IAR ELF Object Tool")
+ find_program(CMAKE_IAR_SYMEXPORT isymexport.exe HINTS ${__iar_hints}
+ DOC "The IAR Absolute Symbol Exporter")
+ mark_as_advanced(CMAKE_IAR_LINKARM CMAKE_IAR_ARCHIVE CMAKE_IAR_ELFTOOL CMAKE_IAR_ELFDUMP CMAKE_IAR_OBJMANIP CMAKE_IAR_SYMEXPORT)
+
+ set(CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_CUSTOM_CODE
+"set(CMAKE_IAR_LINKARM \"${CMAKE_IAR_LINKARM}\")
+set(CMAKE_IAR_ARCHIVE \"${CMAKE_IAR_ARCHIVE}\")
+set(CMAKE_IAR_ELFTOOL \"${CMAKE_IAR_ELFTOOL}\")
+set(CMAKE_IAR_ELFDUMP \"${CMAKE_IAR_ELFDUMP}\")
+set(CMAKE_IAR_OBJMANIP \"${CMAKE_IAR_OBJMANIP}\")
+set(CMAKE_IAR_LINKARM \"${CMAKE_IAR_LINKARM}\")
+")
+
+
+elseif("${CMAKE_C_COMPILER_ARCHITECTURE_ID}" STREQUAL "AVR")
+
+ # For AVR and AVR32, IAR uses the "xlink" linker and the "xar" archiver:
+ find_program(CMAKE_IAR_LINKER xlink.exe HINTS ${__iar_hints}
+ DOC "The IAR AVR linker")
+ find_program(CMAKE_IAR_AR xar.exe HINTS ${__iar_hints}
+ DOC "The IAR archiver")
+ mark_as_advanced(CMAKE_IAR_LINKER CMAKE_IAR_AR)
+
+ set(CMAKE_${_CMAKE_PROCESSING_LANGUAGE}_COMPILER_CUSTOM_CODE
+"set(CMAKE_IAR_LINKER \"${CMAKE_IAR_LINKER}\")
+set(CMAKE_IAR_AR \"${CMAKE_IAR_AR}\")
+")
+endif()
diff --git a/Modules/Compiler/IAR.cmake b/Modules/Compiler/IAR.cmake
index 8c45276db..52ebaf20a 100644
--- a/Modules/Compiler/IAR.cmake
+++ b/Modules/Compiler/IAR.cmake
@@ -2,46 +2,75 @@
# Documentation can be downloaded here: http://www.iar.com/website1/1.0.1.0/675/1/
# The initial feature request is here: https://gitlab.kitware.com/cmake/cmake/issues/10176
# It also contains additional links and information.
+# See USER GUIDES -> C/C++ Development Guide and ReleaseNotes for:
+# version 6.30.8: http://supp.iar.com/FilesPublic/UPDINFO/006607/arm/doc/infocenter/index.ENU.html
+# version 7.60.1: http://supp.iar.com/FilesPublic/UPDINFO/011006/arm/doc/infocenter/index.ENU.html
+# version 8.10.1: http://netstorage.iar.com/SuppDB/Public/UPDINFO/011854/arm/doc/infocenter/index.ENU.html
-if(_IAR_CMAKE_LOADED)
+# C/C++ Standard versions
+#
+# IAR typically only supports one C and C++ Standard version,
+# the exception is C89 which is always supported and can be selected
+# if its not the default
+#
+# C++ is trickier, there were historically 3 switches,
+# and some IAR versions support multiple of those.
+# they are --eec++, --ec++ and --c++ and where used to
+# enable various language features like exceptions
+#
+# recent versions only have --c++ for full support
+# but can choose to disable features with further arguments
+#
+# C/C++ Standard compliance
+#
+# IAR has 3 modes: default, strict and extended
+# the extended mode is needed for popular libraries like CMSIS
+#
+# "Silent" Operation
+#
+# this really is different to most programs I know.
+# nothing meaningfull from the operation is lost, just some redundant
+# code and data size printouts (that can be inspected with common tools).
+
+# This module is shared by multiple languages; use include blocker.
+if(_IARARM_CMAKE_LOADED)
return()
endif()
-set(_IAR_CMAKE_LOADED TRUE)
+set(_IARARM_CMAKE_LOADED 1)
+macro(__compiler_iar_ARM lang)
+ set(CMAKE_EXECUTABLE_SUFFIX ".elf")
+ if (${lang} STREQUAL "C" OR ${lang} STREQUAL "CXX")
-get_filename_component(_CMAKE_C_TOOLCHAIN_LOCATION "${CMAKE_C_COMPILER}" PATH)
-get_filename_component(_CMAKE_CXX_TOOLCHAIN_LOCATION "${CMAKE_CXX_COMPILER}" PATH)
-get_filename_component(_CMAKE_ASM_TOOLCHAIN_LOCATION "${CMAKE_ASM_COMPILER}" PATH)
+ set(CMAKE_${lang}_COMPILE_OBJECT "<CMAKE_${lang}_COMPILER> ${CMAKE_IAR_${lang}_FLAG} --silent <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT>")
+ set(CMAKE_${lang}_CREATE_PREPROCESSED_SOURCE "<CMAKE_${lang}_COMPILER> ${CMAKE_IAR_${lang}_FLAG} --silent <SOURCE> <DEFINES> <INCLUDES> <FLAGS> --preprocess=cnl <PREPROCESSED_SOURCE>")
+ set(CMAKE_${lang}_CREATE_ASSEMBLY_SOURCE "<CMAKE_${lang}_COMPILER> ${CMAKE_IAR_${lang}_FLAG} --silent <SOURCE> <DEFINES> <INCLUDES> <FLAGS> -lAH <ASSEMBLY_SOURCE> -o <OBJECT>.dummy")
+ set(CMAKE_${lang}_RESPONSE_FILE_LINK_FLAG "-f ")
+ set(CMAKE_DEPFILE_FLAGS_${lang} "--dependencies=ns <DEPFILE>")
-if("${CMAKE_C_COMPILER}" MATCHES "arm" OR "${CMAKE_CXX_COMPILER}" MATCHES "arm" OR "${CMAKE_ASM_COMPILER}" MATCHES "arm")
- set(CMAKE_EXECUTABLE_SUFFIX ".elf")
+ string(APPEND CMAKE_${lang}_FLAGS_INIT " ")
+ string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -r")
+ string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " -Ohz -DNDEBUG")
+ string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -Oh -DNDEBUG")
+ string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -Oh -r -DNDEBUG")
+ endif()
- # For arm, IAR uses the "ilinkarm" linker and "iarchive" archiver:
- find_program(CMAKE_IAR_LINKER ilinkarm HINTS "${_CMAKE_C_TOOLCHAIN_LOCATION}" "${_CMAKE_CXX_TOOLCHAIN_LOCATION}" "${_CMAKE_ASM_TOOLCHAIN_LOCATION}")
- find_program(CMAKE_IAR_AR iarchive HINTS "${_CMAKE_C_TOOLCHAIN_LOCATION}" "${_CMAKE_CXX_TOOLCHAIN_LOCATION}" "${_CMAKE_ASM_TOOLCHAIN_LOCATION}" )
+ set(CMAKE_${lang}_LINK_EXECUTABLE "\"${CMAKE_IAR_LINKARM}\" --silent <OBJECTS> <CMAKE_${lang}_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES> -o <TARGET>")
+ set(CMAKE_${lang}_CREATE_STATIC_LIBRARY "\"${CMAKE_IAR_ARCHIVE}\" <TARGET> --create <LINK_FLAGS> <OBJECTS>")
+ set(CMAKE_${lang}_ARCHIVE_CREATE "\"${CMAKE_IAR_ARCHIVE}\" <TARGET> --create <LINK_FLAGS> <OBJECTS>")
+ set(CMAKE_${lang}_ARCHIVE_APPEND "\"${CMAKE_IAR_ARCHIVE}\" <TARGET> --replace <LINK_FLAGS> <OBJECTS>")
+ set(CMAKE_${lang}_ARCHIVE_FINISH "")
- set(IAR_TARGET_ARCHITECTURE "ARM" CACHE STRING "IAR compiler target architecture")
-endif()
+ set(CMAKE_LINKER "${CMAKE_IAR_LINKARM}" CACHE FILEPATH "The IAR linker" FORCE)
+ set(CMAKE_AR "${CMAKE_IAR_ARCHIVE}" CACHE FILEPATH "The IAR archiver" FORCE)
+endmacro()
-if("${CMAKE_C_COMPILER}" MATCHES "avr" OR "${CMAKE_CXX_COMPILER}" MATCHES "avr" OR "${CMAKE_ASM_COMPILER}" MATCHES "avr")
+macro(__compiler_iar_AVR lang)
set(CMAKE_EXECUTABLE_SUFFIX ".bin")
- # For AVR and AVR32, IAR uses the "xlink" linker and the "xar" archiver:
- find_program(CMAKE_IAR_LINKER xlink HINTS "${_CMAKE_C_TOOLCHAIN_LOCATION}" "${_CMAKE_CXX_TOOLCHAIN_LOCATION}" "${_CMAKE_ASM_TOOLCHAIN_LOCATION}" )
- find_program(CMAKE_IAR_AR xar HINTS "${_CMAKE_C_TOOLCHAIN_LOCATION}" "${_CMAKE_CXX_TOOLCHAIN_LOCATION}" "${_CMAKE_ASM_TOOLCHAIN_LOCATION}" )
-
- set(IAR_TARGET_ARCHITECTURE "AVR" CACHE STRING "IAR compiler target architecture")
-
set(CMAKE_LIBRARY_PATH_FLAG "-I")
-endif()
-
-if(NOT IAR_TARGET_ARCHITECTURE)
- message(FATAL_ERROR "The IAR compiler for this architecture is not yet supported "
- "by CMake. Please go to https://gitlab.kitware.com/cmake/cmake/issues "
- "and enter a feature request there.")
-endif()
-
-set(CMAKE_LINKER "${CMAKE_IAR_LINKER}" CACHE FILEPATH "The IAR linker" FORCE)
-set(CMAKE_AR "${CMAKE_IAR_AR}" CACHE FILEPATH "The IAR archiver" FORCE)
+ set(CMAKE_LINKER "${CMAKE_IAR_LINKER}" CACHE FILEPATH "The IAR linker" FORCE)
+ set(CMAKE_AR "${CMAKE_IAR_AR}" CACHE FILEPATH "The IAR archiver" FORCE)
+endmacro()
diff --git a/Modules/Compiler/MSVC-CXX.cmake b/Modules/Compiler/MSVC-CXX.cmake
index 9371301d7..789fff53b 100644
--- a/Modules/Compiler/MSVC-CXX.cmake
+++ b/Modules/Compiler/MSVC-CXX.cmake
@@ -3,7 +3,38 @@
include(Compiler/CMakeCommonCompilerMacros)
-if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.0)
+if ((CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.0.24215.1 AND
+ CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10) OR
+ CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.10.25017)
+
+ # VS 2015 Update 3 and above support language standard level flags,
+ # with the default and minimum level being C++14.
+ set(CMAKE_CXX98_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX98_EXTENSION_COMPILE_OPTION "")
+ set(CMAKE_CXX11_STANDARD_COMPILE_OPTION "")
+ set(CMAKE_CXX11_EXTENSION_COMPILE_OPTION "")
+ set(CMAKE_CXX14_STANDARD_COMPILE_OPTION "-std:c++14")
+ set(CMAKE_CXX14_EXTENSION_COMPILE_OPTION "-std:c++14")
+ if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.11.25505)
+ set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std:c++17")
+ set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std:c++17")
+ else()
+ set(CMAKE_CXX17_STANDARD_COMPILE_OPTION "-std:c++latest")
+ set(CMAKE_CXX17_EXTENSION_COMPILE_OPTION "-std:c++latest")
+ endif()
+
+ __compiler_check_default_language_standard(CXX 19.0 14)
+
+ # All features that we define are available in the base mode, except
+ # for meta-features for C++14 and above. Override the default macro
+ # to avoid doing unnecessary work.
+ macro(cmake_record_cxx_compile_features)
+ list(APPEND CMAKE_CXX17_COMPILE_FEATURES cxx_std_17)
+ list(APPEND CMAKE_CXX14_COMPILE_FEATURES cxx_std_14)
+ list(APPEND CMAKE_CXX98_COMPILE_FEATURES cxx_std_11) # no flag needed for 11
+ _record_compiler_features_cxx(98)
+ endmacro()
+elseif (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.0)
# MSVC has no specific options to set language standards, but set them as
# empty strings anyways so the feature test infrastructure can at least check
# to see if they are defined.
@@ -18,4 +49,18 @@ if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.0)
# There is no meaningful default for this
set(CMAKE_CXX_STANDARD_DEFAULT "")
+
+ # There are no compiler modes so we only need to test features once.
+ # Override the default macro for this special case. Pretend that
+ # all language standards are available so that at least compilation
+ # can be attempted.
+ macro(cmake_record_cxx_compile_features)
+ list(APPEND CMAKE_CXX_COMPILE_FEATURES
+ cxx_std_98
+ cxx_std_11
+ cxx_std_14
+ cxx_std_17
+ )
+ _record_compiler_features(CXX "" CMAKE_CXX_COMPILE_FEATURES)
+ endmacro()
endif()
diff --git a/Modules/Compiler/NVIDIA-CUDA.cmake b/Modules/Compiler/NVIDIA-CUDA.cmake
index 785e26998..1c9165458 100644
--- a/Modules/Compiler/NVIDIA-CUDA.cmake
+++ b/Modules/Compiler/NVIDIA-CUDA.cmake
@@ -26,6 +26,8 @@ else()
set(CMAKE_CUDA11_EXTENSION_COMPILE_OPTION "-std=c++11")
if (NOT CMAKE_CUDA_COMPILER_VERSION VERSION_LESS 9.0)
+ set(CMAKE_CUDA98_STANDARD_COMPILE_OPTION "-std=c++03")
+ set(CMAKE_CUDA98_EXTENSION_COMPILE_OPTION "-std=c++03")
set(CMAKE_CUDA14_STANDARD_COMPILE_OPTION "-std=c++14")
set(CMAKE_CUDA14_EXTENSION_COMPILE_OPTION "-std=c++14")
endif()
diff --git a/Modules/Compiler/PGI-Fortran.cmake b/Modules/Compiler/PGI-Fortran.cmake
index 478342436..a183c339b 100644
--- a/Modules/Compiler/PGI-Fortran.cmake
+++ b/Modules/Compiler/PGI-Fortran.cmake
@@ -7,7 +7,6 @@ set(CMAKE_Fortran_PREPROCESS_SOURCE
set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-Mnofreeform")
set(CMAKE_Fortran_FORMAT_FREE_FLAG "-Mfreeform")
-string(APPEND CMAKE_Fortran_FLAGS_INIT " -Mpreprocess -Kieee")
string(APPEND CMAKE_Fortran_FLAGS_DEBUG_INIT " -Mbounds")
set(CMAKE_Fortran_MODDIR_FLAG "-module ")
diff --git a/Modules/Compiler/PGI.cmake b/Modules/Compiler/PGI.cmake
index 0cbfd8a0b..d5a57ee1c 100644
--- a/Modules/Compiler/PGI.cmake
+++ b/Modules/Compiler/PGI.cmake
@@ -19,16 +19,20 @@ macro(__compiler_pgi lang)
string(APPEND CMAKE_${lang}_FLAGS_DEBUG_INIT " -g -O0")
string(APPEND CMAKE_${lang}_FLAGS_MINSIZEREL_INIT " -O2 -s")
string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -fast -O3")
- # -Mipa was dropped with PGI 16.3 from Windows versions
- if(NOT CMAKE_HOST_WIN32 OR CMAKE_${lang}_COMPILER_VERSION VERSION_LESS 16.3)
- string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT " -Mipa=fast")
- endif()
string(APPEND CMAKE_${lang}_FLAGS_RELWITHDEBINFO_INIT " -O2 -gopt")
if(CMAKE_HOST_WIN32)
string(APPEND CMAKE_${lang}_FLAGS_INIT " -Bdynamic")
endif()
+ set(_CMAKE_${lang}_IPO_SUPPORTED_BY_CMAKE YES)
+ if(NOT CMAKE_SYSTEM_PROCESSOR STREQUAL ppc64le AND (NOT CMAKE_HOST_WIN32 OR CMAKE_${lang}_COMPILER_VERSION VERSION_LESS 16.3))
+ set(_CMAKE_${lang}_IPO_MAY_BE_SUPPORTED_BY_COMPILER YES)
+ set(CMAKE_${lang}_COMPILE_OPTIONS_IPO "-Mipa=fast,inline")
+ else()
+ set(_CMAKE_${lang}_IPO_MAY_BE_SUPPORTED_BY_COMPILER NO)
+ endif()
+
# Preprocessing and assembly rules.
set(CMAKE_${lang}_CREATE_PREPROCESSED_SOURCE "<CMAKE_${lang}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -E <SOURCE> > <PREPROCESSED_SOURCE>")
set(CMAKE_${lang}_CREATE_ASSEMBLY_SOURCE "<CMAKE_${lang}_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -S <SOURCE> -o <ASSEMBLY_SOURCE>")
diff --git a/Modules/CompilerId/Xcode-3.pbxproj.in b/Modules/CompilerId/Xcode-3.pbxproj.in
index 84f48ae65..1cbaa578b 100644
--- a/Modules/CompilerId/Xcode-3.pbxproj.in
+++ b/Modules/CompilerId/Xcode-3.pbxproj.in
@@ -72,6 +72,7 @@
1DEB928608733DD80010E9CD = {
isa = XCBuildConfiguration;
buildSettings = {
+ @id_development_team@
PRODUCT_NAME = CompilerId@id_lang@;
};
name = Debug;
diff --git a/Modules/DartConfiguration.tcl.in b/Modules/DartConfiguration.tcl.in
index 0ff2eed8b..b86a5a9a8 100644
--- a/Modules/DartConfiguration.tcl.in
+++ b/Modules/DartConfiguration.tcl.in
@@ -16,6 +16,9 @@ Site: @SITE@
# Build name is osname-revision-compiler, i.e. Linux-2.4.2-2smp-c++
BuildName: @BUILDNAME@
+# Subprojects
+LabelsForSubprojects: @CTEST_LABELS_FOR_SUBPROJECTS@
+
# Submission information
IsCDash: @CTEST_DROP_SITE_CDASH@
CDashVersion: @CTEST_CDASH_VERSION@
diff --git a/Modules/ExternalProject.cmake b/Modules/ExternalProject.cmake
index 24957363e..419c9d67b 100644
--- a/Modules/ExternalProject.cmake
+++ b/Modules/ExternalProject.cmake
@@ -5,413 +5,863 @@
ExternalProject
---------------
-Create custom targets to build projects in external trees
+.. only:: html
+
+ .. contents::
+
+External Project Definition
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. command:: ExternalProject_Add
- The ``ExternalProject_Add`` function creates a custom target to drive
+ The ``ExternalProject_Add()`` function creates a custom target to drive
download, update/patch, configure, build, install and test steps of an
external project::
- ExternalProject_Add(<name> [<option>...])
-
- General options are:
-
- ``DEPENDS <projects>...``
- Targets on which the project depends
- ``PREFIX <dir>``
- Root dir for entire project
- ``LIST_SEPARATOR <sep>``
- Sep to be replaced by ; in cmd lines
- ``TMP_DIR <dir>``
- Directory to store temporary files
- ``STAMP_DIR <dir>``
- Directory to store step timestamps
- ``EXCLUDE_FROM_ALL 1``
- The "all" target does not depend on this
-
- Download step options are:
-
- ``DOWNLOAD_NAME <fname>``
- File name to store (if not end of URL)
- ``DOWNLOAD_DIR <dir>``
- Directory to store downloaded files
- ``DOWNLOAD_COMMAND <cmd>...``
- Command to download source tree
- ``DOWNLOAD_NO_PROGRESS 1``
- Disable download progress reports
- ``CVS_REPOSITORY <cvsroot>``
- CVSROOT of CVS repository
- ``CVS_MODULE <mod>``
- Module to checkout from CVS repo
- ``CVS_TAG <tag>``
- Tag to checkout from CVS repo
- ``SVN_REPOSITORY <url>``
- URL of Subversion repo
- ``SVN_REVISION -r<rev>``
- Revision to checkout from Subversion repo
- ``SVN_USERNAME <username>``
- Username for Subversion checkout and update
- ``SVN_PASSWORD <password>``
- Password for Subversion checkout and update
- ``SVN_TRUST_CERT 1``
- Trust the Subversion server site certificate
- ``GIT_REPOSITORY <url>``
- URL of git repo
- ``GIT_TAG <tag>``
- Git branch name, commit id or tag
- ``GIT_REMOTE_NAME <name>``
- The optional name of the remote, default to ``origin``
- ``GIT_SUBMODULES <module>...``
- Git submodules that shall be updated, all if empty
- ``GIT_SHALLOW 1``
- Tell Git to clone with ``--depth 1``. Use when ``GIT_TAG`` is not
- specified or when it names a branch in order to download only the
- tip of the branch without the rest of its history.
- ``GIT_PROGRESS 1``
- Tell Git to clone with ``--progress``. For large projects, the clone step
- does not output anything which can make the build appear to have stalled.
- This option forces Git to output progress information during the clone step
- so that forward progress is indicated.
- ``GIT_CONFIG <option>...``
- Tell Git to clone with ``--config <option>``. Use additional configuration
- parameters when cloning the project (``key=value`` as expected by ``git
- config``).
- ``HG_REPOSITORY <url>``
- URL of mercurial repo
- ``HG_TAG <tag>``
- Mercurial branch name, commit id or tag
- ``URL /.../src.tgz [/.../src.tgz]...``
- Full path or URL(s) of source. Multiple URLs are allowed as mirrors.
- ``URL_HASH ALGO=value``
- Hash of file at URL
- ``URL_MD5 md5``
- Equivalent to URL_HASH MD5=md5
- ``HTTP_USERNAME <username>``
- Username for download operation
- ``HTTP_PASSWORD <username>``
- Password for download operation
- ``HTTP_HEADER <header>``
- HTTP header for download operation. Suboption can be repeated several times.
- ``TLS_VERIFY <bool>``
- Should certificate for https be checked
- ``TLS_CAINFO <file>``
- Path to a certificate authority file
- ``TIMEOUT <seconds>``
- Time allowed for file download operations
- ``DOWNLOAD_NO_EXTRACT 1``
- Just download the file and do not extract it; the full path to the
- downloaded file is available as ``<DOWNLOADED_FILE>``.
-
- Update/Patch step options are:
-
- ``UPDATE_COMMAND <cmd>...``
- Source work-tree update command
- ``UPDATE_DISCONNECTED 1``
- Never update automatically from the remote repository
- ``PATCH_COMMAND <cmd>...``
- Command to patch downloaded source
-
- Configure step options are:
-
- ``SOURCE_DIR <dir>``
- Source dir to be used for build
- ``SOURCE_SUBDIR <dir>``
- Path to source CMakeLists.txt relative to ``SOURCE_DIR``
- ``CONFIGURE_COMMAND <cmd>...``
- Build tree configuration command
- ``CMAKE_COMMAND /.../cmake``
- Specify alternative cmake executable
- ``CMAKE_GENERATOR <gen>``
- Specify generator for native build
- ``CMAKE_GENERATOR_PLATFORM <platform>``
- Generator-specific platform name
- ``CMAKE_GENERATOR_TOOLSET <toolset>``
- Generator-specific toolset name
- ``CMAKE_ARGS <arg>...``
- Arguments to CMake command line.
- These arguments are passed to CMake command line, and can contain
- arguments other than cache values, see also
- :manual:`CMake Options <cmake(1)>`. Arguments in the form
- ``-Dvar:string=on`` are always passed to the command line, and
- therefore cannot be changed by the user.
- Arguments may use
- :manual:`generator expressions <cmake-generator-expressions(7)>`.
- ``CMAKE_CACHE_ARGS <arg>...``
- Initial cache arguments, of the form ``-Dvar:string=on``.
- These arguments are written in a pre-load a script that populates
- CMake cache, see also :manual:`cmake -C <cmake(1)>`. This allows one to
- overcome command line length limits.
- These arguments are :command:`set` using the ``FORCE`` argument,
- and therefore cannot be changed by the user.
- Arguments may use
- :manual:`generator expressions <cmake-generator-expressions(7)>`.
- ``CMAKE_CACHE_DEFAULT_ARGS <arg>...``
- Initial default cache arguments, of the form ``-Dvar:string=on``.
- These arguments are written in a pre-load a script that populates
- CMake cache, see also :manual:`cmake -C <cmake(1)>`. This allows one to
- overcome command line length limits.
- These arguments can be used as default value that will be set if no
- previous value is found in the cache, and that the user can change
- later.
- Arguments may use
- :manual:`generator expressions <cmake-generator-expressions(7)>`.
-
- Build step options are:
-
- ``BINARY_DIR <dir>``
- Specify build dir location
- ``BUILD_COMMAND <cmd>...``
- Command to drive the native build
- ``BUILD_IN_SOURCE 1``
- Use source dir for build dir
- ``BUILD_ALWAYS 1``
- No stamp file, build step always runs
- ``BUILD_BYPRODUCTS <file>...``
- Files that will be generated by the build command but may or may
- not have their modification time updated by subsequent builds.
-
- Install step options are:
-
- ``INSTALL_DIR <dir>``
- Installation prefix to be placed in the ``<INSTALL_DIR>`` placeholder.
- This does not actually configure the external project to install to
- the given prefix. That must be done by passing appropriate arguments
- to the external project configuration step, e.g. using ``<INSTALL_DIR>``.
- ``INSTALL_COMMAND <cmd>...``
- Command to drive installation of the external project after it has been
- built. This only happens at the *build* time of the calling project.
- In order to install files from the external project alongside the
- locally-built files, a separate local :command:`install` call must be
- added to pick the files up from one of the external project trees.
-
- Test step options are:
-
- ``TEST_BEFORE_INSTALL 1``
- Add test step executed before install step
- ``TEST_AFTER_INSTALL 1``
- Add test step executed after install step
- ``TEST_EXCLUDE_FROM_MAIN 1``
- Main target does not depend on the test step
- ``TEST_COMMAND <cmd>...``
- Command to drive test
-
- Output logging options are:
-
- ``LOG_DOWNLOAD 1``
- Wrap download in script to log output
- ``LOG_UPDATE 1``
- Wrap update in script to log output
- ``LOG_CONFIGURE 1``
- Wrap configure in script to log output
- ``LOG_BUILD 1``
- Wrap build in script to log output
- ``LOG_TEST 1``
- Wrap test in script to log output
- ``LOG_INSTALL 1``
- Wrap install in script to log output
-
- Steps can be given direct access to the terminal if possible. With
- the :generator:`Ninja` generator, this places the steps in the
- ``console`` :prop_gbl:`pool <JOB_POOLS>`. Options are:
-
- ``USES_TERMINAL_DOWNLOAD 1``
- Give download terminal access.
- ``USES_TERMINAL_UPDATE 1``
- Give update terminal access.
- ``USES_TERMINAL_CONFIGURE 1``
- Give configure terminal access.
- ``USES_TERMINAL_BUILD 1``
- Give build terminal access.
- ``USES_TERMINAL_TEST 1``
- Give test terminal access.
- ``USES_TERMINAL_INSTALL 1``
- Give install terminal access.
-
- Other options are:
-
- ``STEP_TARGETS <step-target>...``
- Generate custom targets for these steps
- ``INDEPENDENT_STEP_TARGETS <step-target>...``
- Generate custom targets for these steps that do not depend on other
- external projects even if a dependency is set
-
- The ``*_DIR`` options specify directories for the project, with default
- directories computed as follows. If the ``PREFIX`` option is given to
- ``ExternalProject_Add()`` or the ``EP_PREFIX`` directory property is set,
- then an external project is built and installed under the specified prefix::
-
- TMP_DIR = <prefix>/tmp
- STAMP_DIR = <prefix>/src/<name>-stamp
- DOWNLOAD_DIR = <prefix>/src
- SOURCE_DIR = <prefix>/src/<name>
- BINARY_DIR = <prefix>/src/<name>-build
- INSTALL_DIR = <prefix>
-
- Otherwise, if the ``EP_BASE`` directory property is set then components
- of an external project are stored under the specified base::
-
- TMP_DIR = <base>/tmp/<name>
- STAMP_DIR = <base>/Stamp/<name>
- DOWNLOAD_DIR = <base>/Download/<name>
- SOURCE_DIR = <base>/Source/<name>
- BINARY_DIR = <base>/Build/<name>
- INSTALL_DIR = <base>/Install/<name>
-
- If no ``PREFIX``, ``EP_PREFIX``, or ``EP_BASE`` is specified then the
- default is to set ``PREFIX`` to ``<name>-prefix``. Relative paths are
- interpreted with respect to the build directory corresponding to the
- source directory in which ``ExternalProject_Add`` is invoked.
-
- If ``SOURCE_SUBDIR`` is set and no ``CONFIGURE_COMMAND`` is specified, the
- configure command will run CMake using the ``CMakeLists.txt`` located in the
- relative path specified by ``SOURCE_SUBDIR``, relative to the ``SOURCE_DIR``.
- If no ``SOURCE_SUBDIR`` is given, ``SOURCE_DIR`` is used.
-
- If ``SOURCE_DIR`` is explicitly set to an existing directory the project
- will be built from it. Otherwise a download step must be specified
- using one of the ``DOWNLOAD_COMMAND``, ``CVS_*``, ``SVN_*``, or ``URL``
- options. The ``URL`` option may refer locally to a directory or source
- tarball, or refer to a remote tarball (e.g. ``http://.../src.tgz``).
-
- If ``UPDATE_DISCONNECTED`` is set, the update step is not executed
- automatically when building the main target. The update step can still
- be added as a step target and called manually. This is useful if you
- want to allow one to build the project when you are disconnected from the
- network (you might still need the network for the download step).
- This is disabled by default.
- The directory property ``EP_UPDATE_DISCONNECTED`` can be used to change
- the default value for all the external projects in the current
- directory and its subdirectories.
+ ExternalProject_Add(<name> [<option>...])
+
+ The individual steps within the process can be driven independently if
+ required (e.g. for CDash submission) and extra custom steps can be defined,
+ along with the ability to control the step dependencies. The directory
+ structure used for the management of the external project can also be
+ customized. The function supports a large number of options which can be used
+ to tailor the external project behavior.
+
+ **Directory Options:**
+ Most of the time, the default directory layout is sufficient. It is largely
+ an implementation detail that the main project usually doesn't need to
+ change. In some circumstances, however, control over the directory layout
+ can be useful or necessary. The directory options are potentially more
+ useful from the point of view that the main build can use the
+ :command:`ExternalProject_Get_Property` command to retrieve their values,
+ thereby allowing the main project to refer to build artifacts of the
+ external project.
+
+ ``PREFIX <dir>``
+ Root directory for the external project. Unless otherwise noted below,
+ all other directories associated with the external project will be
+ created under here.
+
+ ``TMP_DIR <dir>``
+ Directory in which to store temporary files.
+
+ ``STAMP_DIR <dir>``
+ Directory in which to store the timestamps of each step. Log files from
+ individual steps are also created in here (see *Logging Options* below).
+
+ ``DOWNLOAD_DIR <dir>``
+ Directory in which to store downloaded files before unpacking them. This
+ directory is only used by the URL download method, all other download
+ methods use ``SOURCE_DIR`` directly instead.
+
+ ``SOURCE_DIR <dir>``
+ Source directory into which downloaded contents will be unpacked, or for
+ non-URL download methods, the directory in which the repository should be
+ checked out, cloned, etc. If no download method is specified, this must
+ point to an existing directory where the external project has already
+ been unpacked or cloned/checked out.
+
+ .. note::
+ If a download method is specified, any existing contents of the source
+ directory may be deleted. Only the URL download method checks whether
+ this directory is either missing or empty before initiating the
+ download, stopping with an error if it is not empty. All other
+ download methods silently discard any previous contents of the source
+ directory.
+
+ ``BINARY_DIR <dir>``
+ Specify the build directory location. This option is ignored if
+ ``BUILD_IN_SOURCE`` is enabled.
+
+ ``INSTALL_DIR <dir>``
+ Installation prefix to be placed in the ``<INSTALL_DIR>`` placeholder.
+ This does not actually configure the external project to install to
+ the given prefix. That must be done by passing appropriate arguments
+ to the external project configuration step, e.g. using ``<INSTALL_DIR>``.
+
+ If any of the above ``..._DIR`` options are not specified, their defaults
+ are computed as follows. If the ``PREFIX`` option is given or the
+ ``EP_PREFIX`` directory property is set, then an external project is built
+ and installed under the specified prefix::
+
+ TMP_DIR = <prefix>/tmp
+ STAMP_DIR = <prefix>/src/<name>-stamp
+ DOWNLOAD_DIR = <prefix>/src
+ SOURCE_DIR = <prefix>/src/<name>
+ BINARY_DIR = <prefix>/src/<name>-build
+ INSTALL_DIR = <prefix>
+
+ Otherwise, if the ``EP_BASE`` directory property is set then components
+ of an external project are stored under the specified base::
+
+ TMP_DIR = <base>/tmp/<name>
+ STAMP_DIR = <base>/Stamp/<name>
+ DOWNLOAD_DIR = <base>/Download/<name>
+ SOURCE_DIR = <base>/Source/<name>
+ BINARY_DIR = <base>/Build/<name>
+ INSTALL_DIR = <base>/Install/<name>
+
+ If no ``PREFIX``, ``EP_PREFIX``, or ``EP_BASE`` is specified, then the
+ default is to set ``PREFIX`` to ``<name>-prefix``. Relative paths are
+ interpreted with respect to :variable:`CMAKE_CURRENT_BINARY_DIR` at the
+ point where ``ExternalProject_Add()`` is called.
+
+ **Download Step Options:**
+ A download method can be omitted if the ``SOURCE_DIR`` option is used to
+ point to an existing non-empty directory. Otherwise, one of the download
+ methods below must be specified (multiple download methods should not be
+ given) or a custom ``DOWNLOAD_COMMAND`` provided.
+
+ ``DOWNLOAD_COMMAND <cmd>...``
+ Overrides the command used for the download step
+ (:manual:`generator expressions <cmake-generator-expressions(7)>` are
+ supported). If this option is specified, all other download options will
+ be ignored. Providing an empty string for ``<cmd>`` effectively disables
+ the download step.
+
+ *URL Download*
+ ``URL <url1> [<url2>...]``
+ List of paths and/or URL(s) of the external project's source. When more
+ than one URL is given, they are tried in turn until one succeeds. A URL
+ may be an ordinary path in the local file system (in which case it
+ must be the only URL provided) or any downloadable URL supported by the
+ :command:`file(DOWNLOAD)` command. A local filesystem path may refer to
+ either an existing directory or to an archive file, whereas a URL is
+ expected to point to a file which can be treated as an archive. When an
+ archive is used, it will be unpacked automatically unless the
+ ``DOWNLOAD_NO_EXTRACT`` option is set to prevent it. The archive type
+ is determined by inspecting the actual content rather than using logic
+ based on the file extension.
+
+ ``URL_HASH ALGO=<value>``
+ Hash of the archive file to be downloaded. The ``<value>`` should be of
+ the form ``algo=hashValue`` where ``algo`` can be any of the hashing
+ algorithms supported by the :command:`file()` command. Specifying this
+ option is strongly recommended for URL downloads, as it ensures the
+ integrity of the downloaded content. It is also used as a check for a
+ previously downloaded file, allowing connection to the remote location
+ to be avoided altogether if the local directory already has a file from
+ an earlier download that matches the specified hash.
+
+ ``URL_MD5 <md5>``
+ Equivalent to ``URL_HASH MD5=<md5>``.
+
+ ``DOWNLOAD_NAME <fname>``
+ File name to use for the downloaded file. If not given, the end of the
+ URL is used to determine the file name. This option is rarely needed,
+ the default name is generally suitable and is not normally used outside
+ of code internal to the ``ExternalProject`` module.
+
+ ``DOWNLOAD_NO_EXTRACT <bool>``
+ Allows the extraction part of the download step to be disabled by
+ passing a boolean true value for this option. If this option is not
+ given, the downloaded contents will be unpacked automatically if
+ required. If extraction has been disabled, the full path to the
+ downloaded file is available as ``<DOWNLOADED_FILE>`` in subsequent
+ steps or as the property ``DOWNLOADED_FILE`` with the
+ :command:`ExternalProject_Get_Property` command.
+
+ ``DOWNLOAD_NO_PROGRESS <bool>``
+ Can be used to disable logging the download progress. If this option is
+ not given, download progress messages will be logged.
+
+ ``TIMEOUT <seconds>``
+ Maximum time allowed for file download operations.
+
+ ``HTTP_USERNAME <username>``
+ Username for the download operation if authentication is required.
+
+ ``HTTP_PASSWORD <password>``
+ Password for the download operation if authentication is required.
+
+ ``HTTP_HEADER <header1> [<header2>...]``
+ Provides an arbitrary list of HTTP headers for the download operation.
+ This can be useful for accessing content in systems like AWS, etc.
+
+ ``TLS_VERIFY <bool>``
+ Specifies whether certificate verification should be performed for
+ https URLs. If this option is not provided, the default behavior is
+ determined by the ``CMAKE_TLS_VERIFY`` variable (see
+ :command:`file(DOWNLOAD)`). If that is also not set, certificate
+ verification will not be performed. In situations where ``URL_HASH``
+ cannot be provided, this option can be an alternative verification
+ measure.
+
+ ``TLS_CAINFO <file>``
+ Specify a custom certificate authority file to use if ``TLS_VERIFY``
+ is enabled. If this option is not specified, the value of the
+ ``CMAKE_TLS_CAINFO`` variable will be used instead (see
+ :command:`file(DOWNLOAD)`)
+
+ *Git*
+ NOTE: A git version of 1.6.5 or later is required if this download method
+ is used.
+
+ ``GIT_REPOSITORY <url>``
+ URL of the git repository. Any URL understood by the ``git`` command
+ may be used.
+
+ ``GIT_TAG <tag>``
+ Git branch name, tag or commit hash. Note that branch names and tags
+ should generally be specified as remote names (i.e. ``origin/myBranch``
+ rather than simply ``myBranch``). This ensures that if the remote end
+ has its tag moved or branch rebased or history rewritten, the local
+ clone will still be updated correctly. In general, however, specifying
+ a commit hash should be preferred for a number of reasons:
+
+ - If the local clone already has the commit corresponding to the hash,
+ no ``git fetch`` needs to be performed to check for changes each time
+ CMake is re-run. This can result in a significant speed up if many
+ external projects are being used.
+ - Using a specific git hash ensures that the main project's own history
+ is fully traceable to a specific point in the external project's
+ evolution. If a branch or tag name is used instead, then checking out
+ a specific commit of the main project doesn't necessarily pin the
+ whole build to a specific point in the life of the external project.
+ The lack of such deterministic behavior makes the main project lose
+ traceability and repeatability.
+
+ ``GIT_REMOTE_NAME <name>``
+ The optional name of the remote. If this option is not specified, it
+ defaults to ``origin``.
+
+ ``GIT_SUBMODULES <module>...``
+ Specific git submodules that should also be updated. If this option is
+ not provided, all git submodules will be updated.
+
+ ``GIT_SHALLOW <bool>``
+ When this option is enabled, the ``git clone`` operation will be given
+ the ``--depth 1`` option. This performs a shallow clone, which avoids
+ downloading the whole history and instead retrieves just the commit
+ denoted by the ``GIT_TAG`` option.
+
+ ``GIT_PROGRESS <bool>``
+ When enabled, this option instructs the ``git clone`` operation to
+ report its progress by passing it the ``--progress`` option. Without
+ this option, the clone step for large projects may appear to make the
+ build stall, since nothing will be logged until the clone operation
+ finishes. While this option can be used to provide progress to prevent
+ the appearance of the build having stalled, it may also make the build
+ overly noisy if lots of external projects are used.
+
+ ``GIT_CONFIG <option1> [<option2>...]``
+ Specify a list of config options to pass to ``git clone``. Each option
+ listed will be transformed into its own ``--config <option>`` on the
+ ``git clone`` command line, with each option required to be in the
+ form ``key=value``.
+
+ *Subversion*
+ ``SVN_REPOSITORY <url>``
+ URL of the Subversion repository.
+
+ ``SVN_REVISION -r<rev>``
+ Revision to checkout from the Subversion repository.
+
+ ``SVN_USERNAME <username>``
+ Username for the Subversion checkout and update.
+
+ ``SVN_PASSWORD <password>``
+ Password for the Subversion checkout and update.
+
+ ``SVN_TRUST_CERT <bool>``
+ Specifies whether to trust the Subversion server site certificate. If
+ enabled, the ``--trust-server-cert`` option is passed to the ``svn``
+ checkout and update commands.
+
+ *Mercurial*
+ ``HG_REPOSITORY <url>``
+ URL of the mercurial repository.
+
+ ``HG_TAG <tag>``
+ Mercurial branch name, tag or commit id.
+
+ *CVS*
+ ``CVS_REPOSITORY <cvsroot>``
+ CVSROOT of the CVS repository.
+
+ ``CVS_MODULE <mod>``
+ Module to checkout from the CVS repository.
+
+ ``CVS_TAG <tag>``
+ Tag to checkout from the CVS repository.
+
+ **Update/Patch Step Options:**
+ Whenever CMake is re-run, by default the external project's sources will be
+ updated if the download method supports updates (e.g. a git repository
+ would be checked if the ``GIT_TAG`` does not refer to a specific commit).
+
+ ``UPDATE_COMMAND <cmd>...``
+ Overrides the download method's update step with a custom command.
+ The command may use
+ :manual:`generator expressions <cmake-generator-expressions(7)>`.
+
+ ``UPDATE_DISCONNECTED <bool>``
+ When enabled, this option causes the update step to be skipped. It does
+ not, however, prevent the download step. The update step can still be
+ added as a step target (see :command:`ExternalProject_Add_StepTargets`)
+ and called manually. This is useful if you want to allow developers to
+ build the project when disconnected from the network (the network may
+ still be needed for the download step though).
+
+ When this option is present, it is generally advisable to make the value
+ a cache variable under the developer's control rather than hard-coding
+ it. If this option is not present, the default value is taken from the
+ ``EP_UPDATE_DISCONNECTED`` directory property. If that is also not
+ defined, updates are performed as normal. The ``EP_UPDATE_DISCONNECTED``
+ directory property is intended as a convenience for controlling the
+ ``UPDATE_DISCONNECTED`` behavior for an entire section of a project's
+ directory hierarchy and may be a more convenient method of giving
+ developers control over whether or not to perform updates (assuming the
+ project also provides a cache variable or some other convenient method
+ for setting the directory property).
+
+ ``PATCH_COMMAND <cmd>...``
+ Specifies a custom command to patch the sources after an update. By
+ default, no patch command is defined. Note that it can be quite difficult
+ to define an appropriate patch command that performs robustly, especially
+ for download methods such as git where changing the ``GIT_TAG`` will not
+ discard changes from a previous patch, but the patch command will be
+ called again after updating to the new tag.
+
+ **Configure Step Options:**
+ The configure step is run after the download and update steps. By default,
+ the external project is assumed to be a CMake project, but this can be
+ overridden if required.
+
+ ``CONFIGURE_COMMAND <cmd>...``
+ The default configure command runs CMake with options based on the main
+ project. For non-CMake external projects, the ``CONFIGURE_COMMAND``
+ option must be used to override this behavior
+ (:manual:`generator expressions <cmake-generator-expressions(7)>` are
+ supported). For projects that require no configure step, specify this
+ option with an empty string as the command to execute.
+
+ ``CMAKE_COMMAND /.../cmake``
+ Specify an alternative cmake executable for the configure step (use an
+ absolute path). This is generally not recommended, since it is
+ usually desirable to use the same CMake version throughout the whole
+ build. This option is ignored if a custom configure command has been
+ specified with ``CONFIGURE_COMMAND``.
+
+ ``CMAKE_GENERATOR <gen>``
+ Override the CMake generator used for the configure step. Without this
+ option, the same generator as the main build will be used. This option is
+ ignored if a custom configure command has been specified with the
+ ``CONFIGURE_COMMAND`` option.
+
+ ``CMAKE_GENERATOR_PLATFORM <platform>``
+ Pass a generator-specific platform name to the CMake command (see
+ :variable:`CMAKE_GENERATOR_PLATFORM`). It is an error to provide this
+ option without the ``CMAKE_GENERATOR`` option.
+
+ ``CMAKE_GENERATOR_TOOLSET <toolset>``
+ Pass a generator-specific toolset name to the CMake command (see
+ :variable:`CMAKE_GENERATOR_TOOLSET`). It is an error to provide this
+ option without the ``CMAKE_GENERATOR`` option.
+
+ ``CMAKE_ARGS <arg>...``
+ The specified arguments are passed to the ``cmake`` command line. They
+ can be any argument the ``cmake`` command understands, not just cache
+ values defined by ``-D...`` arguments (see also
+ :manual:`CMake Options <cmake(1)>`). In addition, arguments may use
+ :manual:`generator expressions <cmake-generator-expressions(7)>`.
+
+ ``CMAKE_CACHE_ARGS <arg>...``
+ This is an alternate way of specifying cache variables where command line
+ length issues may become a problem. The arguments are expected to be in
+ the form ``-Dvar:STRING=value``, which are then transformed into
+ CMake :command:`set` commands with the ``FORCE`` option used. These
+ ``set()`` commands are written to a pre-load script which is then applied
+ using the :manual:`cmake -C <cmake(1)>` command line option. Arguments
+ may use :manual:`generator expressions <cmake-generator-expressions(7)>`.
+
+ ``CMAKE_CACHE_DEFAULT_ARGS <arg>...``
+ This is the same as the ``CMAKE_CACHE_ARGS`` option except the ``set()``
+ commands do not include the ``FORCE`` keyword. This means the values act
+ as initial defaults only and will not override any variables already set
+ from a previous run. Use this option with care, as it can lead to
+ different behavior depending on whether the build starts from a fresh
+ build directory or re-uses previous build contents.
+
+ ``SOURCE_SUBDIR <dir>``
+ When no ``CONFIGURE_COMMAND`` option is specified, the configure step
+ assumes the external project has a ``CMakeLists.txt`` file at the top of
+ its source tree (i.e. in ``SOURCE_DIR``). The ``SOURCE_SUBDIR`` option
+ can be used to point to an alternative directory within the source tree
+ to use as the top of the CMake source tree instead. This must be a
+ relative path and it will be interpreted as being relative to
+ ``SOURCE_DIR``.
+
+ **Build Step Options:**
+ If the configure step assumed the external project uses CMake as its build
+ system, the build step will also. Otherwise, the build step will assume a
+ Makefile-based build and simply run ``make`` with no arguments as the
+ default build step. This can be overridden with custom build commands if
+ required.
+
+ ``BUILD_COMMAND <cmd>...``
+ Overrides the default build command
+ (:manual:`generator expressions <cmake-generator-expressions(7)>` are
+ supported). If this option is not given, the default build command will
+ be chosen to integrate with the main build in the most appropriate way
+ (e.g. using recursive ``make`` for Makefile generators or
+ ``cmake --build`` if the project uses a CMake build). This option can be
+ specified with an empty string as the command to make the build step do
+ nothing.
+
+ ``BUILD_IN_SOURCE <bool>``
+ When this option is enabled, the build will be done directly within the
+ external project's source tree. This should generally be avoided, the use
+ of a separate build directory is usually preferred, but it can be useful
+ when the external project assumes an in-source build. The ``BINARY_DIR``
+ option should not be specified if building in-source.
+
+ ``BUILD_ALWAYS <bool>``
+ Enabling this option forces the build step to always be run. This can be
+ the easiest way to robustly ensure that the external project's own build
+ dependencies are evaluated rather than relying on the default
+ success timestamp-based method. This option is not normally needed unless
+ developers are expected to modify something the external project's build
+ depends on in a way that is not detectable via the step target
+ dependencies (e.g. ``SOURCE_DIR`` is used without a download method and
+ developers might modify the sources in ``SOURCE_DIR``).
+
+ ``BUILD_BYPRODUCTS <file>...``
+ Specifies files that will be generated by the build command but which
+ might or might not have their modification time updated by subsequent
+ builds. These ultimately get passed through as ``BYPRODUCTS`` to the
+ build step's own underlying call to :command:`add_custom_command`.
+
+ **Install Step Options:**
+ If the configure step assumed the external project uses CMake as its build
+ system, the install step will also. Otherwise, the install step will assume
+ a Makefile-based build and simply run ``make install`` as the default build
+ step. This can be overridden with custom install commands if required.
+
+ ``INSTALL_COMMAND <cmd>...``
+ The external project's own install step is invoked as part of the main
+ project's *build*. It is done after the external project's build step
+ and may be before or after the external project's test step (see the
+ ``TEST_BEFORE_INSTALL`` option below). The external project's install
+ rules are not part of the main project's install rules, so if anything
+ from the external project should be installed as part of the main build,
+ these need to be specified in the main build as additional
+ :command:`install` commands. The default install step builds the
+ ``install`` target of the external project, but this can be overridden
+ with a custom command using this option
+ (:manual:`generator expressions <cmake-generator-expressions(7)>` are
+ supported). Passing an empty string as the ``<cmd>`` makes the install
+ step do nothing.
+
+ **Test Step Options:**
+ The test step is only defined if at least one of the following ``TEST_...``
+ options are provided.
+
+ ``TEST_COMMAND <cmd>...``
+ Overrides the default test command
+ (:manual:`generator expressions <cmake-generator-expressions(7)>` are
+ supported). If this option is not given, the default behavior of the test
+ step is to build the external project's own ``test`` target. This option
+ can be specified with ``<cmd>`` as an empty string, which allows the test
+ step to still be defined, but it will do nothing. Do not specify any of
+ the other ``TEST_...`` options if providing an empty string as the test
+ command, but prefer to omit all ``TEST_...`` options altogether if the
+ test step target is not needed.
+
+ ``TEST_BEFORE_INSTALL <bool>``
+ When this option is enabled, the test step will be executed before the
+ install step. The default behavior is for the test step to run after the
+ install step.
+
+ ``TEST_AFTER_INSTALL <bool>``
+ This option is mainly useful as a way to indicate that the test step is
+ desired but all default behavior is sufficient. Specifying this option
+ with a boolean true value ensures the test step is defined and that it
+ comes after the install step. If both ``TEST_BEFORE_INSTALL`` and
+ ``TEST_AFTER_INSTALL`` are enabled, the latter is silently ignored.
+
+ ``TEST_EXCLUDE_FROM_MAIN <bool>``
+ If enabled, the main build's default ALL target will not depend on the
+ test step. This can be a useful way of ensuring the test step is defined
+ but only gets invoked when manually requested.
+
+ **Output Logging Options:**
+ Each of the following ``LOG_...`` options can be used to wrap the relevant
+ step in a script to capture its output to files. The log files will be
+ created in the ``STAMP_DIR`` directory with step-specific file names.
+
+ ``LOG_DOWNLOAD <bool>``
+ When enabled, the output of the download step is logged to files.
+
+ ``LOG_UPDATE <bool>``
+ When enabled, the output of the update step is logged to files.
+
+ ``LOG_CONFIGURE <bool>``
+ When enabled, the output of the configure step is logged to files.
+
+ ``LOG_BUILD <bool>``
+ When enabled, the output of the build step is logged to files.
+
+ ``LOG_INSTALL <bool>``
+ When enabled, the output of the install step is logged to files.
+
+ ``LOG_TEST <bool>``
+ When enabled, the output of the test step is logged to files.
+
+ **Terminal Access Options:**
+ Steps can be given direct access to the terminal in some cases. Giving a
+ step access to the terminal may allow it to receive terminal input if
+ required, such as for authentication details not provided by other options.
+ With the :generator:`Ninja` generator, these options place the steps in the
+ ``console`` :prop_gbl:`job pool <JOB_POOLS>`. Each step can be given access
+ to the terminal individually via the following options:
+
+ ``USES_TERMINAL_DOWNLOAD <bool>``
+ Give the download step access to the terminal.
+
+ ``USES_TERMINAL_UPDATE <bool>``
+ Give the update step access to the terminal.
+
+ ``USES_TERMINAL_CONFIGURE <bool>``
+ Give the configure step access to the terminal.
+
+ ``USES_TERMINAL_BUILD <bool>``
+ Give the build step access to the terminal.
+
+ ``USES_TERMINAL_INSTALL <bool>``
+ Give the install step access to the terminal.
+
+ ``USES_TERMINAL_TEST <bool>``
+ Give the test step access to the terminal.
+
+ **Target Options:**
+ ``DEPENDS <targets>...``
+ Specify other targets on which the external project depends. The other
+ targets will be brought up to date before any of the external project's
+ steps are executed. Because the external project uses additional custom
+ targets internally for each step, the ``DEPENDS`` option is the most
+ convenient way to ensure all of those steps depend on the other targets.
+ Simply doing
+ :command:`add_dependencies(\<name\> \<targets\>) <add_dependencies>` will
+ not make any of the steps dependent on ``<targets>``.
+
+ ``EXCLUDE_FROM_ALL <bool>``
+ When enabled, this option excludes the external project from the default
+ ALL target of the main build.
+
+ ``STEP_TARGETS <step-target>...``
+ Generate custom targets for the specified steps. This is required if the
+ steps need to be triggered manually or if they need to be used as
+ dependencies of other targets. If this option is not specified, the
+ default value is taken from the ``EP_STEP_TARGETS`` directory property.
+ See :command:`ExternalProject_Add_Step` below for further discussion of
+ the effects of this option.
+
+ ``INDEPENDENT_STEP_TARGETS <step-target>...``
+ Generate custom targets for the specified steps and prevent these targets
+ from having the usual dependencies applied to them. If this option is not
+ specified, the default value is taken from the
+ ``EP_INDEPENDENT_STEP_TARGETS`` directory property. This option is mostly
+ useful for allowing individual steps to be driven independently, such as
+ for a CDash setup where each step should be initiated and reported
+ individually rather than as one whole build. See
+ :command:`ExternalProject_Add_Step` below for further discussion of the
+ effects of this option.
+
+ **Miscellaneous Options:**
+ ``LIST_SEPARATOR <sep>``
+ For any of the various ``..._COMMAND`` options, replace ``;`` with
+ ``<sep>`` in the specified command lines. This can be useful where list
+ variables may be given in commands where they should end up as
+ space-separated arguments (``<sep>`` would be a single space character
+ string in this case).
+
+ ``COMMAND <cmd>...``
+ Any of the other ``..._COMMAND`` options can have additional commands
+ appended to them by following them with as many ``COMMAND ...`` options
+ as needed
+ (:manual:`generator expressions <cmake-generator-expressions(7)>` are
+ supported). For example::
+
+ ExternalProject_Add(example
+ ... # Download options, etc.
+ BUILD_COMMAND ${CMAKE_COMMAND} -E echo "Starting $<CONFIG> build"
+ COMMAND ${CMAKE_COMMAND} --build <BINARY_DIR> --config $<CONFIG>
+ COMMAND ${CMAKE_COMMAND} -E echo "$<CONFIG> build complete"
+ )
+
+ It should also be noted that each build step is created via a call to
+ :command:`ExternalProject_Add_Step`. See that command's documentation for the
+ automatic substitutions that are supported for some options.
+
+Obtaining Project Properties
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. command:: ExternalProject_Get_Property
+
+ The ``ExternalProject_Get_Property()`` function retrieves external project
+ target properties::
+
+ ExternalProject_Get_Property(<name> <prop1> [<prop2>...])
+
+ The function stores property values in variables of the same name. Property
+ names correspond to the keyword argument names of ``ExternalProject_Add()``.
+ For example, the source directory might be retrieved like so:
+
+ .. code-block:: cmake
+
+ ExternalProject_Get_property(myExtProj SOURCE_DIR)
+ message("Source dir of myExtProj = ${SOURCE_DIR}")
+
+Explicit Step Management
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+The ``ExternalProject_Add()`` function on its own is often sufficient for
+incorporating an external project into the main build. Certain scenarios
+require additional work to implement desired behavior, such as adding in a
+custom step or making steps available as manually triggerable targets. The
+``ExternalProject_Add_Step()``, ``ExternalProject_Add_StepTargets()`` and
+``ExternalProject_Add_StepDependencies`` functions provide the lower level
+control needed to implement such step-level capabilities.
.. command:: ExternalProject_Add_Step
- The ``ExternalProject_Add_Step`` function adds a custom step to an
- external project::
+ The ``ExternalProject_Add_Step()`` function specifies an additional custom
+ step for an external project defined by an earlier call to
+ :command:`ExternalProject_Add`::
- ExternalProject_Add_Step(<name> <step> [<option>...])
+ ExternalProject_Add_Step(<name> <step> [<option>...])
- Options are:
+ ``<name>`` is the same as the name passed to the original call to
+ :command:`ExternalProject_Add`. The specified ``<step>`` must not be one of
+ the pre-defined steps (``mkdir``, ``download``, ``update``, ``skip-update``,
+ ``patch``, ``configure``, ``build``, ``install`` or ``test``). The supported
+ options are:
``COMMAND <cmd>...``
- Command line invoked by this step
+ The command line to be executed by this custom step
+ (:manual:`generator expressions <cmake-generator-expressions(7)>` are
+ supported). This option can be repeated multiple times to specify multiple
+ commands to be executed in order.
+
``COMMENT "<text>..."``
- Text printed when step executes
+ Text to be printed when the custom step executes.
+
``DEPENDEES <step>...``
- Steps on which this step depends
+ Other steps (custom or pre-defined) on which this step depends.
+
``DEPENDERS <step>...``
- Steps that depend on this step
+ Other steps (custom or pre-defined) that depend on this new custom step.
+
``DEPENDS <file>...``
- Files on which this step depends
+ Files on which this custom step depends.
+
``BYPRODUCTS <file>...``
- Files that will be generated by this step but may or may not
- have their modification time updated by subsequent builds.
- ``ALWAYS 1``
- No stamp file, step always runs
- ``EXCLUDE_FROM_MAIN 1``
- Main target does not depend on this step
+ Files that will be generated by this custom step but which might or might
+ not have their modification time updated by subsequent builds. This list of
+ files will ultimately be passed through as the ``BYPRODUCTS`` option to the
+ :command:`add_custom_command` used to implement the custom step internally.
+
+ ``ALWAYS <bool>``
+ When enabled, this option specifies that the custom step should always be
+ run (i.e. that it is always considered out of date).
+
+ ``EXCLUDE_FROM_MAIN <bool>``
+ When enabled, this option specifies that the external project's main target
+ does not depend on the custom step.
+
``WORKING_DIRECTORY <dir>``
- Working directory for command
- ``LOG 1``
- Wrap step in script to log output
- ``USES_TERMINAL 1``
- Give the step direct access to the terminal if possible.
+ Specifies the working directory to set before running the custom step's
+ command. If this option is not specified, the directory will be the value
+ of the :variable:`CMAKE_CURRENT_BINARY_DIR` at the point where
+ ``ExternalProject_Add_Step()`` was called.
- The command line, comment, working directory, and byproducts of every
- standard and custom step are processed to replace tokens ``<SOURCE_DIR>``,
- ``<SOURCE_SUBDIR>``, ``<BINARY_DIR>``, ``<INSTALL_DIR>``, and ``<TMP_DIR>``
- with corresponding property values.
+ ``LOG <bool>``
+ If set, this causes the output from the custom step to be captured to files
+ in the external project's ``STAMP_DIR``.
-Any builtin step that specifies a ``<step>_COMMAND cmd...`` or custom
-step that specifies a ``COMMAND cmd...`` may specify additional command
-lines using the form ``COMMAND cmd...``. At build time the commands
-will be executed in order and aborted if any one fails. For example::
+ ``USES_TERMINAL <bool>``
+ If enabled, this gives the custom step direct access to the terminal if
+ possible.
- ... BUILD_COMMAND make COMMAND echo done ...
+ The command line, comment, working directory and byproducts of every
+ standard and custom step are processed to replace the tokens
+ ``<SOURCE_DIR>``, ``<SOURCE_SUBDIR>``, ``<BINARY_DIR>``, ``<INSTALL_DIR>``
+ and ``<TMP_DIR>`` with their corresponding property values defined in the
+ original call to :command:`ExternalProject_Add`.
-specifies to run ``make`` and then ``echo done`` during the build step.
-Whether the current working directory is preserved between commands is
-not defined. Behavior of shell operators like ``&&`` is not defined.
+.. command:: ExternalProject_Add_StepTargets
-Arguments to ``<step>_COMMAND`` or ``COMMAND`` options may use
-:manual:`generator expressions <cmake-generator-expressions(7)>`.
+ The ``ExternalProject_Add_StepTargets()`` function generates targets for the
+ steps listed. The name of each created target will be of the form
+ ``<name>-<step>``::
+
+ ExternalProject_Add_StepTargets(<name> [NO_DEPENDS] <step1> [<step2>...])
+
+ Creating a target for a step allows it to be used as a dependency of another
+ target or to be triggered manually. Having targets for specific steps also
+ allows them to be driven independently of each other by specifying targets on
+ build command lines. For example, you may be submitting to a sub-project
+ based dashboard where you want to drive the configure portion of the build,
+ then submit to the dashboard, followed by the build portion, followed
+ by tests. If you invoke a custom target that depends on a step halfway
+ through the step dependency chain, then all the previous steps will also run
+ to ensure everything is up to date.
+
+ If the ``NO_DEPENDS`` option is specified, the step target will not depend on
+ the dependencies of the external project (i.e. on any dependencies of the
+ ``<name>`` custom target created by :command:`ExternalProject_Add`). This is
+ usually safe for the ``download``, ``update`` and ``patch`` steps, since they
+ do not typically require that the dependencies are updated and built. Using
+ ``NO_DEPENDS`` for any of the other pre-defined steps, however, may break
+ parallel builds. Only use ``NO_DEPENDS`` where it is certain that the named
+ steps genuinely do not have dependencies. For custom steps, consider whether
+ or not the custom commands require the dependencies to be configured, built
+ and installed.
+
+ Internally, :command:`ExternalProject_Add` calls
+ :command:`ExternalProject_Add_Step` to create each step. If any
+ ``STEP_TARGETS`` or ``INDEPENDENT_STEP_TARGETS`` were specified, then
+ ``ExternalProject_Add_StepTargets()`` will also be called after
+ :command:`ExternalProject_Add_Step`. ``INDEPENDENT_STEP_TARGETS`` have the
+ ``NO_DEPENDS`` option set, whereas ``STEP_TARGETS`` do not. Other than that,
+ the two options result in ``ExternalProject_Add_StepTargets()`` being called
+ in the same way. Even if a step is not mentioned in either of those two
+ options, ``ExternalProject_Add_StepTargets()`` can still be called later to
+ manually define a target for the step.
+
+ The ``STEP_TARGETS`` and ``INDEPENDENT_STEP_TARGETS`` options for
+ :command:`ExternalProject_Add` are generally the easiest way to ensure
+ targets are created for specific steps of interest. For custom steps,
+ ``ExternalProject_Add_StepTargets()`` must be called explicitly if a target
+ should also be created for that custom step. An alternative to these two
+ options is to populate the ``EP_STEP_TARGETS`` and
+ ``EP_INDEPENDENT_STEP_TARGETS`` directory properties. These act as defaults
+ for the step target options and can save having to repeatedly specify the
+ same set of step targets when multiple external projects are being defined.
-.. command:: ExternalProject_Get_Property
+.. command:: ExternalProject_Add_StepDependencies
- The ``ExternalProject_Get_Property`` function retrieves external project
- target properties::
+ The ``ExternalProject_Add_StepDependencies()`` function can be used to add
+ dependencies to a step. The dependencies added must be targets CMake already
+ knows about (these can be ordinary executable or library targets, custom
+ targets or even step targets of another external project)::
- ExternalProject_Get_Property(<name> [prop1 [prop2 [...]]])
+ ExternalProject_Add_StepDependencies(<name> <step> <target1> [<target2>...])
- It stores property values in variables of the same name. Property
- names correspond to the keyword argument names of
- ``ExternalProject_Add``.
+ This function takes care to set both target and file level dependencies and
+ will ensure that parallel builds will not break. It should be used instead of
+ :command:`add_dependencies` whenever adding a dependency for some of the step
+ targets generated by the ``ExternalProject`` module.
-.. command:: ExternalProject_Add_StepTargets
+Examples
+^^^^^^^^
- The ``ExternalProject_Add_StepTargets`` function generates custom
- targets for the steps listed::
-
- ExternalProject_Add_StepTargets(<name> [NO_DEPENDS] [step1 [step2 [...]]])
-
-If ``NO_DEPENDS`` is set, the target will not depend on the
-dependencies of the complete project. This is usually safe to use for
-the download, update, and patch steps that do not require that all the
-dependencies are updated and built. Using ``NO_DEPENDS`` for other
-of the default steps might break parallel builds, so you should avoid,
-it. For custom steps, you should consider whether or not the custom
-commands requires that the dependencies are configured, built and
-installed.
-
-If ``STEP_TARGETS`` or ``INDEPENDENT_STEP_TARGETS`` is set then
-``ExternalProject_Add_StepTargets`` is automatically called at the end
-of matching calls to ``ExternalProject_Add_Step``. Pass
-``STEP_TARGETS`` or ``INDEPENDENT_STEP_TARGETS`` explicitly to
-individual ``ExternalProject_Add`` calls, or implicitly to all
-``ExternalProject_Add`` calls by setting the directory properties
-``EP_STEP_TARGETS`` and ``EP_INDEPENDENT_STEP_TARGETS``. The
-``INDEPENDENT`` version of the argument and of the property will call
-``ExternalProject_Add_StepTargets`` with the ``NO_DEPENDS`` argument.
-
-If ``STEP_TARGETS`` and ``INDEPENDENT_STEP_TARGETS`` are not set,
-clients may still manually call ``ExternalProject_Add_StepTargets``
-after calling ``ExternalProject_Add`` or ``ExternalProject_Add_Step``.
-
-This functionality is provided to make it easy to drive the steps
-independently of each other by specifying targets on build command
-lines. For example, you may be submitting to a sub-project based
-dashboard, where you want to drive the configure portion of the build,
-then submit to the dashboard, followed by the build portion, followed
-by tests. If you invoke a custom target that depends on a step
-halfway through the step dependency chain, then all the previous steps
-will also run to ensure everything is up to date.
-
-For example, to drive configure, build and test steps independently
-for each ``ExternalProject_Add`` call in your project, write the following
-line prior to any ``ExternalProject_Add`` calls in your ``CMakeLists.txt``
-file::
-
- set_property(DIRECTORY PROPERTY EP_STEP_TARGETS configure build test)
+The following example shows how to download and build a hypothetical project
+called *FooBar* from github:
-.. command:: ExternalProject_Add_StepDependencies
+.. code-block:: cmake
+
+ include(ExternalProject)
+ ExternalProject_Add(foobar
+ GIT_REPOSITORY git@github.com:FooCo/FooBar.git
+ GIT_TAG origin/release/1.2.3
+ )
- The ``ExternalProject_Add_StepDependencies`` function add some
- dependencies for some external project step::
+For the sake of the example, also define a second hypothetical external project
+called *SecretSauce*, which is downloaded from a web server. Two URLs are given
+to take advantage of a faster internal network if available, with a fallback to
+a slower external server. The project is a typical ``Makefile`` project with no
+configure step, so some of the default commands are overridden. The build is
+only required to build the *sauce* target:
+
+.. code-block:: cmake
+
+ find_program(MAKE_EXE NAMES gmake nmake make)
+ ExternalProject_Add(secretsauce
+ URL http://intranet.somecompany.com/artifacts/sauce-2.7.tgz
+ https://www.somecompany.com/downloads/sauce-2.7.zip
+ URL_HASH MD5=d41d8cd98f00b204e9800998ecf8427e
+ CONFIGURE_COMMAND ""
+ BUILD_COMMAND ${MAKE_EXE} sauce
+ )
+
+Suppose the build step of ``secretsauce`` requires that ``foobar`` must already
+be built. This could be enforced like so:
+
+.. code-block:: cmake
+
+ ExternalProject_Add_StepDependencies(secretsauce build foobar)
+
+Another alternative would be to create a custom target for ``foobar``'s build
+step and make ``secretsauce`` depend on that rather than the whole ``foobar``
+project. This would mean ``foobar`` only needs to be built, it doesn't need to
+run its install or test steps before ``secretsauce`` can be built. The
+dependency can also be defined along with the ``secretsauce`` project:
+
+.. code-block:: cmake
+
+ ExternalProject_Add_StepTargets(foobar build)
+ ExternalProject_Add(secretsauce
+ URL http://intranet.somecompany.com/artifacts/sauce-2.7.tgz
+ https://www.somecompany.com/downloads/sauce-2.7.zip
+ URL_HASH MD5=d41d8cd98f00b204e9800998ecf8427e
+ CONFIGURE_COMMAND ""
+ BUILD_COMMAND ${MAKE_EXE} sauce
+ DEPENDS foobar-build
+ )
+
+Instead of calling :command:`ExternalProject_Add_StepTargets`, the target could
+be defined along with the ``foobar`` project itself:
+
+.. code-block:: cmake
+
+ ExternalProject_Add(foobar
+ GIT_REPOSITORY git@github.com:FooCo/FooBar.git
+ GIT_TAG origin/release/1.2.3
+ STEP_TARGETS build
+ )
+
+If many external projects should have the same set of step targets, setting a
+directory property may be more convenient. The ``build`` step target could be
+created automatically by setting the ``EP_STEP_TARGETS`` directory property
+before creating the external projects with :command:`ExternalProject_Add`:
+
+.. code-block:: cmake
+
+ set_property(DIRECTORY PROPERTY EP_STEP_TARGETS build)
+
+Lastly, suppose that ``secretsauce`` provides a script called ``makedoc`` which
+can be used to generate its own documentation. Further suppose that the script
+expects the output directory to be provided as the only parameter and that it
+should be run from the ``secretsauce`` source directory. A custom step and a
+custom target to trigger the script can be defined like so:
- ExternalProject_Add_StepDependencies(<name> <step> [target1 [target2 [...]]])
+.. code-block:: cmake
+
+ ExternalProject_Add_Step(secretsauce docs
+ COMMAND <SOURCE_DIR>/makedoc <BINARY_DIR>
+ WORKING_DIRECTORY <SOURCE_DIR>
+ COMMENT "Building secretsauce docs"
+ ALWAYS TRUE
+ EXCLUDE_FROM_MAIN TRUE
+ )
+ ExternalProject_Add_StepTargets(secretsauce docs)
+
+The custom step could then be triggered from the main build like so::
+
+ cmake --build . --target secretsauce-docs
- This function takes care to set both target and file level
- dependencies, and will ensure that parallel builds will not break.
- It should be used instead of :command:`add_dependencies()` when adding
- a dependency for some of the step targets generated by
- ``ExternalProject``.
#]=======================================================================]
+cmake_policy(PUSH)
+cmake_policy(SET CMP0054 NEW) # if() quoted variables not dereferenced
+
# Pre-compute a regex to match documented keywords for each command.
-math(EXPR _ep_documentation_line_count "${CMAKE_CURRENT_LIST_LINE} - 16")
+math(EXPR _ep_documentation_line_count "${CMAKE_CURRENT_LIST_LINE} - 4")
file(STRINGS "${CMAKE_CURRENT_LIST_FILE}" lines
LIMIT_COUNT ${_ep_documentation_line_count}
- REGEX "^\\.\\. command:: [A-Za-z0-9_]+|^ ``[A-Z0-9_]+ .*``$")
+ REGEX "^\\.\\. command:: [A-Za-z0-9_]+|^ +``[A-Z0-9_]+ [^`]*``$")
foreach(line IN LISTS lines)
if("${line}" MATCHES "^\\.\\. command:: ([A-Za-z0-9_]+)")
if(_ep_func)
@@ -421,8 +871,16 @@ foreach(line IN LISTS lines)
#message("function [${_ep_func}]")
set(_ep_keywords_${_ep_func} "^(")
set(_ep_keyword_sep)
- elseif("${line}" MATCHES "^ ``([A-Z0-9_]+) .*``$")
+ elseif("${line}" MATCHES "^ +``([A-Z0-9_]+) [^`]*``$")
set(_ep_key "${CMAKE_MATCH_1}")
+ # COMMAND should never be included as a keyword,
+ # for ExternalProject_Add(), as it is treated as a
+ # special case by argument parsing as an extension
+ # of a previous ..._COMMAND
+ if("x${_ep_key}x" STREQUAL "xCOMMANDx" AND
+ "x${_ep_func}x" STREQUAL "xExternalProject_Addx")
+ continue()
+ endif()
#message(" keyword [${_ep_key}]")
string(APPEND _ep_keywords_${_ep_func}
"${_ep_keyword_sep}${_ep_key}")
@@ -504,7 +962,7 @@ define_property(DIRECTORY PROPERTY "EP_STEP_TARGETS" INHERITED
BRIEF_DOCS
"List of ExternalProject steps that automatically get corresponding targets"
FULL_DOCS
- "These targets will be dependent on the main target dependencies"
+ "These targets will be dependent on the main target dependencies. "
"See documentation of the ExternalProject_Add_StepTargets() function in the "
"ExternalProject module."
)
@@ -513,7 +971,7 @@ define_property(DIRECTORY PROPERTY "EP_INDEPENDENT_STEP_TARGETS" INHERITED
BRIEF_DOCS
"List of ExternalProject steps that automatically get corresponding targets"
FULL_DOCS
- "These targets will not be dependent on the main target dependencies"
+ "These targets will not be dependent on the main target dependencies. "
"See documentation of the ExternalProject_Add_StepTargets() function in the "
"ExternalProject module."
)
@@ -1468,6 +1926,15 @@ function(_ep_get_step_stampfile name step stampfile_var)
endfunction()
+function(_ep_get_complete_stampfile name stampfile_var)
+ set(cmf_dir ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles)
+ _ep_get_configuration_subdir_suffix(cfgdir)
+ set(stampfile "${cmf_dir}${cfgdir}/${name}-complete")
+
+ set(${stampfile_var} ${stampfile} PARENT_SCOPE)
+endfunction()
+
+
function(ExternalProject_Add_StepTargets name)
set(steps ${ARGN})
if(ARGC GREATER 1 AND "${ARGV1}" STREQUAL "NO_DEPENDS")
@@ -1497,10 +1964,7 @@ endfunction()
function(ExternalProject_Add_Step name step)
- set(cmf_dir ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles)
- _ep_get_configuration_subdir_suffix(cfgdir)
-
- set(complete_stamp_file "${cmf_dir}${cfgdir}/${name}-complete")
+ _ep_get_complete_stampfile(${name} complete_stamp_file)
_ep_get_step_stampfile(${name} ${step} stamp_file)
_ep_parse_arguments(ExternalProject_Add_Step
@@ -2012,12 +2476,12 @@ function(_ep_add_download_command name)
" ${source_dir}\n"
"is not an existing non-empty directory. Please specify one of:\n"
" * SOURCE_DIR with an existing non-empty directory\n"
+ " * DOWNLOAD_COMMAND\n"
" * URL\n"
" * GIT_REPOSITORY\n"
+ " * SVN_REPOSITORY\n"
" * HG_REPOSITORY\n"
- " * CVS_REPOSITORY and CVS_MODULE\n"
- " * SVN_REVISION\n"
- " * DOWNLOAD_COMMAND"
+ " * CVS_REPOSITORY and CVS_MODULE"
)
endif()
endif()
@@ -2503,7 +2967,7 @@ function(ExternalProject_Add name)
# Add a custom target for the external project.
set(cmf_dir ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles)
- set(complete_stamp_file "${cmf_dir}${cfgdir}/${name}-complete")
+ _ep_get_complete_stampfile(${name} complete_stamp_file)
# The "ALL" option to add_custom_target just tells it to not set the
# EXCLUDE_FROM_ALL target property. Later, if the EXCLUDE_FROM_ALL
@@ -2574,3 +3038,5 @@ function(ExternalProject_Add name)
#
_ep_add_test_command(${name})
endfunction()
+
+cmake_policy(POP)
diff --git a/Modules/FindBoost.cmake b/Modules/FindBoost.cmake
index 6d7cc27f4..88d14abd2 100644
--- a/Modules/FindBoost.cmake
+++ b/Modules/FindBoost.cmake
@@ -76,7 +76,7 @@
# Boost::system will be automatically detected and satisfied, even
# if system is not specified when using find_package and if
# Boost::system is not added to target_link_libraries. If using
-# Boost::thread, then Thread::Thread will also be added automatically.
+# Boost::thread, then Threads::Threads will also be added automatically.
#
# It is important to note that the imported targets behave differently
# than variables created by this module: multiple calls to
@@ -107,6 +107,10 @@
# Users or projects may tell this module which variant to find by
# setting variables::
#
+# Boost_USE_DEBUG_LIBS - Set to ON or OFF to specify whether to search
+# and use the debug libraries. Default is ON.
+# Boost_USE_RELEASE_LIBS - Set to ON or OFF to specify whether to search
+# and use the release libraries. Default is ON.
# Boost_USE_MULTITHREADED - Set to OFF to use the non-multithreaded
# libraries ('mt' tag). Default is ON.
# Boost_USE_STATIC_LIBS - Set to ON to force the use of the static
@@ -183,9 +187,11 @@
# target_link_libraries(foo Boost::date_time Boost::filesystem
# Boost::iostreams)
#
-# Example to find Boost headers and some *static* libraries::
+# Example to find Boost headers and some *static* (release only) libraries::
#
-# set(Boost_USE_STATIC_LIBS ON) # only find static libs
+# set(Boost_USE_STATIC_LIBS ON) # only find static libs
+# set(Boost_USE_DEBUG_LIBS OFF) # ignore debug libs and
+# set(Boost_USE_RELEASE_LIBS ON) # only find release libs
# set(Boost_USE_MULTITHREADED ON)
# set(Boost_USE_STATIC_RUNTIME OFF)
# find_package(Boost 1.36.0 COMPONENTS date_time filesystem system ...)
@@ -208,6 +214,10 @@
#
# Set Boost_NO_BOOST_CMAKE to ON to disable the search for boost-cmake.
+# Save project's policies
+cmake_policy(PUSH)
+cmake_policy(SET CMP0057 NEW) # if IN_LIST
+
#-------------------------------------------------------------------------------
# Before we go searching, check whether boost-cmake is available, unless the
# user specifically asked NOT to search for boost-cmake.
@@ -235,11 +245,12 @@ if (NOT Boost_NO_BOOST_CMAKE)
# If we found boost-cmake, then we're done. Print out what we found.
# Otherwise let the rest of the module try to find it.
if (Boost_FOUND)
- message("Boost ${Boost_FIND_VERSION} found.")
+ message(STATUS "Boost ${Boost_FIND_VERSION} found.")
if (Boost_FIND_COMPONENTS)
- message("Found Boost components:")
- message(" ${Boost_FIND_COMPONENTS}")
+ message(STATUS "Found Boost components:\n ${Boost_FIND_COMPONENTS}")
endif()
+ # Restore project's policies
+ cmake_policy(POP)
return()
endif()
endif()
@@ -292,13 +303,17 @@ macro(_Boost_ADJUST_LIB_VARS basename)
endif()
# If the debug & release library ends up being the same, omit the keywords
- if(${Boost_${basename}_LIBRARY_RELEASE} STREQUAL ${Boost_${basename}_LIBRARY_DEBUG})
+ if("${Boost_${basename}_LIBRARY_RELEASE}" STREQUAL "${Boost_${basename}_LIBRARY_DEBUG}")
set(Boost_${basename}_LIBRARY ${Boost_${basename}_LIBRARY_RELEASE} )
set(Boost_${basename}_LIBRARIES ${Boost_${basename}_LIBRARY_RELEASE} )
endif()
if(Boost_${basename}_LIBRARY AND Boost_${basename}_HEADER)
set(Boost_${basename}_FOUND ON)
+ if("x${basename}" STREQUAL "xTHREAD" AND NOT TARGET Threads::Threads)
+ string(APPEND Boost_ERROR_REASON_THREAD " (missing dependency: Threads)")
+ set(Boost_THREAD_FOUND OFF)
+ endif()
endif()
endif()
@@ -893,9 +908,7 @@ function(_Boost_MISSING_DEPENDENCIES componentvar extravar)
set(_Boost_${uppercomponent}_DEPENDENCIES ${_Boost_${uppercomponent}_DEPENDENCIES} PARENT_SCOPE)
set(_Boost_IMPORTED_TARGETS ${_Boost_IMPORTED_TARGETS} PARENT_SCOPE)
foreach(componentdep ${_Boost_${uppercomponent}_DEPENDENCIES})
- list(FIND _boost_processed_components "${componentdep}" _boost_component_found)
- list(FIND _boost_new_components "${componentdep}" _boost_component_new)
- if (_boost_component_found EQUAL -1 AND _boost_component_new EQUAL -1)
+ if (NOT ("${componentdep}" IN_LIST _boost_processed_components OR "${componentdep}" IN_LIST _boost_new_components))
list(APPEND _boost_new_components ${componentdep})
endif()
endforeach()
@@ -992,8 +1005,14 @@ if(NOT Boost_LIBRARY_DIR_DEBUG AND Boost_LIBRARY_DIR)
set(Boost_LIBRARY_DIR_DEBUG "${Boost_LIBRARY_DIR}")
endif()
+if(NOT DEFINED Boost_USE_DEBUG_LIBS)
+ set(Boost_USE_DEBUG_LIBS TRUE)
+endif()
+if(NOT DEFINED Boost_USE_RELEASE_LIBS)
+ set(Boost_USE_RELEASE_LIBS TRUE)
+endif()
if(NOT DEFINED Boost_USE_MULTITHREADED)
- set(Boost_USE_MULTITHREADED TRUE)
+ set(Boost_USE_MULTITHREADED TRUE)
endif()
if(NOT DEFINED Boost_USE_DEBUG_RUNTIME)
set(Boost_USE_DEBUG_RUNTIME TRUE)
@@ -1523,10 +1542,14 @@ endif()
_Boost_MISSING_DEPENDENCIES(Boost_FIND_COMPONENTS _Boost_EXTRA_FIND_COMPONENTS)
# If thread is required, get the thread libs as a dependency
-list(FIND Boost_FIND_COMPONENTS thread _Boost_THREAD_DEPENDENCY_LIBS)
-if(NOT _Boost_THREAD_DEPENDENCY_LIBS EQUAL -1)
- include(CMakeFindDependencyMacro)
- find_dependency(Threads)
+if("thread" IN_LIST Boost_FIND_COMPONENTS)
+ if(Boost_FIND_QUIETLY)
+ set(_Boost_find_quiet QUIET)
+ else()
+ set(_Boost_find_quiet "")
+ endif()
+ find_package(Threads ${_Boost_find_quiet})
+ unset(_Boost_find_quiet)
endif()
# If the user changed any of our control inputs flush previous results.
@@ -1628,12 +1651,14 @@ foreach(COMPONENT ${Boost_FIND_COMPONENTS})
# Avoid passing backslashes to _Boost_FIND_LIBRARY due to macro re-parsing.
string(REPLACE "\\" "/" _boost_LIBRARY_SEARCH_DIRS_tmp "${_boost_LIBRARY_SEARCH_DIRS_RELEASE}")
- _Boost_FIND_LIBRARY(Boost_${UPPERCOMPONENT}_LIBRARY_RELEASE RELEASE
- NAMES ${_boost_RELEASE_NAMES}
- HINTS ${_boost_LIBRARY_SEARCH_DIRS_tmp}
- NAMES_PER_DIR
- DOC "${_boost_docstring_release}"
- )
+ if(Boost_USE_RELEASE_LIBS)
+ _Boost_FIND_LIBRARY(Boost_${UPPERCOMPONENT}_LIBRARY_RELEASE RELEASE
+ NAMES ${_boost_RELEASE_NAMES}
+ HINTS ${_boost_LIBRARY_SEARCH_DIRS_tmp}
+ NAMES_PER_DIR
+ DOC "${_boost_docstring_release}"
+ )
+ endif()
#
# Find DEBUG libraries
@@ -1677,12 +1702,14 @@ foreach(COMPONENT ${Boost_FIND_COMPONENTS})
# Avoid passing backslashes to _Boost_FIND_LIBRARY due to macro re-parsing.
string(REPLACE "\\" "/" _boost_LIBRARY_SEARCH_DIRS_tmp "${_boost_LIBRARY_SEARCH_DIRS_DEBUG}")
- _Boost_FIND_LIBRARY(Boost_${UPPERCOMPONENT}_LIBRARY_DEBUG DEBUG
- NAMES ${_boost_DEBUG_NAMES}
- HINTS ${_boost_LIBRARY_SEARCH_DIRS_tmp}
- NAMES_PER_DIR
- DOC "${_boost_docstring_debug}"
- )
+ if(Boost_USE_DEBUG_LIBS)
+ _Boost_FIND_LIBRARY(Boost_${UPPERCOMPONENT}_LIBRARY_DEBUG DEBUG
+ NAMES ${_boost_DEBUG_NAMES}
+ HINTS ${_boost_LIBRARY_SEARCH_DIRS_tmp}
+ NAMES_PER_DIR
+ DOC "${_boost_docstring_debug}"
+ )
+ endif ()
if(Boost_REALPATH)
_Boost_SWAP_WITH_REALPATH(Boost_${UPPERCOMPONENT}_LIBRARY_RELEASE "${_boost_docstring_release}")
@@ -1752,8 +1779,9 @@ if(Boost_FOUND)
string(APPEND Boost_ERROR_REASON
" Boost libraries:\n")
foreach(COMPONENT ${_Boost_MISSING_COMPONENTS})
+ string(TOUPPER ${COMPONENT} UPPERCOMPONENT)
string(APPEND Boost_ERROR_REASON
- " ${Boost_NAMESPACE}_${COMPONENT}\n")
+ " ${Boost_NAMESPACE}_${COMPONENT}${Boost_ERROR_REASON_${UPPERCOMPONENT}}\n")
endforeach()
list(LENGTH Boost_FIND_COMPONENTS Boost_NUM_COMPONENTS_WANTED)
@@ -1949,3 +1977,6 @@ list(REMOVE_DUPLICATES _Boost_COMPONENTS_SEARCHED)
list(SORT _Boost_COMPONENTS_SEARCHED)
set(_Boost_COMPONENTS_SEARCHED "${_Boost_COMPONENTS_SEARCHED}"
CACHE INTERNAL "Components requested for this build tree.")
+
+# Restore project's policies
+cmake_policy(POP)
diff --git a/Modules/FindCUDA.cmake b/Modules/FindCUDA.cmake
index a4dca5433..1c8ac2646 100644
--- a/Modules/FindCUDA.cmake
+++ b/Modules/FindCUDA.cmake
@@ -2,6 +2,20 @@
# FindCUDA
# --------
#
+# .. note::
+#
+# The FindCUDA module has been superseded by first-class support
+# for the CUDA language in CMake. It is no longer necessary to
+# use this module or call ``find_package(CUDA)``. This module
+# now exists only for compatibility with projects that have not
+# been ported.
+#
+# Instead, list ``CUDA`` among the languages named in the top-level
+# call to the :command:`project` command, or call the
+# :command:`enable_language` command with ``CUDA``.
+# Then one can add CUDA (``.cu``) sources to programs directly
+# in calls to :command:`add_library` and :command:`add_executable`.
+#
# Tools for building CUDA C files: libraries and build dependencies.
#
# This script locates the NVIDIA CUDA C tools. It should work on linux,
@@ -325,7 +339,27 @@
# CUDA_nppc_LIBRARY -- NVIDIA Performance Primitives lib (core).
# Only available for CUDA version 5.5+.
# CUDA_nppi_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
-# Only available for CUDA version 5.5+.
+# Only available for CUDA version 5.5 - 8.0.
+# CUDA_nppial_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
+# Only available for CUDA version 9.0.
+# CUDA_nppicc_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
+# Only available for CUDA version 9.0.
+# CUDA_nppicom_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
+# Only available for CUDA version 9.0.
+# CUDA_nppidei_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
+# Only available for CUDA version 9.0.
+# CUDA_nppif_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
+# Only available for CUDA version 9.0.
+# CUDA_nppig_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
+# Only available for CUDA version 9.0.
+# CUDA_nppim_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
+# Only available for CUDA version 9.0.
+# CUDA_nppist_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
+# Only available for CUDA version 9.0.
+# CUDA_nppisu_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
+# Only available for CUDA version 9.0.
+# CUDA_nppitc_LIBRARY -- NVIDIA Performance Primitives lib (image processing).
+# Only available for CUDA version 9.0.
# CUDA_npps_LIBRARY -- NVIDIA Performance Primitives lib (signal processing).
# Only available for CUDA version 5.5+.
# CUDA_nvcuvenc_LIBRARY -- CUDA Video Encoder library.
@@ -589,7 +623,6 @@ macro(cuda_unset_include_and_libraries)
unset(CUDA_npps_LIBRARY CACHE)
unset(CUDA_nvcuvenc_LIBRARY CACHE)
unset(CUDA_nvcuvid_LIBRARY CACHE)
- unset(CUDA_USE_STATIC_CUDA_RUNTIME CACHE)
unset(CUDA_GPU_DETECT_OUTPUT CACHE)
endmacro()
@@ -679,7 +712,11 @@ if(CMAKE_CROSSCOMPILING)
# add known CUDA targetr root path to the set of directories we search for programs, libraries and headers
set( CMAKE_FIND_ROOT_PATH "${CUDA_TOOLKIT_TARGET_DIR};${CMAKE_FIND_ROOT_PATH}")
macro( cuda_find_host_program )
- find_host_program( ${ARGN} )
+ if (COMMAND find_host_program)
+ find_host_program( ${ARGN} )
+ else()
+ find_program( ${ARGN} )
+ endif()
endmacro()
else()
# for non-cross-compile, find_host_program == find_program and CUDA_TOOLKIT_TARGET_DIR == CUDA_TOOLKIT_ROOT_DIR
@@ -798,12 +835,17 @@ endif()
if(CUDA_cudart_static_LIBRARY)
# If static cudart available, use it by default, but provide a user-visible option to disable it.
option(CUDA_USE_STATIC_CUDA_RUNTIME "Use the static version of the CUDA runtime library if available" ON)
- set(CUDA_CUDART_LIBRARY_VAR CUDA_cudart_static_LIBRARY)
else()
# If not available, silently disable the option.
set(CUDA_USE_STATIC_CUDA_RUNTIME OFF CACHE INTERNAL "")
+endif()
+
+if(CUDA_USE_STATIC_CUDA_RUNTIME)
+ set(CUDA_CUDART_LIBRARY_VAR CUDA_cudart_static_LIBRARY)
+else()
set(CUDA_CUDART_LIBRARY_VAR CUDA_CUDART_LIBRARY)
endif()
+
if(NOT CUDA_VERSION VERSION_LESS "5.0")
cuda_find_library_local_first(CUDA_cudadevrt_LIBRARY cudadevrt "\"cudadevrt\" library")
mark_as_advanced(CUDA_cudadevrt_LIBRARY)
@@ -917,6 +959,24 @@ if(NOT CUDA_VERSION VERSION_LESS "3.2")
endif()
if(CUDA_VERSION VERSION_GREATER "5.0")
find_cuda_helper_libs(cublas_device)
+endif()
+
+if(NOT CUDA_VERSION VERSION_LESS "9.0")
+ # In CUDA 9.0 NPP was nppi was removed
+ find_cuda_helper_libs(nppc)
+ find_cuda_helper_libs(nppial)
+ find_cuda_helper_libs(nppicc)
+ find_cuda_helper_libs(nppicom)
+ find_cuda_helper_libs(nppidei)
+ find_cuda_helper_libs(nppif)
+ find_cuda_helper_libs(nppig)
+ find_cuda_helper_libs(nppim)
+ find_cuda_helper_libs(nppist)
+ find_cuda_helper_libs(nppisu)
+ find_cuda_helper_libs(nppitc)
+ find_cuda_helper_libs(npps)
+ set(CUDA_npp_LIBRARY "${CUDA_nppc_LIBRARY};${CUDA_nppial_LIBRARY};${CUDA_nppicc_LIBRARY};${CUDA_nppicom_LIBRARY};${CUDA_nppidei_LIBRARY};${CUDA_nppif_LIBRARY};${CUDA_nppig_LIBRARY};${CUDA_nppim_LIBRARY};${CUDA_nppist_LIBRARY};${CUDA_nppisu_LIBRARY};${CUDA_nppitc_LIBRARY};${CUDA_npps_LIBRARY}")
+elseif(CUDA_VERSION VERSION_GREATER "5.0")
# In CUDA 5.5 NPP was splitted onto 3 separate libraries.
find_cuda_helper_libs(nppc)
find_cuda_helper_libs(nppi)
@@ -1698,6 +1758,7 @@ function(CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS output_file cuda_target options
COMMAND ${CUDA_NVCC_EXECUTABLE} ${nvcc_flags} -dlink ${object_files} -o ${output_file}
${flags}
COMMENT "Building NVCC intermediate link file ${output_file_relative_path}"
+ COMMAND_EXPAND_LISTS
${_verbatim}
)
else()
@@ -1708,6 +1769,7 @@ function(CUDA_LINK_SEPARABLE_COMPILATION_OBJECTS output_file cuda_target options
COMMAND ${CMAKE_COMMAND} -E echo "Building NVCC intermediate link file ${output_file_relative_path}"
COMMAND ${CMAKE_COMMAND} -E make_directory "${output_file_dir}"
COMMAND ${CUDA_NVCC_EXECUTABLE} ${nvcc_flags} ${flags} -dlink ${object_files} -o "${output_file}"
+ COMMAND_EXPAND_LISTS
${_verbatim}
)
endif()
diff --git a/Modules/FindCUDA/run_nvcc.cmake b/Modules/FindCUDA/run_nvcc.cmake
index 28cc1e99e..f78119d34 100644
--- a/Modules/FindCUDA/run_nvcc.cmake
+++ b/Modules/FindCUDA/run_nvcc.cmake
@@ -50,6 +50,8 @@
# generated_cubin_file:STRING=<> File to generate. This argument must be passed
# in if build_cubin is true.
+cmake_policy(PUSH)
+cmake_policy(SET CMP0007 NEW)
if(NOT generated_file)
message(FATAL_ERROR "You must specify generated_file on the command line")
endif()
@@ -74,7 +76,7 @@ set(CUDA_NVCC_FLAGS @CUDA_NVCC_FLAGS@ ;; @CUDA_WRAP_OPTION_NVCC_FLAGS@) # list
@CUDA_NVCC_FLAGS_CONFIG@
set(nvcc_flags @nvcc_flags@) # list
set(CUDA_NVCC_INCLUDE_DIRS "@CUDA_NVCC_INCLUDE_DIRS@") # list (needs to be in quotes to handle spaces properly).
-set(CUDA_NVCC_COMPILE_DEFINITIONS "@CUDA_NVCC_COMPILE_DEFINITIONS@") # list (needs to be in quotes to handle spaces properly).
+set(CUDA_NVCC_COMPILE_DEFINITIONS [==[@CUDA_NVCC_COMPILE_DEFINITIONS@]==]) # list (needs to be in lua quotes see #16510 ).
set(format_flag "@format_flag@") # string
set(cuda_language_flag @cuda_language_flag@) # list
@@ -179,13 +181,8 @@ cuda_execute_process(
set(depends_CUDA_NVCC_FLAGS "${CUDA_NVCC_FLAGS}")
set(CUDA_VERSION @CUDA_VERSION@)
if(CUDA_VERSION VERSION_LESS "3.0")
- cmake_policy(PUSH)
- # CMake policy 0007 NEW states that empty list elements are not
- # ignored. I'm just setting it to avoid the warning that's printed.
- cmake_policy(SET CMP0007 NEW)
# Note that this will remove all occurances of -G.
list(REMOVE_ITEM depends_CUDA_NVCC_FLAGS "-G")
- cmake_policy(POP)
endif()
# nvcc doesn't define __CUDACC__ for some reason when generating dependency files. This
@@ -304,3 +301,5 @@ if( build_cubin )
)
endif()
+
+cmake_policy(POP)
diff --git a/Modules/FindCUDA/select_compute_arch.cmake b/Modules/FindCUDA/select_compute_arch.cmake
index 8fb44d80a..b604a1790 100644
--- a/Modules/FindCUDA/select_compute_arch.cmake
+++ b/Modules/FindCUDA/select_compute_arch.cmake
@@ -30,12 +30,17 @@ endif ()
if (CUDA_VERSION VERSION_GREATER "7.5")
list(APPEND CUDA_KNOWN_GPU_ARCHITECTURES "Pascal")
- list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "6.0" "6.1" "6.1+PTX")
+ list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "6.0" "6.1")
else()
list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "5.2+PTX")
endif ()
-
+if (CUDA_VERSION VERSION_GREATER "8.5")
+ list(APPEND CUDA_KNOWN_GPU_ARCHITECTURES "Volta")
+ list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "7.0" "7.0+PTX")
+else()
+ list(APPEND CUDA_COMMON_GPU_ARCHITECTURES "6.1+PTX")
+endif()
################################################################################################
# A function for automatic detection of GPUs installed (if autodetection is enabled)
@@ -141,6 +146,9 @@ function(CUDA_SELECT_NVCC_ARCH_FLAGS out_variable)
elseif(${arch_name} STREQUAL "Pascal")
set(arch_bin 6.0 6.1)
set(arch_ptx 6.1)
+ elseif(${arch_name} STREQUAL "Volta")
+ set(arch_bin 7.0 7.0)
+ set(arch_ptx 7.0)
else()
message(SEND_ERROR "Unknown CUDA Architecture Name ${arch_name} in CUDA_SELECT_NVCC_ARCH_FLAGS")
endif()
diff --git a/Modules/FindCurses.cmake b/Modules/FindCurses.cmake
index 4365e996e..4f59d2c1e 100644
--- a/Modules/FindCurses.cmake
+++ b/Modules/FindCurses.cmake
@@ -29,6 +29,8 @@
#
# Set ``CURSES_NEED_NCURSES`` to ``TRUE`` before the
# ``find_package(Curses)`` call if NCurses functionality is required.
+# Set ``CURSES_NEED_WIDE`` to ``TRUE`` before the
+# ``find_package(Curses)`` call if unicode functionality is required.
#
# Backward Compatibility
# ^^^^^^^^^^^^^^^^^^^^^^
@@ -42,9 +44,20 @@
include(${CMAKE_CURRENT_LIST_DIR}/CheckLibraryExists.cmake)
+# we don't know anything about cursesw, so only ncurses
+# may be ncursesw
+if(NOT CURSES_NEED_WIDE)
+ set(NCURSES_LIBRARY_NAME "ncurses")
+else()
+ set(NCURSES_LIBRARY_NAME "ncursesw")
+ # Also, if we are searchig fo wide curses - we are actually searching
+ # for ncurses, we don't know about any other unicode version.
+ set(CURSES_NEED_NCURSES TRUE)
+endif()
+
find_library(CURSES_CURSES_LIBRARY NAMES curses )
-find_library(CURSES_NCURSES_LIBRARY NAMES ncurses )
+find_library(CURSES_NCURSES_LIBRARY NAMES "${NCURSES_LIBRARY_NAME}" )
set(CURSES_USE_NCURSES FALSE)
if(CURSES_NCURSES_LIBRARY AND ((NOT CURSES_CURSES_LIBRARY) OR CURSES_NEED_NCURSES))
@@ -55,8 +68,14 @@ endif()
# message. Cygwin is an ncurses package, so force ncurses on
# cygwin if the curses.h is missing
if(CYGWIN)
- if(NOT EXISTS /usr/include/curses.h)
- set(CURSES_USE_NCURSES TRUE)
+ if (CURSES_NEED_WIDE)
+ if(NOT EXISTS /usr/include/ncursesw/curses.h)
+ set(CURSES_USE_NCURSES TRUE)
+ endif()
+ else()
+ if(NOT EXISTS /usr/include/curses.h)
+ set(CURSES_USE_NCURSES TRUE)
+ endif()
endif()
endif()
@@ -96,17 +115,32 @@ if(CURSES_USE_NCURSES)
# Use CURSES_NCURSES_INCLUDE_PATH if set, for compatibility.
if(CURSES_NCURSES_INCLUDE_PATH)
+ if (CURSES_NEED_WIDE)
+ find_path(CURSES_INCLUDE_PATH
+ NAMES ncursesw/ncurses.h ncursesw/curses.h
+ PATHS ${CURSES_NCURSES_INCLUDE_PATH}
+ NO_DEFAULT_PATH
+ )
+ else()
+ find_path(CURSES_INCLUDE_PATH
+ NAMES ncurses/ncurses.h ncurses/curses.h ncurses.h curses.h
+ PATHS ${CURSES_NCURSES_INCLUDE_PATH}
+ NO_DEFAULT_PATH
+ )
+ endif()
+ endif()
+
+ if (CURSES_NEED_WIDE)
+ find_path(CURSES_INCLUDE_PATH
+ NAMES ncursesw/ncurses.h ncursesw/curses.h
+ HINTS "${_cursesParentDir}/include"
+ )
+ else()
find_path(CURSES_INCLUDE_PATH
NAMES ncurses/ncurses.h ncurses/curses.h ncurses.h curses.h
- PATHS ${CURSES_NCURSES_INCLUDE_PATH}
- NO_DEFAULT_PATH
+ HINTS "${_cursesParentDir}/include"
)
- endif()
-
- find_path(CURSES_INCLUDE_PATH
- NAMES ncurses/ncurses.h ncurses/curses.h ncurses.h curses.h
- HINTS "${_cursesParentDir}/include"
- )
+ endif()
# Previous versions of FindCurses provided these values.
if(NOT DEFINED CURSES_LIBRARY)
@@ -123,10 +157,14 @@ else()
get_filename_component(_cursesLibDir "${CURSES_CURSES_LIBRARY}" PATH)
get_filename_component(_cursesParentDir "${_cursesLibDir}" PATH)
- find_path(CURSES_INCLUDE_PATH
- NAMES curses.h
- HINTS "${_cursesParentDir}/include"
- )
+ #We can't find anything with CURSES_NEED_WIDE because we know
+ #only about ncursesw unicode curses version
+ if(NOT CURSES_NEED_WIDE)
+ find_path(CURSES_INCLUDE_PATH
+ NAMES curses.h
+ HINTS "${_cursesParentDir}/include"
+ )
+ endif()
# Previous versions of FindCurses provided these values.
if(NOT DEFINED CURSES_CURSES_H_PATH)
@@ -139,31 +177,44 @@ endif()
# Report whether each possible header name exists in the include directory.
if(NOT DEFINED CURSES_HAVE_NCURSES_NCURSES_H)
- if(EXISTS "${CURSES_INCLUDE_PATH}/ncurses/ncurses.h")
+ if(CURSES_NEED_WIDE)
+ if(EXISTS "${CURSES_INCLUDE_PATH}/ncursesw/ncurses.h")
+ set(CURSES_HAVE_NCURSES_NCURSES_H "${CURSES_INCLUDE_PATH}/ncursesw/ncurses.h")
+ endif()
+ elseif(EXISTS "${CURSES_INCLUDE_PATH}/ncurses/ncurses.h")
set(CURSES_HAVE_NCURSES_NCURSES_H "${CURSES_INCLUDE_PATH}/ncurses/ncurses.h")
- else()
+ endif()
+ if(NOT DEFINED CURSES_HAVE_NCURSES_NCURSES_H)
set(CURSES_HAVE_NCURSES_NCURSES_H "CURSES_HAVE_NCURSES_NCURSES_H-NOTFOUND")
endif()
endif()
if(NOT DEFINED CURSES_HAVE_NCURSES_CURSES_H)
- if(EXISTS "${CURSES_INCLUDE_PATH}/ncurses/curses.h")
+ if(CURSES_NEED_WIDE)
+ if(EXISTS "${CURSES_INCLUDE_PATH}/ncursesw/curses.h")
+ set(CURSES_HAVE_NCURSES_CURSES_H "${CURSES_INCLUDE_PATH}/ncursesw/curses.h")
+ endif()
+ elseif(EXISTS "${CURSES_INCLUDE_PATH}/ncurses/curses.h")
set(CURSES_HAVE_NCURSES_CURSES_H "${CURSES_INCLUDE_PATH}/ncurses/curses.h")
- else()
+ endif()
+ if(NOT DEFINED CURSES_HAVE_NCURSES_CURSES_H)
set(CURSES_HAVE_NCURSES_CURSES_H "CURSES_HAVE_NCURSES_CURSES_H-NOTFOUND")
endif()
endif()
-if(NOT DEFINED CURSES_HAVE_NCURSES_H)
- if(EXISTS "${CURSES_INCLUDE_PATH}/ncurses.h")
- set(CURSES_HAVE_NCURSES_H "${CURSES_INCLUDE_PATH}/ncurses.h")
- else()
- set(CURSES_HAVE_NCURSES_H "CURSES_HAVE_NCURSES_H-NOTFOUND")
+if(NOT CURSES_NEED_WIDE)
+ #ncursesw can't be found for this paths
+ if(NOT DEFINED CURSES_HAVE_NCURSES_H)
+ if(EXISTS "${CURSES_INCLUDE_PATH}/ncurses.h")
+ set(CURSES_HAVE_NCURSES_H "${CURSES_INCLUDE_PATH}/ncurses.h")
+ else()
+ set(CURSES_HAVE_NCURSES_H "CURSES_HAVE_NCURSES_H-NOTFOUND")
+ endif()
endif()
-endif()
-if(NOT DEFINED CURSES_HAVE_CURSES_H)
- if(EXISTS "${CURSES_INCLUDE_PATH}/curses.h")
- set(CURSES_HAVE_CURSES_H "${CURSES_INCLUDE_PATH}/curses.h")
- else()
- set(CURSES_HAVE_CURSES_H "CURSES_HAVE_CURSES_H-NOTFOUND")
+ if(NOT DEFINED CURSES_HAVE_CURSES_H)
+ if(EXISTS "${CURSES_INCLUDE_PATH}/curses.h")
+ set(CURSES_HAVE_CURSES_H "${CURSES_INCLUDE_PATH}/curses.h")
+ else()
+ set(CURSES_HAVE_CURSES_H "CURSES_HAVE_CURSES_H-NOTFOUND")
+ endif()
endif()
endif()
@@ -199,4 +250,5 @@ mark_as_advanced(
CURSES_CURSES_LIBRARY
CURSES_NCURSES_LIBRARY
CURSES_EXTRA_LIBRARY
+ CURSES_FORM_LIBRARY
)
diff --git a/Modules/FindCygwin.cmake b/Modules/FindCygwin.cmake
index c6913da17..092a3bd49 100644
--- a/Modules/FindCygwin.cmake
+++ b/Modules/FindCygwin.cmake
@@ -13,10 +13,12 @@ if (WIN32)
endif()
find_program(CYGWIN_BAT
- cygwin.bat
- "C:/Cygwin"
- "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Cygwin\\setup;rootdir]"
- "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Cygnus Solutions\\Cygwin\\mounts v2\\/;native]"
+ NAMES cygwin.bat
+ PATHS
+ "C:/Cygwin"
+ "C:/Cygwin64"
+ "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Cygwin\\setup;rootdir]"
+ "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Cygnus Solutions\\Cygwin\\mounts v2\\/;native]"
)
get_filename_component(CYGWIN_INSTALL_PATH "${CYGWIN_BAT}" DIRECTORY)
mark_as_advanced(CYGWIN_BAT)
diff --git a/Modules/FindDoxygen.cmake b/Modules/FindDoxygen.cmake
index 46bf340dd..d0dd0f164 100644
--- a/Modules/FindDoxygen.cmake
+++ b/Modules/FindDoxygen.cmake
@@ -832,7 +832,11 @@ doxygen_add_docs() for target ${targetName}")
# and Lucent Bell Labs. The other options in this section have no
# effect if this option is set to NO.
# Doxygen's default value is: NO.
- set(DOXYGEN_HAVE_DOT ${DOXYGEN_DOT_FOUND})
+ if(Doxygen_dot_FOUND)
+ set(DOXYGEN_HAVE_DOT "YES")
+ else()
+ set(DOXYGEN_HAVE_DOT "NO")
+ endif()
endif()
if(NOT DEFINED DOXYGEN_DOT_MULTI_TARGETS)
diff --git a/Modules/FindEXPAT.cmake b/Modules/FindEXPAT.cmake
index 09963fcda..39086e499 100644
--- a/Modules/FindEXPAT.cmake
+++ b/Modules/FindEXPAT.cmake
@@ -5,15 +5,28 @@
# FindEXPAT
# ---------
#
-# Find expat
+# Find the native Expat headers and library.
#
-# Find the native EXPAT headers and libraries.
+# Imported Targets
+# ^^^^^^^^^^^^^^^^
#
-# ::
+# This module defines the following :prop_tgt:`IMPORTED` targets:
+#
+# ``EXPAT::EXPAT``
+# The Expat ``expat`` library, if found.
+#
+# Result Variables
+# ^^^^^^^^^^^^^^^^
+#
+# This module will set the following variables in your project:
+#
+# ``EXPAT_INCLUDE_DIRS``
+# where to find expat.h, etc.
+# ``EXPAT_LIBRARIES``
+# the libraries to link against to use Expat.
+# ``EXPAT_FOUND``
+# true if the Expat headers and libraries were found.
#
-# EXPAT_INCLUDE_DIRS - where to find expat.h, etc.
-# EXPAT_LIBRARIES - List of libraries when using expat.
-# EXPAT_FOUND - True if expat found.
find_package(PkgConfig QUIET)
@@ -49,10 +62,18 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(EXPAT
REQUIRED_VARS EXPAT_LIBRARY EXPAT_INCLUDE_DIR
VERSION_VAR EXPAT_VERSION_STRING)
-# Copy the results to the output variables.
+# Copy the results to the output variables and target.
if(EXPAT_FOUND)
set(EXPAT_LIBRARIES ${EXPAT_LIBRARY})
set(EXPAT_INCLUDE_DIRS ${EXPAT_INCLUDE_DIR})
+
+ if(NOT TARGET EXPAT::EXPAT)
+ add_library(EXPAT::EXPAT UNKNOWN IMPORTED)
+ set_target_properties(EXPAT::EXPAT PROPERTIES
+ IMPORTED_LINK_INTERFACE_LANGUAGES "C"
+ IMPORTED_LOCATION "${EXPAT_LIBRARY}"
+ INTERFACE_INCLUDE_DIRECTORIES "${EXPAT_INCLUDE_DIRS}")
+ endif()
endif()
mark_as_advanced(EXPAT_INCLUDE_DIR EXPAT_LIBRARY)
diff --git a/Modules/FindFreetype.cmake b/Modules/FindFreetype.cmake
index 9ea77df1d..0e6d33645 100644
--- a/Modules/FindFreetype.cmake
+++ b/Modules/FindFreetype.cmake
@@ -5,24 +5,41 @@
# FindFreetype
# ------------
#
-# Locate FreeType library
+# Find the FreeType font renderer includes and library.
#
-# This module defines
+# Imported Targets
+# ^^^^^^^^^^^^^^^^
#
-# ::
+# This module defines the following :prop_tgt:`IMPORTED` target:
#
-# FREETYPE_LIBRARIES, the library to link against
-# FREETYPE_FOUND, if false, do not try to link to FREETYPE
-# FREETYPE_INCLUDE_DIRS, where to find headers.
-# FREETYPE_VERSION_STRING, the version of freetype found (since CMake 2.8.8)
-# This is the concatenation of the paths:
-# FREETYPE_INCLUDE_DIR_ft2build
-# FREETYPE_INCLUDE_DIR_freetype2
+# ``Freetype::Freetype``
+# The Freetype ``freetype`` library, if found
#
+# Result Variables
+# ^^^^^^^^^^^^^^^^
#
+# This module will set the following variables in your project:
#
-# $FREETYPE_DIR is an environment variable that would correspond to the
-# ./configure --prefix=$FREETYPE_DIR used in building FREETYPE.
+# ``FREETYPE_FOUND``
+# true if the Freetype headers and libraries were found
+# ``FREETYPE_INCLUDE_DIRS``
+# directories containing the Freetype headers. This is the
+# concatenation of the variables:
+#
+# ``FREETYPE_INCLUDE_DIR_ft2build``
+# directory holding the main Freetype API configuration header
+# ``FREETYPE_INCLUDE_DIR_freetype2``
+# directory holding Freetype public headers
+# ``FREETYPE_LIBRARIES``
+# the library to link against
+# ``FREETYPE_VERSION_STRING``
+# the version of freetype found (since CMake 2.8.8)
+#
+# Hints
+# ^^^^^
+#
+# The user may set the environment variable ``FREETYPE_DIR`` to the root
+# directory of a Freetype installation.
# Created by Eric Wing.
# Modifications by Alexander Neundorf.
@@ -150,3 +167,33 @@ mark_as_advanced(
FREETYPE_INCLUDE_DIR_freetype2
FREETYPE_INCLUDE_DIR_ft2build
)
+
+if(Freetype_FOUND)
+ if(NOT TARGET Freetype::Freetype)
+ add_library(Freetype::Freetype UNKNOWN IMPORTED)
+ set_target_properties(Freetype::Freetype PROPERTIES
+ INTERFACE_INCLUDE_DIRECTORIES "${FREETYPE_INCLUDE_DIRS}")
+
+ if(FREETYPE_LIBRARY_RELEASE)
+ set_property(TARGET Freetype::Freetype APPEND PROPERTY
+ IMPORTED_CONFIGURATIONS RELEASE)
+ set_target_properties(Freetype::Freetype PROPERTIES
+ IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "C"
+ IMPORTED_LOCATION_RELEASE "${FREETYPE_LIBRARY_RELEASE}")
+ endif()
+
+ if(FREETYPE_LIBRARY_DEBUG)
+ set_property(TARGET Freetype::Freetype APPEND PROPERTY
+ IMPORTED_CONFIGURATIONS DEBUG)
+ set_target_properties(Freetype::Freetype PROPERTIES
+ IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "C"
+ IMPORTED_LOCATION_DEBUG "${FREETYPE_LIBRARY_DEBUG}")
+ endif()
+
+ if(NOT FREETYPE_LIBRARY_RELEASE AND NOT FREETYPE_LIBRARY_DEBUG)
+ set_target_properties(Freetype::Freetype PROPERTIES
+ IMPORTED_LINK_INTERFACE_LANGUAGES "C"
+ IMPORTED_LOCATION "${FREETYPE_LIBRARY}")
+ endif()
+ endif()
+endif()
diff --git a/Modules/FindGTest.cmake b/Modules/FindGTest.cmake
index c4b4535ff..b0579d967 100644
--- a/Modules/FindGTest.cmake
+++ b/Modules/FindGTest.cmake
@@ -71,11 +71,11 @@
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# See :module:`GoogleTest` for information on the :command:`gtest_add_tests`
-# command.
+# and :command:`gtest_discover_tests` commands.
include(${CMAKE_CURRENT_LIST_DIR}/GoogleTest.cmake)
-function(_gtest_append_debugs _endvar _library)
+function(__gtest_append_debugs _endvar _library)
if(${_library} AND ${_library}_DEBUG)
set(_output optimized ${${_library}} debug ${${_library}_DEBUG})
else()
@@ -84,7 +84,7 @@ function(_gtest_append_debugs _endvar _library)
set(${_endvar} ${_output} PARENT_SCOPE)
endfunction()
-function(_gtest_find_library _name)
+function(__gtest_find_library _name)
find_library(${_name}
NAMES ${ARGN}
HINTS
@@ -95,6 +95,56 @@ function(_gtest_find_library _name)
mark_as_advanced(${_name})
endfunction()
+macro(__gtest_determine_windows_library_type _var)
+ if(EXISTS "${${_var}}")
+ file(TO_NATIVE_PATH "${${_var}}" _lib_path)
+ get_filename_component(_name "${${_var}}" NAME_WE)
+ file(STRINGS "${${_var}}" _match REGEX "${_name}\\.dll" LIMIT_COUNT 1)
+ if(NOT _match STREQUAL "")
+ set(${_var}_TYPE SHARED PARENT_SCOPE)
+ else()
+ set(${_var}_TYPE UNKNOWN PARENT_SCOPE)
+ endif()
+ return()
+ endif()
+endmacro()
+
+function(__gtest_determine_library_type _var)
+ if(WIN32)
+ # For now, at least, only Windows really needs to know the library type
+ __gtest_determine_windows_library_type(${_var})
+ __gtest_determine_windows_library_type(${_var}_RELEASE)
+ __gtest_determine_windows_library_type(${_var}_DEBUG)
+ endif()
+ # If we get here, no determination was made from the above checks
+ set(${_var}_TYPE UNKNOWN PARENT_SCOPE)
+endfunction()
+
+function(__gtest_import_library _target _var _config)
+ if(_config)
+ set(_config_suffix "_${_config}")
+ else()
+ set(_config_suffix "")
+ endif()
+
+ set(_lib "${${_var}${_config_suffix}}")
+ if(EXISTS "${_lib}")
+ if(_config)
+ set_property(TARGET ${_target} APPEND PROPERTY
+ IMPORTED_CONFIGURATIONS ${_config})
+ endif()
+ set_target_properties(${_target} PROPERTIES
+ IMPORTED_LINK_INTERFACE_LANGUAGES${_config_suffix} "CXX")
+ if(WIN32 AND ${_var}_TYPE STREQUAL SHARED)
+ set_target_properties(${_target} PROPERTIES
+ IMPORTED_IMPLIB${_config_suffix} "${_lib}")
+ else()
+ set_target_properties(${_target} PROPERTIES
+ IMPORTED_LOCATION${_config_suffix} "${_lib}")
+ endif()
+ endif()
+endfunction()
+
#
if(NOT DEFINED GTEST_MSVC_SEARCH)
@@ -131,15 +181,15 @@ mark_as_advanced(GTEST_INCLUDE_DIR)
if(MSVC AND GTEST_MSVC_SEARCH STREQUAL "MD")
# The provided /MD project files for Google Test add -md suffixes to the
# library names.
- _gtest_find_library(GTEST_LIBRARY gtest-md gtest)
- _gtest_find_library(GTEST_LIBRARY_DEBUG gtest-mdd gtestd)
- _gtest_find_library(GTEST_MAIN_LIBRARY gtest_main-md gtest_main)
- _gtest_find_library(GTEST_MAIN_LIBRARY_DEBUG gtest_main-mdd gtest_maind)
+ __gtest_find_library(GTEST_LIBRARY gtest-md gtest)
+ __gtest_find_library(GTEST_LIBRARY_DEBUG gtest-mdd gtestd)
+ __gtest_find_library(GTEST_MAIN_LIBRARY gtest_main-md gtest_main)
+ __gtest_find_library(GTEST_MAIN_LIBRARY_DEBUG gtest_main-mdd gtest_maind)
else()
- _gtest_find_library(GTEST_LIBRARY gtest)
- _gtest_find_library(GTEST_LIBRARY_DEBUG gtestd)
- _gtest_find_library(GTEST_MAIN_LIBRARY gtest_main)
- _gtest_find_library(GTEST_MAIN_LIBRARY_DEBUG gtest_maind)
+ __gtest_find_library(GTEST_LIBRARY gtest)
+ __gtest_find_library(GTEST_LIBRARY_DEBUG gtestd)
+ __gtest_find_library(GTEST_MAIN_LIBRARY gtest_main)
+ __gtest_find_library(GTEST_MAIN_LIBRARY_DEBUG gtest_maind)
endif()
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
@@ -147,63 +197,38 @@ FIND_PACKAGE_HANDLE_STANDARD_ARGS(GTest DEFAULT_MSG GTEST_LIBRARY GTEST_INCLUDE_
if(GTEST_FOUND)
set(GTEST_INCLUDE_DIRS ${GTEST_INCLUDE_DIR})
- _gtest_append_debugs(GTEST_LIBRARIES GTEST_LIBRARY)
- _gtest_append_debugs(GTEST_MAIN_LIBRARIES GTEST_MAIN_LIBRARY)
+ __gtest_append_debugs(GTEST_LIBRARIES GTEST_LIBRARY)
+ __gtest_append_debugs(GTEST_MAIN_LIBRARIES GTEST_MAIN_LIBRARY)
set(GTEST_BOTH_LIBRARIES ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES})
- include(CMakeFindDependencyMacro)
- find_dependency(Threads)
+ find_package(Threads QUIET)
if(NOT TARGET GTest::GTest)
- add_library(GTest::GTest UNKNOWN IMPORTED)
- set_target_properties(GTest::GTest PROPERTIES
- INTERFACE_LINK_LIBRARIES "Threads::Threads")
- if(GTEST_INCLUDE_DIRS)
- set_target_properties(GTest::GTest PROPERTIES
- INTERFACE_INCLUDE_DIRECTORIES "${GTEST_INCLUDE_DIRS}")
- endif()
- if(EXISTS "${GTEST_LIBRARY}")
+ __gtest_determine_library_type(GTEST_LIBRARY)
+ add_library(GTest::GTest ${GTEST_LIBRARY_TYPE} IMPORTED)
+ if(TARGET Threads::Threads)
set_target_properties(GTest::GTest PROPERTIES
- IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
- IMPORTED_LOCATION "${GTEST_LIBRARY}")
+ INTERFACE_LINK_LIBRARIES Threads::Threads)
endif()
- if(EXISTS "${GTEST_LIBRARY_RELEASE}")
- set_property(TARGET GTest::GTest APPEND PROPERTY
- IMPORTED_CONFIGURATIONS RELEASE)
+ if(GTEST_LIBRARY_TYPE STREQUAL "SHARED")
set_target_properties(GTest::GTest PROPERTIES
- IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX"
- IMPORTED_LOCATION_RELEASE "${GTEST_LIBRARY_RELEASE}")
+ INTERFACE_COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1")
endif()
- if(EXISTS "${GTEST_LIBRARY_DEBUG}")
- set_property(TARGET GTest::GTest APPEND PROPERTY
- IMPORTED_CONFIGURATIONS DEBUG)
+ if(GTEST_INCLUDE_DIRS)
set_target_properties(GTest::GTest PROPERTIES
- IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
- IMPORTED_LOCATION_DEBUG "${GTEST_LIBRARY_DEBUG}")
+ INTERFACE_INCLUDE_DIRECTORIES "${GTEST_INCLUDE_DIRS}")
endif()
- endif()
- if(NOT TARGET GTest::Main)
- add_library(GTest::Main UNKNOWN IMPORTED)
- set_target_properties(GTest::Main PROPERTIES
- INTERFACE_LINK_LIBRARIES "GTest::GTest")
- if(EXISTS "${GTEST_MAIN_LIBRARY}")
- set_target_properties(GTest::Main PROPERTIES
- IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
- IMPORTED_LOCATION "${GTEST_MAIN_LIBRARY}")
- endif()
- if(EXISTS "${GTEST_MAIN_LIBRARY_RELEASE}")
- set_property(TARGET GTest::Main APPEND PROPERTY
- IMPORTED_CONFIGURATIONS RELEASE)
- set_target_properties(GTest::Main PROPERTIES
- IMPORTED_LINK_INTERFACE_LANGUAGES_RELEASE "CXX"
- IMPORTED_LOCATION_RELEASE "${GTEST_MAIN_LIBRARY_RELEASE}")
- endif()
- if(EXISTS "${GTEST_MAIN_LIBRARY_DEBUG}")
- set_property(TARGET GTest::Main APPEND PROPERTY
- IMPORTED_CONFIGURATIONS DEBUG)
- set_target_properties(GTest::Main PROPERTIES
- IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX"
- IMPORTED_LOCATION_DEBUG "${GTEST_MAIN_LIBRARY_DEBUG}")
- endif()
+ __gtest_import_library(GTest::GTest GTEST_LIBRARY "")
+ __gtest_import_library(GTest::GTest GTEST_LIBRARY "RELEASE")
+ __gtest_import_library(GTest::GTest GTEST_LIBRARY "DEBUG")
+ endif()
+ if(NOT TARGET GTest::Main)
+ __gtest_determine_library_type(GTEST_MAIN_LIBRARY)
+ add_library(GTest::Main ${GTEST_MAIN_LIBRARY_TYPE} IMPORTED)
+ set_target_properties(GTest::Main PROPERTIES
+ INTERFACE_LINK_LIBRARIES "GTest::GTest")
+ __gtest_import_library(GTest::Main GTEST_MAIN_LIBRARY "")
+ __gtest_import_library(GTest::Main GTEST_MAIN_LIBRARY "RELEASE")
+ __gtest_import_library(GTest::Main GTEST_MAIN_LIBRARY "DEBUG")
endif()
endif()
diff --git a/Modules/FindGettext.cmake b/Modules/FindGettext.cmake
index 803550715..9623b85dd 100644
--- a/Modules/FindGettext.cmake
+++ b/Modules/FindGettext.cmake
@@ -66,10 +66,14 @@ if(GETTEXT_MSGMERGE_EXECUTABLE)
OUTPUT_VARIABLE gettext_version
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
- if (gettext_version MATCHES "^msgmerge \\([^\\)]*\\) ([0-9\\.]+[^ \n]*)")
- set(GETTEXT_VERSION_STRING "${CMAKE_MATCH_1}")
+ get_filename_component(msgmerge_name ${GETTEXT_MSGMERGE_EXECUTABLE} NAME)
+ get_filename_component(msgmerge_namewe ${GETTEXT_MSGMERGE_EXECUTABLE} NAME_WE)
+ if (gettext_version MATCHES "^(${msgmerge_name}|${msgmerge_namewe}) \\([^\\)]*\\) ([0-9\\.]+[^ \n]*)")
+ set(GETTEXT_VERSION_STRING "${CMAKE_MATCH_2}")
endif()
unset(gettext_version)
+ unset(msgmerge_name)
+ unset(msgmerge_namewe)
endif()
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
diff --git a/Modules/FindHDF5.cmake b/Modules/FindHDF5.cmake
index 5962c5bd4..3279bf26b 100644
--- a/Modules/FindHDF5.cmake
+++ b/Modules/FindHDF5.cmake
@@ -23,7 +23,7 @@
# Fortran_HL. If the COMPONENTS argument is not given, the module will
# attempt to find only the C bindings.
#
-# On UNIX systems, this module will read the variable
+# This module will read the variable
# HDF5_USE_STATIC_LIBRARIES to determine whether or not to prefer a
# static link to a dynamic link for HDF5 and all of it's dependencies.
# To use this feature, make sure that the HDF5_USE_STATIC_LIBRARIES
@@ -187,8 +187,16 @@ function(_HDF5_test_regular_compiler_C success version is_parallel)
file(WRITE ${test_file}
"#include <hdf5.h>\n"
"#include <hdf5_hl.h>\n"
- "int main(void) {\n"
- " char const* info_ver = \"INFO\" \":\" H5_VERSION;\n"
+ "const char* info_ver = \"INFO\" \":\" H5_VERSION;\n"
+ "#ifdef H5_HAVE_PARALLEL\n"
+ "const char* info_parallel = \"INFO\" \":\" \"PARALLEL\";\n"
+ "#endif\n"
+ "int main(int argc, char **argv) {\n"
+ " int require = 0;\n"
+ " require += info_ver[argc];\n"
+ "#ifdef H5_HAVE_PARALLEL\n"
+ " require += info_parallel[argc];\n"
+ "#endif\n"
" hid_t fid;\n"
" fid = H5Fcreate(\"foo.h5\",H5F_ACC_TRUNC,H5P_DEFAULT,H5P_DEFAULT);\n"
" return 0;\n"
@@ -198,24 +206,19 @@ function(_HDF5_test_regular_compiler_C success version is_parallel)
)
endif()
if(${success})
- file(STRINGS ${scratch_directory}/compiler_has_h5_c INFO_VER
- REGEX "^INFO:([0-9]+\\.[0-9]+\\.[0-9]+)(-patch([0-9]+))?"
+ file(STRINGS ${scratch_directory}/compiler_has_h5_c INFO_STRINGS
+ REGEX "^INFO:"
)
string(REGEX MATCH "^INFO:([0-9]+\\.[0-9]+\\.[0-9]+)(-patch([0-9]+))?"
- INFO_VER "${INFO_VER}"
+ INFO_VER "${INFO_STRINGS}"
)
set(${version} ${CMAKE_MATCH_1})
if(CMAKE_MATCH_3)
- set(${version} ${HDF5_CXX_VERSION}.${CMAKE_MATCH_3})
+ set(${version} ${HDF5_C_VERSION}.${CMAKE_MATCH_3})
endif()
set(${version} ${${version}} PARENT_SCOPE)
- execute_process(COMMAND ${CMAKE_C_COMPILER} -showconfig
- OUTPUT_VARIABLE config_output
- ERROR_VARIABLE config_error
- RESULT_VARIABLE config_result
- )
- if(config_output MATCHES "Parallel HDF5: yes")
+ if(INFO_STRINGS MATCHES "INFO:PARALLEL")
set(${is_parallel} TRUE PARENT_SCOPE)
else()
set(${is_parallel} FALSE PARENT_SCOPE)
@@ -233,8 +236,16 @@ function(_HDF5_test_regular_compiler_CXX success version is_parallel)
"#ifndef H5_NO_NAMESPACE\n"
"using namespace H5;\n"
"#endif\n"
+ "const char* info_ver = \"INFO\" \":\" H5_VERSION;\n"
+ "#ifdef H5_HAVE_PARALLEL\n"
+ "const char* info_parallel = \"INFO\" \":\" \"PARALLEL\";\n"
+ "#endif\n"
"int main(int argc, char **argv) {\n"
- " char const* info_ver = \"INFO\" \":\" H5_VERSION;\n"
+ " int require = 0;\n"
+ " require += info_ver[argc];\n"
+ "#ifdef H5_HAVE_PARALLEL\n"
+ " require += info_parallel[argc];\n"
+ "#endif\n"
" H5File file(\"foo.h5\", H5F_ACC_TRUNC);\n"
" return 0;\n"
"}")
@@ -243,11 +254,11 @@ function(_HDF5_test_regular_compiler_CXX success version is_parallel)
)
endif()
if(${success})
- file(STRINGS ${scratch_directory}/compiler_has_h5_cxx INFO_VER
- REGEX "^INFO:([0-9]+\\.[0-9]+\\.[0-9]+)(-patch([0-9]+))?"
+ file(STRINGS ${scratch_directory}/compiler_has_h5_cxx INFO_STRINGS
+ REGEX "^INFO:"
)
string(REGEX MATCH "^INFO:([0-9]+\\.[0-9]+\\.[0-9]+)(-patch([0-9]+))?"
- INFO_VER "${INFO_VER}"
+ INFO_VER "${INFO_STRINGS}"
)
set(${version} ${CMAKE_MATCH_1})
if(CMAKE_MATCH_3)
@@ -255,12 +266,7 @@ function(_HDF5_test_regular_compiler_CXX success version is_parallel)
endif()
set(${version} ${${version}} PARENT_SCOPE)
- execute_process(COMMAND ${CMAKE_CXX_COMPILER} -showconfig
- OUTPUT_VARIABLE config_output
- ERROR_VARIABLE config_error
- RESULT_VARIABLE config_result
- )
- if(config_output MATCHES "Parallel HDF5: yes")
+ if(INFO_STRINGS MATCHES "INFO:PARALLEL")
set(${is_parallel} TRUE PARENT_SCOPE)
else()
set(${is_parallel} FALSE PARENT_SCOPE)
@@ -390,6 +396,45 @@ macro( _HDF5_parse_compile_line
endforeach()
endmacro()
+# Select a preferred imported configuration from a target
+function(_HDF5_select_imported_config target imported_conf)
+ # We will first assign the value to a local variable _imported_conf, then assign
+ # it to the function argument at the end.
+ get_target_property(_imported_conf ${target} MAP_IMPORTED_CONFIG_${CMAKE_BUILD_TYPE})
+ if (NOT _imported_conf)
+ # Get available imported configurations by examining target properties
+ get_target_property(_imported_conf ${target} IMPORTED_CONFIGURATIONS)
+ if(HDF5_FIND_DEBUG)
+ message(STATUS "Found imported configurations: ${_imported_conf}")
+ endif()
+ # Find the imported configuration that we prefer.
+ # We do this by making list of configurations in order of preference,
+ # starting with ${CMAKE_BUILD_TYPE} and ending with the first imported_conf
+ set(_preferred_confs ${CMAKE_BUILD_TYPE})
+ list(GET _imported_conf 0 _fallback_conf)
+ list(APPEND _preferred_confs RELWITHDEBINFO RELEASE DEBUG ${_fallback_conf})
+ if(HDF5_FIND_DEBUG)
+ message(STATUS "Start search through imported configurations in the following order: ${_preferred_confs}")
+ endif()
+ # Now find the first of these that is present in imported_conf
+ cmake_policy(PUSH)
+ cmake_policy(SET CMP0057 NEW) # support IN_LISTS
+ foreach (_conf IN LISTS _preferred_confs)
+ if (${_conf} IN_LIST _imported_conf)
+ set(_imported_conf ${_conf})
+ break()
+ endif()
+ endforeach()
+ cmake_policy(POP)
+ endif()
+ if(HDF5_FIND_DEBUG)
+ message(STATUS "Selected imported configuration: ${_imported_conf}")
+ endif()
+ # assign value to function argument
+ set(${imported_conf} ${_imported_conf} PARENT_SCOPE)
+endfunction()
+
+
if(NOT HDF5_ROOT)
set(HDF5_ROOT $ENV{HDF5_ROOT})
endif()
@@ -446,30 +491,39 @@ if(NOT HDF5_FOUND AND NOT HDF5_NO_FIND_PACKAGE_CONFIG_FILE)
message(STATUS "Trying to get properties of target ${HDF5_${_lang}_TARGET}${_suffix}")
endif()
# Find library for this target. Complicated as on Windows with a DLL, we need to search for the import-lib.
- get_target_property(_imported_conf ${HDF5_${_lang}_TARGET}${_suffix} IMPORTED_CONFIGURATIONS)
- get_target_property(_lang_location ${HDF5_${_lang}_TARGET}${_suffix} IMPORTED_IMPLIB_${_imported_conf} )
- if (NOT _lang_location)
+ _HDF5_select_imported_config(${HDF5_${_lang}_TARGET}${_suffix} _hdf5_imported_conf)
+ get_target_property(_hdf5_lang_location ${HDF5_${_lang}_TARGET}${_suffix} IMPORTED_IMPLIB_${_hdf5_imported_conf} )
+ if (NOT _hdf5_lang_location)
# no import lib, just try LOCATION
- get_target_property(_lang_location ${HDF5_${_lang}_TARGET}${_suffix} LOCATION)
+ get_target_property(_hdf5_lang_location ${HDF5_${_lang}_TARGET}${_suffix} LOCATION_${_hdf5_imported_conf})
+ if (NOT _hdf5_lang_location)
+ get_target_property(_hdf5_lang_location ${HDF5_${_lang}_TARGET}${_suffix} LOCATION)
+ endif()
endif()
- if( _lang_location )
- set(HDF5_${_lang}_LIBRARY ${_lang_location})
+ if( _hdf5_lang_location )
+ set(HDF5_${_lang}_LIBRARY ${_hdf5_lang_location})
list(APPEND HDF5_LIBRARIES ${HDF5_${_lang}_TARGET}${_suffix})
set(HDF5_${_lang}_LIBRARIES ${HDF5_${_lang}_TARGET}${_suffix})
set(HDF5_${_lang}_FOUND True)
endif()
if(FIND_HL)
- get_target_property(__lang_hl_location ${HDF5_${_lang}_HL_TARGET}${_suffix} IMPORTED_IMPLIB_${_imported_conf} )
- if (NOT _lang_hl_location)
- get_target_property(_lang_hl_location ${HDF5_${_lang}_HL_TARGET}${_suffix} LOCATION)
+ get_target_property(__lang_hl_location ${HDF5_${_lang}_HL_TARGET}${_suffix} IMPORTED_IMPLIB_${_hdf5_imported_conf} )
+ if (NOT _hdf5_lang_hl_location)
+ get_target_property(_hdf5_lang_hl_location ${HDF5_${_lang}_HL_TARGET}${_suffix} LOCATION_${_hdf5_imported_conf})
+ if (NOT _hdf5_hl_lang_location)
+ get_target_property(_hdf5_hl_lang_location ${HDF5_${_lang}_HL_TARGET}${_suffix} LOCATION)
+ endif()
endif()
- if( _lang_hl_location )
- set(HDF5_${_lang}_HL_LIBRARY ${_lang_hl_location})
- list(APPEND HDF5_HL_LIBRARIES ${HDF5_${_lang}_TARGET}${_suffix})
- set(HDF5_${_lang}_HL_LIBRARIES ${HDF5_${_lang}_TARGET}${_suffix})
+ if( _hdf5_lang_hl_location )
+ set(HDF5_${_lang}_HL_LIBRARY ${_hdf5_lang_hl_location})
+ list(APPEND HDF5_HL_LIBRARIES ${HDF5_${_lang}_HL_TARGET}${_suffix})
+ set(HDF5_${_lang}_HL_LIBRARIES ${HDF5_${_lang}_HL_TARGET}${_suffix})
set(HDF5_HL_FOUND True)
endif()
+ unset(_hdf5_lang_hl_location)
endif()
+ unset(_hdf5_imported_conf)
+ unset(_hdf5_lang_location)
endforeach()
endif()
endif()
@@ -545,8 +599,12 @@ if(NOT HDF5_FOUND)
if("x${L}" MATCHES "hdf5")
# hdf5 library
set(_HDF5_SEARCH_OPTS_LOCAL ${_HDF5_SEARCH_OPTS})
- if(UNIX AND HDF5_USE_STATIC_LIBRARIES)
- set(_HDF5_SEARCH_NAMES_LOCAL lib${L}.a)
+ if(HDF5_USE_STATIC_LIBRARIES)
+ if(WIN32)
+ set(_HDF5_SEARCH_NAMES_LOCAL lib${L})
+ else()
+ set(_HDF5_SEARCH_NAMES_LOCAL lib${L}.a)
+ endif()
endif()
else()
# external library
@@ -573,8 +631,12 @@ if(NOT HDF5_FOUND)
if("x${L}" MATCHES "hdf5")
# hdf5 library
set(_HDF5_SEARCH_OPTS_LOCAL ${_HDF5_SEARCH_OPTS})
- if(UNIX AND HDF5_USE_STATIC_LIBRARIES)
- set(_HDF5_SEARCH_NAMES_LOCAL lib${L}.a)
+ if(HDF5_USE_STATIC_LIBRARIES)
+ if(WIN32)
+ set(_HDF5_SEARCH_NAMES_LOCAL lib${L})
+ else()
+ set(_HDF5_SEARCH_NAMES_LOCAL lib${L}.a)
+ endif()
endif()
else()
# external library
@@ -706,19 +768,22 @@ if( NOT HDF5_FOUND )
# find the HDF5 libraries
foreach(LIB IN LISTS HDF5_${__lang}_LIBRARY_NAMES)
- if(UNIX AND HDF5_USE_STATIC_LIBRARIES)
+ if(HDF5_USE_STATIC_LIBRARIES)
# According to bug 1643 on the CMake bug tracker, this is the
# preferred method for searching for a static library.
# See https://gitlab.kitware.com/cmake/cmake/issues/1643. We search
# first for the full static library name, but fall back to a
# generic search on the name if the static search fails.
set( THIS_LIBRARY_SEARCH_DEBUG
- lib${LIB}d.a lib${LIB}_debug.a ${LIB}d ${LIB}_debug
- lib${LIB}d-static.a lib${LIB}_debug-static.a ${LIB}d-static ${LIB}_debug-static )
- set( THIS_LIBRARY_SEARCH_RELEASE lib${LIB}.a ${LIB} lib${LIB}-static.a ${LIB}-static)
+ lib${LIB}d.a lib${LIB}_debug.a lib${LIB}d lib${LIB}_D lib${LIB}_debug
+ lib${LIB}d-static.a lib${LIB}_debug-static.a ${LIB}d-static ${LIB}_D-static ${LIB}_debug-static )
+ set( THIS_LIBRARY_SEARCH_RELEASE lib${LIB}.a lib${LIB} lib${LIB}-static.a ${LIB}-static)
else()
- set( THIS_LIBRARY_SEARCH_DEBUG ${LIB}d ${LIB}_debug ${LIB}d-shared ${LIB}_debug-shared)
+ set( THIS_LIBRARY_SEARCH_DEBUG ${LIB}d ${LIB}_D ${LIB}_debug ${LIB}d-shared ${LIB}_D-shared ${LIB}_debug-shared)
set( THIS_LIBRARY_SEARCH_RELEASE ${LIB} ${LIB}-shared)
+ if(WIN32)
+ list(APPEND HDF5_DEFINITIONS "-DH5_BUILT_AS_DYNAMIC_LIB")
+ endif()
endif()
find_library(HDF5_${LIB}_LIBRARY_DEBUG
NAMES ${THIS_LIBRARY_SEARCH_DEBUG}
@@ -743,18 +808,18 @@ if( NOT HDF5_FOUND )
if(FIND_HL)
foreach(LIB IN LISTS HDF5_${__lang}_HL_LIBRARY_NAMES)
- if(UNIX AND HDF5_USE_STATIC_LIBRARIES)
+ if(HDF5_USE_STATIC_LIBRARIES)
# According to bug 1643 on the CMake bug tracker, this is the
# preferred method for searching for a static library.
# See https://gitlab.kitware.com/cmake/cmake/issues/1643. We search
# first for the full static library name, but fall back to a
# generic search on the name if the static search fails.
set( THIS_LIBRARY_SEARCH_DEBUG
- lib${LIB}d.a lib${LIB}_debug.a ${LIB}d ${LIB}_debug
- lib${LIB}d-static.a lib${LIB}_debug-static.a ${LIB}d-static ${LIB}_debug-static )
- set( THIS_LIBRARY_SEARCH_RELEASE lib${LIB}.a ${LIB} lib${LIB}-static.a ${LIB}-static)
+ lib${LIB}d.a lib${LIB}_debug.a lib${LIB}d lib${LIB}_D lib${LIB}_debug
+ lib${LIB}d-static.a lib${LIB}_debug-static.a lib${LIB}d-static lib${LIB}_D-static lib${LIB}_debug-static )
+ set( THIS_LIBRARY_SEARCH_RELEASE lib${LIB}.a ${LIB} lib${LIB}-static.a lib${LIB}-static)
else()
- set( THIS_LIBRARY_SEARCH_DEBUG ${LIB}d ${LIB}_debug ${LIB}d-shared ${LIB}_debug-shared)
+ set( THIS_LIBRARY_SEARCH_DEBUG ${LIB}d ${LIB}_D ${LIB}_debug ${LIB}d-shared ${LIB}_D-shared ${LIB}_debug-shared)
set( THIS_LIBRARY_SEARCH_RELEASE ${LIB} ${LIB}-shared)
endif()
find_library(HDF5_${LIB}_LIBRARY_DEBUG
@@ -780,6 +845,7 @@ if( NOT HDF5_FOUND )
set(HDF5_HL_FOUND True)
endif()
+ _HDF5_remove_duplicates_from_beginning(HDF5_DEFINITIONS)
_HDF5_remove_duplicates_from_beginning(HDF5_INCLUDE_DIRS)
_HDF5_remove_duplicates_from_beginning(HDF5_LIBRARIES)
_HDF5_remove_duplicates_from_beginning(HDF5_HL_LIBRARIES)
@@ -855,11 +921,14 @@ if (HDF5_FIND_DEBUG)
message(STATUS "HDF5_DEFINITIONS: ${HDF5_DEFINITIONS}")
message(STATUS "HDF5_INCLUDE_DIRS: ${HDF5_INCLUDE_DIRS}")
message(STATUS "HDF5_LIBRARIES: ${HDF5_LIBRARIES}")
+ message(STATUS "HDF5_HL_LIBRARIES: ${HDF5_HL_LIBRARIES}")
foreach(__lang IN LISTS HDF5_LANGUAGE_BINDINGS)
message(STATUS "HDF5_${__lang}_DEFINITIONS: ${HDF5_${__lang}_DEFINITIONS}")
message(STATUS "HDF5_${__lang}_INCLUDE_DIR: ${HDF5_${__lang}_INCLUDE_DIR}")
message(STATUS "HDF5_${__lang}_INCLUDE_DIRS: ${HDF5_${__lang}_INCLUDE_DIRS}")
message(STATUS "HDF5_${__lang}_LIBRARY: ${HDF5_${__lang}_LIBRARY}")
message(STATUS "HDF5_${__lang}_LIBRARIES: ${HDF5_${__lang}_LIBRARIES}")
+ message(STATUS "HDF5_${__lang}_HL_LIBRARY: ${HDF5_${__lang}_HL_LIBRARY}")
+ message(STATUS "HDF5_${__lang}_HL_LIBRARIES: ${HDF5_${__lang}_HL_LIBRARIES}")
endforeach()
endif()
diff --git a/Modules/FindHTMLHelp.cmake b/Modules/FindHTMLHelp.cmake
index 84e2458af..6aab8a712 100644
--- a/Modules/FindHTMLHelp.cmake
+++ b/Modules/FindHTMLHelp.cmake
@@ -18,28 +18,28 @@
if(WIN32)
find_program(HTML_HELP_COMPILER
- hhc
- "[HKEY_CURRENT_USER\\Software\\Microsoft\\HTML Help Workshop;InstallDir]"
- "$ENV{ProgramFiles}/HTML Help Workshop"
- "C:/Program Files/HTML Help Workshop"
+ NAMES hhc
+ PATHS
+ "[HKEY_CURRENT_USER\\Software\\Microsoft\\HTML Help Workshop;InstallDir]"
+ PATH_SUFFIXES "HTML Help Workshop"
)
get_filename_component(HTML_HELP_COMPILER_PATH "${HTML_HELP_COMPILER}" PATH)
find_path(HTML_HELP_INCLUDE_PATH
- htmlhelp.h
- "${HTML_HELP_COMPILER_PATH}/include"
- "[HKEY_CURRENT_USER\\Software\\Microsoft\\HTML Help Workshop;InstallDir]/include"
- "$ENV{ProgramFiles}/HTML Help Workshop/include"
- "C:/Program Files/HTML Help Workshop/include"
+ NAMES htmlhelp.h
+ PATHS
+ "${HTML_HELP_COMPILER_PATH}/include"
+ "[HKEY_CURRENT_USER\\Software\\Microsoft\\HTML Help Workshop;InstallDir]/include"
+ PATH_SUFFIXES "HTML Help Workshop/include"
)
find_library(HTML_HELP_LIBRARY
- htmlhelp
- "${HTML_HELP_COMPILER_PATH}/lib"
- "[HKEY_CURRENT_USER\\Software\\Microsoft\\HTML Help Workshop;InstallDir]/lib"
- "$ENV{ProgramFiles}/HTML Help Workshop/lib"
- "C:/Program Files/HTML Help Workshop/lib"
+ NAMES htmlhelp
+ PATHS
+ "${HTML_HELP_COMPILER_PATH}/lib"
+ "[HKEY_CURRENT_USER\\Software\\Microsoft\\HTML Help Workshop;InstallDir]/lib"
+ PATH_SUFFIXES "HTML Help Workshop/lib"
)
mark_as_advanced(
diff --git a/Modules/FindICU.cmake b/Modules/FindICU.cmake
index 5210f0806..d9705d9db 100644
--- a/Modules/FindICU.cmake
+++ b/Modules/FindICU.cmake
@@ -55,6 +55,11 @@
# ICU_<C>_FOUND - ON if component was found
# ICU_<C>_LIBRARIES - libraries for component
#
+# ICU datafiles are reported in::
+#
+# ICU_MAKEFILE_INC - Makefile.inc
+# ICU_PKGDATA_INC - pkgdata.inc
+#
# Note that ``<C>`` is the uppercased name of the component.
#
# This module reads hints about search results from::
@@ -100,6 +105,10 @@ set(icu_programs
icupkg
gencmn)
+set(icu_data
+ Makefile.inc
+ pkgdata.inc)
+
# The ICU checks are contained in a function due to the large number
# of temporary variables needed.
function(_ICU_FIND)
@@ -116,6 +125,28 @@ function(_ICU_FIND)
endif()
endif()
+ # Find include directory
+ list(APPEND icu_include_suffixes "include")
+ find_path(ICU_INCLUDE_DIR
+ NAMES "unicode/utypes.h"
+ HINTS ${icu_roots}
+ PATH_SUFFIXES ${icu_include_suffixes}
+ DOC "ICU include directory")
+ set(ICU_INCLUDE_DIR "${ICU_INCLUDE_DIR}" PARENT_SCOPE)
+
+ # Get version
+ if(ICU_INCLUDE_DIR AND EXISTS "${ICU_INCLUDE_DIR}/unicode/uvernum.h")
+ file(STRINGS "${ICU_INCLUDE_DIR}/unicode/uvernum.h" icu_header_str
+ REGEX "^#define[\t ]+U_ICU_VERSION[\t ]+\".*\".*")
+
+ string(REGEX REPLACE "^#define[\t ]+U_ICU_VERSION[\t ]+\"([^ \\n]*)\".*"
+ "\\1" icu_version_string "${icu_header_str}")
+ set(ICU_VERSION "${icu_version_string}")
+ set(ICU_VERSION "${icu_version_string}" PARENT_SCOPE)
+ unset(icu_header_str)
+ unset(icu_version_string)
+ endif()
+
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
# 64-bit binary directory
set(_bin64 "bin64")
@@ -123,12 +154,9 @@ function(_ICU_FIND)
set(_lib64 "lib64")
endif()
- # Generic 64-bit and 32-bit directories
- list(APPEND icu_binary_suffixes "${_bin64}" "bin")
- list(APPEND icu_library_suffixes "${_lib64}" "lib")
- list(APPEND icu_include_suffixes "include")
# Find all ICU programs
+ list(APPEND icu_binary_suffixes "${_bin64}" "bin")
foreach(program ${icu_programs})
string(TOUPPER "${program}" program_upcase)
set(cache_var "ICU_${program_upcase}_EXECUTABLE")
@@ -141,27 +169,8 @@ function(_ICU_FIND)
set("${program_var}" "${${cache_var}}" PARENT_SCOPE)
endforeach()
- # Find include directory
- find_path(ICU_INCLUDE_DIR
- NAMES "unicode/utypes.h"
- HINTS ${icu_roots}
- PATH_SUFFIXES ${icu_include_suffixes}
- DOC "ICU include directory")
- set(ICU_INCLUDE_DIR "${ICU_INCLUDE_DIR}" PARENT_SCOPE)
-
- # Get version
- if(ICU_INCLUDE_DIR AND EXISTS "${ICU_INCLUDE_DIR}/unicode/uvernum.h")
- file(STRINGS "${ICU_INCLUDE_DIR}/unicode/uvernum.h" icu_header_str
- REGEX "^#define[\t ]+U_ICU_VERSION[\t ]+\".*\".*")
-
- string(REGEX REPLACE "^#define[\t ]+U_ICU_VERSION[\t ]+\"([^ \\n]*)\".*"
- "\\1" icu_version_string "${icu_header_str}")
- set(ICU_VERSION "${icu_version_string}" PARENT_SCOPE)
- unset(icu_header_str)
- unset(icu_version_string)
- endif()
-
# Find all ICU libraries
+ list(APPEND icu_library_suffixes "${_lib64}" "lib")
set(ICU_REQUIRED_LIBS_FOUND ON)
foreach(component ${ICU_FIND_COMPONENTS})
string(TOUPPER "${component}" component_upcase)
@@ -233,6 +242,32 @@ function(_ICU_FIND)
set(_ICU_REQUIRED_LIBS_FOUND "${ICU_REQUIRED_LIBS_FOUND}" PARENT_SCOPE)
set(ICU_LIBRARY "${ICU_LIBRARY}" PARENT_SCOPE)
+ # Find all ICU data files
+ if(CMAKE_LIBRARY_ARCHITECTURE)
+ list(APPEND icu_data_suffixes
+ "${_lib64}/${CMAKE_LIBRARY_ARCHITECTURE}/icu/${ICU_VERSION}"
+ "lib/${CMAKE_LIBRARY_ARCHITECTURE}/icu/${ICU_VERSION}"
+ "${_lib64}/${CMAKE_LIBRARY_ARCHITECTURE}/icu"
+ "lib/${CMAKE_LIBRARY_ARCHITECTURE}/icu")
+ endif()
+ list(APPEND icu_data_suffixes
+ "${_lib64}/icu/${ICU_VERSION}"
+ "lib/icu/${ICU_VERSION}"
+ "${_lib64}/icu"
+ "lib/icu")
+ foreach(data ${icu_data})
+ string(TOUPPER "${data}" data_upcase)
+ string(REPLACE "." "_" data_upcase "${data_upcase}")
+ set(cache_var "ICU_${data_upcase}")
+ set(data_var "ICU_${data_upcase}")
+ find_file("${cache_var}" "${data}"
+ HINTS ${icu_roots}
+ PATH_SUFFIXES ${icu_data_suffixes}
+ DOC "ICU ${data} data file")
+ mark_as_advanced(cache_var)
+ set("${data_var}" "${${cache_var}}" PARENT_SCOPE)
+ endforeach()
+
if(NOT ICU_FIND_QUIETLY)
if(ICU_LIBS_FOUND)
message(STATUS "Found the following ICU libraries:")
@@ -334,6 +369,15 @@ if(ICU_DEBUG)
unset(program_lib)
endforeach()
+ foreach(data IN LISTS icu_data)
+ string(TOUPPER "${data}" data_upcase)
+ string(REPLACE "." "_" data_upcase "${data_upcase}")
+ set(data_lib "ICU_${data_upcase}")
+ message(STATUS "${data} data: ${${data_lib}}")
+ unset(data_upcase)
+ unset(data_lib)
+ endforeach()
+
foreach(component IN LISTS ICU_FIND_COMPONENTS)
string(TOUPPER "${component}" component_upcase)
set(component_lib "ICU_${component_upcase}_LIBRARIES")
diff --git a/Modules/FindIce.cmake b/Modules/FindIce.cmake
index e0286ee2c..b37f7965b 100644
--- a/Modules/FindIce.cmake
+++ b/Modules/FindIce.cmake
@@ -10,8 +10,16 @@
#
# This module supports multiple components.
# Components can include any of: ``Freeze``, ``Glacier2``, ``Ice``,
-# ``IceBox``, ``IceDB``, ``IceGrid``, ``IcePatch``, ``IceSSL``,
-# ``IceStorm``, ``IceUtil``, ``IceXML``, or ``Slice``.
+# ``IceBox``, ``IceDB``, ``IceDiscovery``, ``IceGrid``,
+# ``IceLocatorDiscovery``, ``IcePatch``, ``IceSSL``, ``IceStorm``,
+# ``IceUtil``, ``IceXML``, or ``Slice``.
+#
+# Ice 3.7 and later also include C++11-specific components:
+# ``Glacier2++11``, ``Ice++11``, ``IceBox++11``, ``IceDiscovery++11``
+# ``IceGrid``, ``IceLocatorDiscovery++11``, ``IceSSL++11``,
+# ``IceStorm++11``
+#
+# Note that the set of supported components is Ice version-specific.
#
# This module reports information about the Ice installation in
# several variables. General variables::
@@ -28,7 +36,7 @@
# Ice::<C>
#
# Where ``<C>`` is the name of an Ice component, for example
-# ``Ice::Glacier2``.
+# ``Ice::Glacier2`` or ``Ice++11``.
#
# Ice slice programs are reported in::
#
@@ -39,6 +47,7 @@
# Ice_SLICE2HTML_EXECUTABLE - path to slice2html executable
# Ice_SLICE2JAVA_EXECUTABLE - path to slice2java executable
# Ice_SLICE2JS_EXECUTABLE - path to slice2js executable
+# Ice_SLICE2OBJC_EXECUTABLE - path to slice2objc executable
# Ice_SLICE2PHP_EXECUTABLE - path to slice2php executable
# Ice_SLICE2PY_EXECUTABLE - path to slice2py executable
# Ice_SLICE2RB_EXECUTABLE - path to slice2rb executable
@@ -47,10 +56,13 @@
#
# Ice_GLACIER2ROUTER_EXECUTABLE - path to glacier2router executable
# Ice_ICEBOX_EXECUTABLE - path to icebox executable
+# Ice_ICEBOXXX11_EXECUTABLE - path to icebox++11 executable
# Ice_ICEBOXADMIN_EXECUTABLE - path to iceboxadmin executable
# Ice_ICEBOXD_EXECUTABLE - path to iceboxd executable
# Ice_ICEBOXNET_EXECUTABLE - path to iceboxnet executable
+# Ice_ICEBRIDGE_EXECUTABLE - path to icebridge executable
# Ice_ICEGRIDADMIN_EXECUTABLE - path to icegridadmin executable
+# Ice_ICEGRIDDB_EXECUTABLE - path to icegriddb executable
# Ice_ICEGRIDNODE_EXECUTABLE - path to icegridnode executable
# Ice_ICEGRIDNODED_EXECUTABLE - path to icegridnoded executable
# Ice_ICEGRIDREGISTRY_EXECUTABLE - path to icegridregistry executable
@@ -60,6 +72,7 @@
# Ice_ICEPATCH2SERVER_EXECUTABLE - path to icepatch2server executable
# Ice_ICESERVICEINSTALL_EXECUTABLE - path to iceserviceinstall executable
# Ice_ICESTORMADMIN_EXECUTABLE - path to icestormadmin executable
+# Ice_ICESTORMDB_EXECUTABLE - path to icestormdb executable
# Ice_ICESTORMMIGRATE_EXECUTABLE - path to icestormmigrate executable
#
# Ice db programs (Windows only; standard system versions on all other
@@ -95,6 +108,13 @@
# The environment variable ``ICE_HOME`` may also be used; the
# Ice_HOME variable takes precedence.
#
+# .. note::
+# On Windows, Ice 3.7.0 and later provide libraries via the NuGet
+# package manager. Appropriate NuGet packages will be searched for
+# using ``CMAKE_PREFIX_PATH``, or alternatively ``Ice_HOME`` may be
+# set to the location of a specific NuGet package to restrict the
+# search.
+#
# The following cache variables may also be set::
#
# Ice_<P>_EXECUTABLE - the path to executable <P>
@@ -124,12 +144,67 @@
# Written by Roger Leigh <rleigh@codelibre.net>
+ set(_Ice_db_programs
+ db_archive
+ db_checkpoint
+ db_deadlock
+ db_dump
+ db_hotbackup
+ db_load
+ db_log_verify
+ db_printlog
+ db_recover
+ db_stat
+ db_tuner
+ db_upgrade
+ db_verify
+ dumpdb
+ transformdb)
+
+ set(_Ice_programs
+ glacier2router
+ icebox
+ icebox++11
+ iceboxadmin
+ iceboxd
+ iceboxnet
+ icebridge
+ icegridadmin
+ icegriddb
+ icegridnode
+ icegridnoded
+ icegridregistry
+ icegridregistryd
+ icepatch2calc
+ icepatch2client
+ icepatch2server
+ iceserviceinstall
+ icestormadmin
+ icestormdb
+ icestormmigrate)
+
+ set(_Ice_slice_programs
+ slice2cpp
+ slice2cs
+ slice2freezej
+ slice2freeze
+ slice2html
+ slice2java
+ slice2js
+ slice2objc
+ slice2php
+ slice2py
+ slice2rb)
+
+
# The Ice checks are contained in a function due to the large number
# of temporary variables needed.
function(_Ice_FIND)
# Released versions of Ice, including generic short forms
set(ice_versions
3
+ 3.7
+ 3.7.0
3.6
3.6.3
3.6.2
@@ -146,6 +221,14 @@ function(_Ice_FIND)
3.3.1
3.3.0)
+ foreach(ver ${ice_versions})
+ string(REGEX MATCH "^([0-9]+)\\.([0-9]+)\$" two_digit_version_match "${ver}")
+ if(two_digit_version_match)
+ string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\$" "\\1\\2" two_digit_version "${ver}")
+ list(APPEND ice_suffix_versions "${two_digit_version}")
+ endif()
+ endforeach()
+
# Set up search paths, taking compiler into account. Search Ice_HOME,
# with ICE_HOME in the environment as a fallback if unset.
if(Ice_HOME)
@@ -159,52 +242,85 @@ function(_Ice_FIND)
endif()
endif()
+ set(_bin "bin/Win32")
+ set(_lib "lib/Win32")
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+ set(_bin "bin/x64")
+ set(_lib "lib/x64")
# 64-bit path suffix
set(_x64 "/x64")
# 64-bit library directory
set(_lib64 "lib64")
endif()
- if(MSVC_VERSION)
- # VS 8.0
- if(NOT MSVC_VERSION VERSION_LESS 1400 AND MSVC_VERSION VERSION_LESS 1500)
- set(vcver "vc80")
- set(vcyear "2005")
- # VS 9.0
- elseif(NOT MSVC_VERSION VERSION_LESS 1500 AND MSVC_VERSION VERSION_LESS 1600)
- set(vcver "vc90")
+ unset(vcvers)
+ if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
+ if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10)
+ set(vcvers "141;140")
+ elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19)
+ set(vcvers "140")
+ elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18)
+ set(vcvers "120")
+ elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 17)
+ set(vcvers "110")
+ elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 16)
+ set(vcvers "100")
+ elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 15)
+ set(vcvers "90")
set(vcyear "2008")
- # VS 10.0
- elseif(NOT MSVC_VERSION VERSION_LESS 1600 AND MSVC_VERSION VERSION_LESS 1700)
- set(vcver "vc100")
- # VS 11.0
- elseif(NOT MSVC_VERSION VERSION_LESS 1700 AND MSVC_VERSION VERSION_LESS 1800)
- set(vcver "vc110")
- # VS 12.0
- elseif(NOT MSVC_VERSION VERSION_LESS 1800 AND MSVC_VERSION VERSION_LESS 1900)
- set(vcver "vc120")
- # VS 14.0
- elseif(NOT MSVC_VERSION VERSION_LESS 1900 AND MSVC_VERSION VERSION_LESS 2000)
- set(vcver "vc140")
+ elseif(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 14)
+ set(vcvers "80")
+ set(vcyear "2005")
+ else() # Unknown version
+ set(vcvers Unknown)
endif()
endif()
# For compatibility with ZeroC Windows builds.
- if(vcver)
- # Earlier Ice (3.3) builds don't use vcnnn subdirectories, but are harmless to check.
- list(APPEND ice_binary_suffixes "bin/${vcver}${_x64}" "bin/${vcver}")
- list(APPEND ice_library_suffixes "lib/${vcver}${_x64}" "lib/${vcver}")
+ if(vcvers)
+ list(APPEND ice_binary_suffixes "build/native/${_bin}/Release" "tools")
+ list(APPEND ice_debug_library_suffixes "build/native/${_lib}/Debug")
+ list(APPEND ice_release_library_suffixes "build/native/${_lib}/Release")
+ foreach(vcver IN LISTS vcvers)
+ # Earlier Ice (3.3) builds don't use vcnnn subdirectories, but are harmless to check.
+ list(APPEND ice_binary_suffixes "bin/vc${vcver}${_x64}" "bin/vc${vcver}")
+ list(APPEND ice_debug_library_suffixes "lib/vc${vcver}${_x64}" "lib/vc${vcver}")
+ list(APPEND ice_release_library_suffixes "lib/vc${vcver}${_x64}" "lib/vc${vcver}")
+ endforeach()
endif()
# Generic 64-bit and 32-bit directories
list(APPEND ice_binary_suffixes "bin${_x64}" "bin")
- list(APPEND ice_library_suffixes "libx32" "${_lib64}" "lib${_x64}" "lib")
+ list(APPEND ice_debug_library_suffixes "libx32" "${_lib64}" "lib${_x64}" "lib")
+ list(APPEND ice_release_library_suffixes "libx32" "${_lib64}" "lib${_x64}" "lib")
+ if(vcvers)
+ list(APPEND ice_include_suffixes "build/native/include")
+ endif()
list(APPEND ice_include_suffixes "include")
list(APPEND ice_slice_suffixes "slice")
# On Windows, look in the registry for install locations. Different
# versions of Ice install support different compiler versions.
- if(vcver)
+ if(vcvers)
+ foreach(ice_version ${ice_versions})
+ foreach(vcver IN LISTS vcvers)
+ list(APPEND ice_nuget_dirs "zeroc.ice.v${vcver}.${ice_version}")
+ list(APPEND freeze_nuget_dirs "zeroc.freeze.v${vcver}.${ice_version}")
+ endforeach()
+ endforeach()
+ find_path(Ice_NUGET_DIR
+ NAMES "tools/slice2cpp.exe"
+ PATH_SUFFIXES ${ice_nuget_dirs}
+ DOC "Ice NuGet directory")
+ if(Ice_NUGET_DIR)
+ list(APPEND ice_roots "${Ice_NUGET_DIR}")
+ endif()
+ find_path(Freeze_NUGET_DIR
+ NAMES "tools/slice2freeze.exe"
+ PATH_SUFFIXES ${freeze_nuget_dirs}
+ DOC "Freeze NuGet directory")
+ if(Freeze_NUGET_DIR)
+ list(APPEND ice_roots "${Freeze_NUGET_DIR}")
+ endif()
foreach(ice_version ${ice_versions})
# Ice 3.3 releases use a Visual Studio year suffix and value is
# enclosed in double quotes, though only the leading quote is
@@ -239,55 +355,8 @@ function(_Ice_FIND)
endforeach()
endif()
- set(db_programs
- db_archive
- db_checkpoint
- db_deadlock
- db_dump
- db_hotbackup
- db_load
- db_log_verify
- db_printlog
- db_recover
- db_stat
- db_tuner
- db_upgrade
- db_verify
- dumpdb
- transformdb)
-
- set(ice_programs
- glacier2router
- icebox
- iceboxadmin
- iceboxd
- iceboxnet
- icegridadmin
- icegridnode
- icegridnoded
- icegridregistry
- icegridregistryd
- icepatch2calc
- icepatch2client
- icepatch2server
- iceserviceinstall
- icestormadmin
- icestormmigrate)
-
- set(slice_programs
- slice2cpp
- slice2cs
- slice2freezej
- slice2freeze
- slice2html
- slice2java
- slice2js
- slice2php
- slice2py
- slice2rb)
-
# Find all Ice programs
- foreach(program ${db_programs} ${ice_programs} ${slice_programs})
+ foreach(program ${_Ice_db_programs} ${_Ice_programs} ${_Ice_slice_programs})
string(TOUPPER "${program}" program_upcase)
set(cache_var "Ice_${program_upcase}_EXECUTABLE")
set(program_var "Ice_${program_upcase}_EXECUTABLE")
@@ -329,6 +398,13 @@ function(_Ice_FIND)
DOC "Ice include directory")
set(Ice_INCLUDE_DIR "${Ice_INCLUDE_DIR}" PARENT_SCOPE)
+ find_path(Freeze_INCLUDE_DIR
+ NAMES "Freeze/Freeze.h"
+ HINTS ${ice_roots}
+ PATH_SUFFIXES ${ice_include_suffixes}
+ DOC "Freeze include directory")
+ set(Freeze_INCLUDE_DIR "${Freeze_INCLUDE_DIR}" PARENT_SCOPE)
+
# In common use on Linux, MacOS X (homebrew) and FreeBSD; prefer
# version-specific dir
list(APPEND ice_slice_paths
@@ -336,6 +412,7 @@ function(_Ice_FIND)
list(APPEND ice_slice_suffixes
"Ice-${Ice_VERSION_SLICE2CPP_FULL}/slice"
"Ice-${Ice_VERSION_SLICE2CPP_SHORT}/slice"
+ "ice/slice"
Ice)
# Find slice directory
@@ -356,13 +433,39 @@ function(_Ice_FIND)
set(component_cache_release "${component_cache}_RELEASE")
set(component_cache_debug "${component_cache}_DEBUG")
set(component_found "${component_upcase}_FOUND")
- find_library("${component_cache_release}" "${component}"
+ set(component_library "${component}")
+ unset(component_library_release_names)
+ unset(component_library_debug_names)
+ if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
+ string(REGEX MATCH ".+\\+\\+11$" component_library_cpp11 "${component_library}")
+ if(component_library_cpp11)
+ string(REGEX REPLACE "^(.+)(\\+\\+11)$" "\\1" component_library "${component_library}")
+ endif()
+ foreach(suffix_ver ${ice_suffix_versions})
+ set(_name "${component_library}${suffix_ver}")
+ if(component_library_cpp11)
+ string(APPEND _name "++11")
+ endif()
+ list(APPEND component_library_debug_names "${_name}d")
+ list(APPEND component_library_release_names "${_name}")
+ endforeach()
+ set(_name "${component_library}")
+ if(component_library_cpp11)
+ string(APPEND _name "++11")
+ endif()
+ list(APPEND component_library_debug_names "${_name}d")
+ list(APPEND component_library_release_names "${_name}")
+ else()
+ list(APPEND component_library_debug_names "${component_library}d")
+ list(APPEND component_library_release_names "${component_library}")
+ endif()
+ find_library("${component_cache_release}" ${component_library_release_names}
HINTS ${ice_roots}
- PATH_SUFFIXES ${ice_library_suffixes}
+ PATH_SUFFIXES ${ice_release_library_suffixes}
DOC "Ice ${component} library (release)")
- find_library("${component_cache_debug}" "${component}d"
+ find_library("${component_cache_debug}" ${component_library_debug_names}
HINTS ${ice_roots}
- PATH_SUFFIXES ${ice_library_suffixes}
+ PATH_SUFFIXES ${ice_debug_library_suffixes}
DOC "Ice ${component} library (debug)")
include(${CMAKE_CURRENT_LIST_DIR}/SelectLibraryConfigurations.cmake)
select_library_configurations(Ice_${component_upcase})
@@ -410,9 +513,14 @@ function(_Ice_FIND)
if(Ice_DEBUG)
message(STATUS "--------FindIce.cmake search debug--------")
message(STATUS "ICE binary path search order: ${ice_roots}")
+ message(STATUS "ICE binary suffixes: ${ice_binary_suffixes}")
message(STATUS "ICE include path search order: ${ice_roots}")
+ message(STATUS "ICE include suffixes: ${ice_include_suffixes}")
message(STATUS "ICE slice path search order: ${ice_roots} ${ice_slice_paths}")
+ message(STATUS "ICE slice suffixes: ${ice_slice_suffixes}")
message(STATUS "ICE library path search order: ${ice_roots}")
+ message(STATUS "ICE debug library suffixes: ${ice_debug_library_suffixes}")
+ message(STATUS "ICE release library suffixes: ${ice_release_library_suffixes}")
message(STATUS "----------------")
endif()
endfunction()
@@ -434,6 +542,9 @@ unset(_Ice_REQUIRED_LIBS_FOUND)
if(Ice_FOUND)
set(Ice_INCLUDE_DIRS "${Ice_INCLUDE_DIR}")
+ if (Freeze_INCLUDE_DIR)
+ list(APPEND Ice_INCLUDE_DIRS "${Freeze_INCLUDE_DIR}")
+ endif()
set(Ice_SLICE_DIRS "${Ice_SLICE_DIR}")
set(Ice_LIBRARIES "${Ice_LIBRARY}")
foreach(_Ice_component ${Ice_FIND_COMPONENTS})
@@ -448,10 +559,8 @@ if(Ice_FOUND)
set("${_Ice_component_lib}" "${${_Ice_component_cache}}")
if(NOT TARGET ${_Ice_imported_target})
add_library(${_Ice_imported_target} UNKNOWN IMPORTED)
- if()
- set_target_properties(${_Ice_imported_target} PROPERTIES
- INTERFACE_INCLUDE_DIRECTORIES "${Ice_INCLUDE_DIR}")
- endif()
+ set_target_properties(${_Ice_imported_target} PROPERTIES
+ INTERFACE_INCLUDE_DIRECTORIES "${Ice_INCLUDE_DIRS}")
if(EXISTS "${${_Ice_component_cache}}")
set_target_properties(${_Ice_imported_target} PROPERTIES
IMPORTED_LINK_INTERFACE_LANGUAGES "CXX"
@@ -488,50 +597,13 @@ if(Ice_DEBUG)
message(STATUS "Ice_INCLUDE_DIR directory: ${Ice_INCLUDE_DIR}")
message(STATUS "Ice_SLICE_DIR directory: ${Ice_SLICE_DIR}")
message(STATUS "Ice_LIBRARIES: ${Ice_LIBRARIES}")
+ message(STATUS "Freeze_INCLUDE_DIR directory: ${Freeze_INCLUDE_DIR}")
+ message(STATUS "Ice_INCLUDE_DIRS directory: ${Ice_INCLUDE_DIRS}")
- message(STATUS "slice2cpp executable: ${Ice_SLICE2CPP_EXECUTABLE}")
- message(STATUS "slice2cs executable: ${Ice_SLICE2CS_EXECUTABLE}")
- message(STATUS "slice2freezej executable: ${Ice_SLICE2FREEZEJ_EXECUTABLE}")
- message(STATUS "slice2freeze executable: ${Ice_SLICE2FREEZE_EXECUTABLE}")
- message(STATUS "slice2html executable: ${Ice_SLICE2HTML_EXECUTABLE}")
- message(STATUS "slice2java executable: ${Ice_SLICE2JAVA_EXECUTABLE}")
- message(STATUS "slice2js executable: ${Ice_SLICE2JS_EXECUTABLE}")
- message(STATUS "slice2php executable: ${Ice_SLICE2PHP_EXECUTABLE}")
- message(STATUS "slice2py executable: ${Ice_SLICE2PY_EXECUTABLE}")
- message(STATUS "slice2rb executable: ${Ice_SLICE2RB_EXECUTABLE}")
- message(STATUS "glacier2router executable: ${Ice_GLACIER2ROUTER_EXECUTABLE}")
-
- message(STATUS "icebox executable: ${Ice_ICEBOX_EXECUTABLE}")
- message(STATUS "iceboxadmin executable: ${Ice_ICEBOXADMIN_EXECUTABLE}")
- message(STATUS "iceboxd executable: ${Ice_ICEBOXD_EXECUTABLE}")
- message(STATUS "iceboxnet executable: ${Ice_ICEBOXNET_EXECUTABLE}")
- message(STATUS "icegridadmin executable: ${Ice_ICEGRIDADMIN_EXECUTABLE}")
- message(STATUS "icegridnode executable: ${Ice_ICEGRIDNODE_EXECUTABLE}")
- message(STATUS "icegridnoded executable: ${Ice_ICEGRIDNODED_EXECUTABLE}")
- message(STATUS "icegridregistry executable: ${Ice_ICEGRIDREGISTRY_EXECUTABLE}")
- message(STATUS "icegridregistryd executable: ${Ice_ICEGRIDREGISTRYD_EXECUTABLE}")
- message(STATUS "icepatch2calc executable: ${Ice_ICEPATCH2CALC_EXECUTABLE}")
- message(STATUS "icepatch2client executable: ${Ice_ICEPATCH2CLIENT_EXECUTABLE}")
- message(STATUS "icepatch2server executable: ${Ice_ICEPATCH2SERVER_EXECUTABLE}")
- message(STATUS "iceserviceinstall executable: ${Ice_ICESERVICEINSTALL_EXECUTABLE}")
- message(STATUS "icestormadmin executable: ${Ice_ICESTORMADMIN_EXECUTABLE}")
- message(STATUS "icestormmigrate executable: ${Ice_ICESTORMMIGRATE_EXECUTABLE}")
-
- message(STATUS "db_archive executable: ${Ice_DB_ARCHIVE_EXECUTABLE}")
- message(STATUS "db_checkpoint executable: ${Ice_DB_CHECKPOINT_EXECUTABLE}")
- message(STATUS "db_deadlock executable: ${Ice_DB_DEADLOCK_EXECUTABLE}")
- message(STATUS "db_dump executable: ${Ice_DB_DUMP_EXECUTABLE}")
- message(STATUS "db_hotbackup executable: ${Ice_DB_HOTBACKUP_EXECUTABLE}")
- message(STATUS "db_load executable: ${Ice_DB_LOAD_EXECUTABLE}")
- message(STATUS "db_log_verify executable: ${Ice_DB_LOG_VERIFY_EXECUTABLE}")
- message(STATUS "db_printlog executable: ${Ice_DB_PRINTLOG_EXECUTABLE}")
- message(STATUS "db_recover executable: ${Ice_DB_RECOVER_EXECUTABLE}")
- message(STATUS "db_stat executable: ${Ice_DB_STAT_EXECUTABLE}")
- message(STATUS "db_tuner executable: ${Ice_DB_TUNER_EXECUTABLE}")
- message(STATUS "db_upgrade executable: ${Ice_DB_UPGRADE_EXECUTABLE}")
- message(STATUS "db_verify executable: ${Ice_DB_VERIFY_EXECUTABLE}")
- message(STATUS "dumpdb executable: ${Ice_DUMPDB_EXECUTABLE}")
- message(STATUS "transformdb executable: ${Ice_TRANSFORMDB_EXECUTABLE}")
+ foreach(program ${_Ice_db_programs} ${_Ice_programs} ${_Ice_slice_programs})
+ string(TOUPPER "${program}" program_upcase)
+ message(STATUS "${program} executable: ${Ice_${program_upcase}_EXECUTABLE}")
+ endforeach()
foreach(component ${Ice_FIND_COMPONENTS})
string(TOUPPER "${component}" component_upcase)
@@ -542,3 +614,7 @@ if(Ice_DEBUG)
endforeach()
message(STATUS "----------------")
endif()
+
+unset(_Ice_db_programs)
+unset(_Ice_programs)
+unset(_Ice_slice_programs)
diff --git a/Modules/FindJava.cmake b/Modules/FindJava.cmake
index eb2242bf5..b913e170f 100644
--- a/Modules/FindJava.cmake
+++ b/Modules/FindJava.cmake
@@ -39,7 +39,7 @@
# Java_VERSION_MINOR = The minor version of the package found.
# Java_VERSION_PATCH = The patch version of the package found.
# Java_VERSION_TWEAK = The tweak version of the package found (after '_')
-# Java_VERSION = This is set to: $major.$minor.$patch(.$tweak)
+# Java_VERSION = This is set to: $major[.$minor[.$patch[.$tweak]]]
#
#
#
@@ -133,39 +133,56 @@ if(Java_JAVA_EXECUTABLE)
message( STATUS "Warning, could not run java -version")
endif()
else()
- # extract major/minor version and patch level from "java -version" output
- # Tested on linux using
- # 1. Sun / Sun OEM
- # 2. OpenJDK 1.6
- # 3. GCJ 1.5
- # 4. Kaffe 1.4.2
- # 5. OpenJDK 1.7.x on OpenBSD
- if(var MATCHES "java version \"([0-9]+\\.[0-9]+\\.[0-9_.]+.*)\"")
- # This is most likely Sun / OpenJDK, or maybe GCJ-java compat layer
+ # Extract version components (up to 4 levels) from "java -version" output.
+ set(_java_version_regex [[(([0-9]+)(\.([0-9]+)(\.([0-9]+)(_([0-9]+))?)?)?.*)]])
+ if(var MATCHES "java version \"${_java_version_regex}\"")
+ # Sun, GCJ, older OpenJDK
set(Java_VERSION_STRING "${CMAKE_MATCH_1}")
+ set(Java_VERSION_MAJOR "${CMAKE_MATCH_2}")
+ set(Java_VERSION_MINOR "${CMAKE_MATCH_4}")
+ set(Java_VERSION_PATCH "${CMAKE_MATCH_6}")
+ set(Java_VERSION_TWEAK "${CMAKE_MATCH_8}")
+ elseif(var MATCHES "openjdk version \"${_java_version_regex}\"")
+ # OpenJDK
+ set(Java_VERSION_STRING "${CMAKE_MATCH_1}")
+ set(Java_VERSION_MAJOR "${CMAKE_MATCH_2}")
+ set(Java_VERSION_MINOR "${CMAKE_MATCH_4}")
+ set(Java_VERSION_PATCH "${CMAKE_MATCH_6}")
+ set(Java_VERSION_TWEAK "${CMAKE_MATCH_8}")
elseif(var MATCHES "openjdk version \"([0-9]+)-[A-Za-z]+\"")
# OpenJDK 9 early access builds or locally built
set(Java_VERSION_STRING "1.${CMAKE_MATCH_1}.0")
- elseif(var MATCHES "java full version \"kaffe-([0-9]+\\.[0-9]+\\.[0-9_]+)\"")
+ set(Java_VERSION_MAJOR "1")
+ set(Java_VERSION_MINOR "${CMAKE_MATCH_1}")
+ set(Java_VERSION_PATCH "0")
+ set(Java_VERSION_TWEAK "")
+ elseif(var MATCHES "java full version \"kaffe-${_java_version_regex}\"")
# Kaffe style
set(Java_VERSION_STRING "${CMAKE_MATCH_1}")
- elseif(var MATCHES "openjdk version \"([0-9]+\\.[0-9]+\\.[0-9_]+.*)\"")
- # OpenJDK ver 1.7.x on OpenBSD
- set(Java_VERSION_STRING "${CMAKE_MATCH_1}")
+ set(Java_VERSION_MAJOR "${CMAKE_MATCH_2}")
+ set(Java_VERSION_MINOR "${CMAKE_MATCH_4}")
+ set(Java_VERSION_PATCH "${CMAKE_MATCH_6}")
+ set(Java_VERSION_TWEAK "${CMAKE_MATCH_8}")
else()
if(NOT Java_FIND_QUIETLY)
- message(WARNING "regex not supported: ${var}. Please report")
+ string(REPLACE "\n" "\n " ver_msg "\n${var}")
+ message(WARNING "Java version not recognized:${ver_msg}\nPlease report.")
endif()
+ set(Java_VERSION_STRING "")
+ set(Java_VERSION_MAJOR "")
+ set(Java_VERSION_MINOR "")
+ set(Java_VERSION_PATCH "")
+ set(Java_VERSION_TWEAK "")
endif()
- string( REGEX REPLACE "([0-9]+).*" "\\1" Java_VERSION_MAJOR "${Java_VERSION_STRING}" )
- string( REGEX REPLACE "[0-9]+\\.([0-9]+).*" "\\1" Java_VERSION_MINOR "${Java_VERSION_STRING}" )
- string( REGEX REPLACE "[0-9]+\\.[0-9]+\\.([0-9]+).*" "\\1" Java_VERSION_PATCH "${Java_VERSION_STRING}" )
- # warning tweak version can be empty:
- string( REGEX REPLACE "[0-9]+\\.[0-9]+\\.[0-9]+[_\\.]?([0-9]*).*$" "\\1" Java_VERSION_TWEAK "${Java_VERSION_STRING}" )
- if( Java_VERSION_TWEAK STREQUAL "" ) # check case where tweak is not defined
- set(Java_VERSION ${Java_VERSION_MAJOR}.${Java_VERSION_MINOR}.${Java_VERSION_PATCH})
- else()
- set(Java_VERSION ${Java_VERSION_MAJOR}.${Java_VERSION_MINOR}.${Java_VERSION_PATCH}.${Java_VERSION_TWEAK})
+ set(Java_VERSION "${Java_VERSION_MAJOR}")
+ if(NOT "x${Java_VERSION}" STREQUAL "x")
+ foreach(c MINOR PATCH TWEAK)
+ if(NOT "x${Java_VERSION_${c}}" STREQUAL "x")
+ string(APPEND Java_VERSION ".${Java_VERSION_${c}}")
+ else()
+ break()
+ endif()
+ endforeach()
endif()
endif()
@@ -254,7 +271,7 @@ else()
find_package_handle_standard_args(Java
REQUIRED_VARS Java_JAVA_EXECUTABLE Java_JAR_EXECUTABLE Java_JAVAC_EXECUTABLE
Java_JAVAH_EXECUTABLE Java_JAVADOC_EXECUTABLE
- VERSION_VAR Java_VERSION
+ VERSION_VAR Java_VERSION_STRING
)
endif()
diff --git a/Modules/FindLibXml2.cmake b/Modules/FindLibXml2.cmake
index 613f927e2..8ac2980d6 100644
--- a/Modules/FindLibXml2.cmake
+++ b/Modules/FindLibXml2.cmake
@@ -5,18 +5,37 @@
# FindLibXml2
# -----------
#
-# Try to find the LibXml2 xml processing library
+# Find the XML processing library (libxml2).
#
-# Once done this will define
+# Result variables
+# ^^^^^^^^^^^^^^^^
#
-# ::
+# This module will set the following variables in your project:
#
-# LIBXML2_FOUND - System has LibXml2
-# LIBXML2_INCLUDE_DIR - The LibXml2 include directory
-# LIBXML2_LIBRARIES - The libraries needed to use LibXml2
-# LIBXML2_DEFINITIONS - Compiler switches required for using LibXml2
-# LIBXML2_XMLLINT_EXECUTABLE - The XML checking tool xmllint coming with LibXml2
-# LIBXML2_VERSION_STRING - the version of LibXml2 found (since CMake 2.8.8)
+# ``LIBXML2_FOUND``
+# true if libxml2 headers and libraries were found
+# ``LIBXML2_INCLUDE_DIR``
+# the directory containing LibXml2 headers
+# ``LIBXML2_INCLUDE_DIRS``
+# list of the include directories needed to use LibXml2
+# ``LIBXML2_LIBRARIES``
+# LibXml2 libraries to be linked
+# ``LIBXML2_DEFINITIONS``
+# the compiler switches required for using LibXml2
+# ``LIBXML2_XMLLINT_EXECUTABLE``
+# path to the XML checking tool xmllint coming with LibXml2
+# ``LIBXML2_VERSION_STRING``
+# the version of LibXml2 found (since CMake 2.8.8)
+#
+# Cache variables
+# ^^^^^^^^^^^^^^^
+#
+# The following cache variables may also be set:
+#
+# ``LIBXML2_INCLUDE_DIR``
+# the directory containing LibXml2 headers
+# ``LIBXML2_LIBRARY``
+# path to the LibXml2 library
# use pkg-config to get the directories and then use these values
# in the find_path() and find_library() calls
@@ -31,7 +50,14 @@ find_path(LIBXML2_INCLUDE_DIR NAMES libxml/xpath.h
PATH_SUFFIXES libxml2
)
-find_library(LIBXML2_LIBRARIES NAMES xml2 libxml2
+# CMake 3.9 and below used 'LIBXML2_LIBRARIES' as the name of
+# the cache entry storing the find_library result. Use the
+# value if it was set by the project or user.
+if(DEFINED LIBXML2_LIBRARIES AND NOT DEFINED LIBXML2_LIBRARY)
+ set(LIBXML2_LIBRARY ${LIBXML2_LIBRARIES})
+endif()
+
+find_library(LIBXML2_LIBRARY NAMES xml2 libxml2
HINTS
${PC_LIBXML_LIBDIR}
${PC_LIBXML_LIBRARY_DIRS}
@@ -52,9 +78,12 @@ elseif(LIBXML2_INCLUDE_DIR AND EXISTS "${LIBXML2_INCLUDE_DIR}/libxml/xmlversion.
unset(libxml2_version_str)
endif()
+set(LIBXML2_INCLUDE_DIRS ${LIBXML2_INCLUDE_DIR} ${PC_LIBXML_INCLUDE_DIRS})
+set(LIBXML2_LIBRARIES ${LIBXML2_LIBRARY})
+
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibXml2
- REQUIRED_VARS LIBXML2_LIBRARIES LIBXML2_INCLUDE_DIR
+ REQUIRED_VARS LIBXML2_LIBRARY LIBXML2_INCLUDE_DIR
VERSION_VAR LIBXML2_VERSION_STRING)
-mark_as_advanced(LIBXML2_INCLUDE_DIR LIBXML2_LIBRARIES LIBXML2_XMLLINT_EXECUTABLE)
+mark_as_advanced(LIBXML2_INCLUDE_DIR LIBXML2_LIBRARY LIBXML2_XMLLINT_EXECUTABLE)
diff --git a/Modules/FindMFC.cmake b/Modules/FindMFC.cmake
index 5c2dbbf6c..3baaf3208 100644
--- a/Modules/FindMFC.cmake
+++ b/Modules/FindMFC.cmake
@@ -31,6 +31,7 @@ if(MFC_ATTEMPT_TRY_COMPILE)
configure_file(${CMAKE_ROOT}/Modules/CheckIncludeFile.cxx.in
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckIncludeFile.cxx)
message(STATUS "Looking for MFC")
+ # Try both shared and static as the root project may have set the /MT flag
try_compile(MFC_HAVE_MFC
${CMAKE_BINARY_DIR}
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckIncludeFile.cxx
@@ -38,6 +39,16 @@ if(MFC_ATTEMPT_TRY_COMPILE)
-DCMAKE_MFC_FLAG:STRING=2
-DCOMPILE_DEFINITIONS:STRING=-D_AFXDLL
OUTPUT_VARIABLE OUTPUT)
+ if(NOT MFC_HAVE_MFC)
+ configure_file(${CMAKE_ROOT}/Modules/CheckIncludeFile.cxx.in
+ ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckIncludeFile.cxx)
+ try_compile(MFC_HAVE_MFC
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckIncludeFile.cxx
+ CMAKE_FLAGS
+ -DCMAKE_MFC_FLAG:STRING=1
+ OUTPUT_VARIABLE OUTPUT)
+ endif()
if(MFC_HAVE_MFC)
message(STATUS "Looking for MFC - found")
set(MFC_HAVE_MFC 1 CACHE INTERNAL "Have MFC?")
diff --git a/Modules/FindMPI.cmake b/Modules/FindMPI.cmake
index 37f325572..7f4c44c5e 100644
--- a/Modules/FindMPI.cmake
+++ b/Modules/FindMPI.cmake
@@ -5,27 +5,45 @@
# FindMPI
# -------
#
-# Find a Message Passing Interface (MPI) implementation
+# Find a Message Passing Interface (MPI) implementation.
#
# The Message Passing Interface (MPI) is a library used to write
# high-performance distributed-memory parallel applications, and is
# typically deployed on a cluster. MPI is a standard interface (defined
# by the MPI forum) for which many implementations are available.
#
-# Variables
-# ^^^^^^^^^
+# Variables for using MPI
+# ^^^^^^^^^^^^^^^^^^^^^^^
+#
+# The module exposes the components ``C``, ``CXX``, ``MPICXX`` and ``Fortran``.
+# Each of these controls the various MPI languages to search for.
+# The difference between ``CXX`` and ``MPICXX`` is that ``CXX`` refers to the
+# MPI C API being usable from C++, whereas ``MPICXX`` refers to the MPI-2 C++ API
+# that was removed again in MPI-3.
+#
+# Depending on the enabled components the following variables will be set:
+#
+# ``MPI_FOUND``
+# Variable indicating that MPI settings for all requested languages have been found.
+# If no components are specified, this is true if MPI settings for all enabled languages
+# were detected. Note that the ``MPICXX`` component does not affect this variable.
+# ``MPI_VERSION``
+# Minimal version of MPI detected among the requested languages, or all enabled languages
+# if no components were specified.
#
# This module will set the following variables per language in your
# project, where ``<lang>`` is one of C, CXX, or Fortran:
#
# ``MPI_<lang>_FOUND``
-# Variable indicating the MPI settings for ``<lang>`` were found.
+# Variable indicating the MPI settings for ``<lang>`` were found and that
+# simple MPI test programs compile with the provided settings.
# ``MPI_<lang>_COMPILER``
-# MPI Compiler wrapper for ``<lang>``.
-# ``MPI_<lang>_COMPILE_FLAGS``
-# Compilation flags for MPI programs, separated by spaces.
-# This is *not* a :ref:`;-list <CMake Language Lists>`.
-# ``MPI_<lang>_INCLUDE_PATH``
+# MPI compiler for ``<lang>`` if such a program exists.
+# ``MPI_<lang>_COMPILE_OPTIONS``
+# Compilation options for MPI programs in ``<lang>``, given as a :ref:`;-list <CMake Language Lists>`.
+# ``MPI_<lang>_COMPILE_DEFINITIONS``
+# Compilation definitions for MPI programs in ``<lang>``, given as a :ref:`;-list <CMake Language Lists>`.
+# ``MPI_<lang>_INCLUDE_DIRS``
# Include path(s) for MPI header.
# ``MPI_<lang>_LINK_FLAGS``
# Linker flags for MPI programs.
@@ -37,53 +55,172 @@
# ``MPI::MPI_<lang>``
# Target for using MPI from ``<lang>``.
#
-# Additionally, FindMPI sets the following variables for running MPI
-# programs from the command line:
+# The following variables indicating which bindings are present will be defined:
#
-# ``MPIEXEC``
-# Executable for running MPI programs, if provided.
+# ``MPI_MPICXX_FOUND``
+# Variable indicating whether the MPI-2 C++ bindings are present (introduced in MPI-2, removed with MPI-3).
+# ``MPI_Fortran_HAVE_F77_HEADER``
+# True if the Fortran 77 header ``mpif.h`` is available.
+# ``MPI_Fortran_HAVE_F90_MODULE``
+# True if the Fortran 90 module ``mpi`` can be used for accessing MPI (MPI-2 and higher only).
+# ``MPI_Fortran_HAVE_F08_MODULE``
+# True if the Fortran 2008 ``mpi_f08`` is available to MPI programs (MPI-3 and higher only).
+#
+# If possible, the MPI version will be determined by this module. The facilities to detect the MPI version
+# were introduced with MPI-1.2, and therefore cannot be found for older MPI versions.
+#
+# ``MPI_<lang>_VERSION_MAJOR``
+# Major version of MPI implemented for ``<lang>`` by the MPI distribution.
+# ``MPI_<lang>_VERSION_MINOR``
+# Minor version of MPI implemented for ``<lang>`` by the MPI distribution.
+# ``MPI_<lang>_VERSION``
+# MPI version implemented for ``<lang>`` by the MPI distribution.
+#
+# Note that there's no variable for the C bindings being accessible through ``mpi.h``, since the MPI standards
+# always have required this binding to work in both C and C++ code.
+#
+# For running MPI programs, the module sets the following variables
+#
+# ``MPIEXEC_EXECUTABLE``
+# Executable for running MPI programs, if such exists.
# ``MPIEXEC_NUMPROC_FLAG``
-# Flag to pass to ``MPIEXEC`` before giving it the number of processors to run on.
+# Flag to pass to ``mpiexec`` before giving it the number of processors to run on.
# ``MPIEXEC_MAX_NUMPROCS``
# Number of MPI processors to utilize. Defaults to the number
# of processors detected on the host system.
# ``MPIEXEC_PREFLAGS``
-# Flags to pass to ``MPIEXEC`` directly before the executable to run.
+# Flags to pass to ``mpiexec`` directly before the executable to run.
# ``MPIEXEC_POSTFLAGS``
-# Flags to pass to ``MPIEXEC`` after other flags.
+# Flags to pass to ``mpiexec`` after other flags.
+#
+# Variables for locating MPI
+# ^^^^^^^^^^^^^^^^^^^^^^^^^^
+#
+# This module performs a three step search for an MPI implementation:
+#
+# 1. Check if the compiler has MPI support built-in. This is the case if the user passed a
+# compiler wrapper as ``CMAKE_<LANG>_COMPILER`` or if they're on a Cray system.
+# 2. Attempt to find an MPI compiler wrapper and determine the compiler information from it.
+# 3. Try to find an MPI implementation that does not ship such a wrapper by guessing settings.
+# Currently, only Microsoft MPI and MPICH2 on Windows are supported.
+#
+# For controlling the second step, the following variables may be set:
+#
+# ``MPI_<lang>_COMPILER``
+# Search for the specified compiler wrapper and use it.
+# ``MPI_<lang>_COMPILER_FLAGS``
+# Flags to pass to the MPI compiler wrapper during interrogation. Some compiler wrappers
+# support linking debug or tracing libraries if a specific flag is passed and this variable
+# may be used to obtain them.
+# ``MPI_COMPILER_FLAGS``
+# Used to initialize ``MPI_<lang>_COMPILER_FLAGS`` if no language specific flag has been given.
+# Empty by default.
+# ``MPI_EXECUTABLE_SUFFIX``
+# A suffix which is appended to all names that are being looked for. For instance you may set this
+# to ``.mpich`` or ``.openmpi`` to prefer the one or the other on Debian and its derivatives.
#
-# Usage
-# ^^^^^
+# In order to control the guessing step, the following variable may be set:
#
-# To use this module, call ``find_package(MPI)``. If you are happy with the
-# auto-detected configuration for your language, then you're done. If
-# not, you have two options:
+# ``MPI_GUESS_LIBRARY_NAME``
+# Valid values are ``MSMPI`` and ``MPICH2``. If set, only the given library will be searched for.
+# By default, ``MSMPI`` will be preferred over ``MPICH2`` if both are available.
+# This also sets ``MPI_SKIP_COMPILER_WRAPPER`` to ``true``, which may be overridden.
#
-# 1. Set ``MPI_<lang>_COMPILER`` to the MPI wrapper (e.g. ``mpicc``) of your
-# choice and reconfigure. FindMPI will attempt to determine all the
-# necessary variables using *that* compiler's compile and link flags.
-# 2. If this fails, or if your MPI implementation does not come with
-# a compiler wrapper, then set both ``MPI_<lang>_LIBRARIES`` and
-# ``MPI_<lang>_INCLUDE_PATH``. You may also set any other variables
-# listed above, but these two are required. This will circumvent
-# autodetection entirely.
+# Each of the search steps may be skipped with the following control variables:
#
-# When configuration is successful, ``MPI_<lang>_COMPILER`` will be set to
-# the compiler wrapper for ``<lang>``, if it was found. ``MPI_<lang>_FOUND``
-# and other variables above will be set if any MPI implementation was
-# found for ``<lang>``, regardless of whether a compiler was found.
+# ``MPI_ASSUME_NO_BUILTIN_MPI``
+# If true, the module assumes that the compiler itself does not provide an MPI implementation and
+# skips to step 2.
+# ``MPI_SKIP_COMPILER_WRAPPER``
+# If true, no compiler wrapper will be searched for.
+# ``MPI_SKIP_GUESSING``
+# If true, the guessing step will be skipped.
#
-# When using ``MPIEXEC`` to execute MPI applications, you should typically
-# use all of the ``MPIEXEC`` flags as follows:
+# Additionally, the following control variable is available to change search behavior:
+#
+# ``MPI_CXX_SKIP_MPICXX``
+# Add some definitions that will disable the MPI-2 C++ bindings.
+# Currently supported are MPICH, Open MPI, Platform MPI and derivatives thereof,
+# for example MVAPICH or Intel MPI.
+#
+# If the find procedure fails for a variable ``MPI_<lang>_WORKS``, then the settings detected by or passed to
+# the module did not work and even a simple MPI test program failed to compile.
+#
+# If all of these parameters were not sufficient to find the right MPI implementation, a user may
+# disable the entire autodetection process by specifying both a list of libraries in ``MPI_<lang>_LIBRARIES``
+# and a list of include directories in ``MPI_<lang>_ADDITIONAL_INCLUDE_DIRS``.
+# Any other variable may be set in addition to these two. The module will then validate the MPI settings and store the
+# settings in the cache.
+#
+# Cache variables for MPI
+# ^^^^^^^^^^^^^^^^^^^^^^^
+#
+# The variable ``MPI_<lang>_INCLUDE_DIRS`` will be assembled from the following variables.
+# For C and CXX:
+#
+# ``MPI_<lang>_HEADER_DIR``
+# Location of the ``mpi.h`` header on disk.
+#
+# For Fortran:
+#
+# ``MPI_Fortran_F77_HEADER_DIR``
+# Location of the Fortran 77 header ``mpif.h``, if it exists.
+# ``MPI_Fortran_MODULE_DIR``
+# Location of the ``mpi`` or ``mpi_f08`` modules, if available.
+#
+# For all languages the following variables are additionally considered:
+#
+# ``MPI_<lang>_ADDITIONAL_INCLUDE_DIRS``
+# A :ref:`;-list <CMake Language Lists>` of paths needed in addition to the normal include directories.
+# ``MPI_<include_name>_INCLUDE_DIR``
+# Path variables for include folders referred to by ``<include_name>``.
+# ``MPI_<lang>_ADDITIONAL_INCLUDE_VARS``
+# A :ref:`;-list <CMake Language Lists>` of ``<include_name>`` that will be added to the include locations of ``<lang>``.
+#
+# The variable ``MPI_<lang>_LIBRARIES`` will be assembled from the following variables:
+#
+# ``MPI_<lib_name>_LIBRARY``
+# The location of a library called ``<lib_name>`` for use with MPI.
+# ``MPI_<lang>_LIB_NAMES``
+# A :ref:`;-list <CMake Language Lists>` of ``<lib_name>`` that will be added to the include locations of ``<lang>``.
+#
+# Usage of mpiexec
+# ^^^^^^^^^^^^^^^^
+#
+# When using ``MPIEXEC_EXECUTABLE`` to execute MPI applications, you should typically
+# use all of the ``MPIEXEC_EXECUTABLE`` flags as follows:
#
# ::
#
-# ${MPIEXEC} ${MPIEXEC_NUMPROC_FLAG} ${MPIEXEC_MAX_NUMPROCS}
+# ${MPIEXEC_EXECUTABLE} ${MPIEXEC_NUMPROC_FLAG} ${MPIEXEC_MAX_NUMPROCS}
# ${MPIEXEC_PREFLAGS} EXECUTABLE ${MPIEXEC_POSTFLAGS} ARGS
#
# where ``EXECUTABLE`` is the MPI program, and ``ARGS`` are the arguments to
# pass to the MPI program.
#
+# Advanced variables for using MPI
+# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+#
+# The module can perform some advanced feature detections upon explicit request.
+#
+# **Important notice:** The following checks cannot be performed without *executing* an MPI test program.
+# Consider the special considerations for the behavior of :command:`try_run` during cross compilation.
+# Moreover, running an MPI program can cause additional issues, like a firewall notification on some systems.
+# You should only enable these detections if you absolutely need the information.
+#
+# If the following variables are set to true, the respective search will be performed:
+#
+# ``MPI_DETERMINE_Fortran_CAPABILITIES``
+# Determine for all available Fortran bindings what the values of ``MPI_SUBARRAYS_SUPPORTED`` and
+# ``MPI_ASYNC_PROTECTS_NONBLOCKING`` are and make their values available as ``MPI_Fortran_<binding>_SUBARRAYS``
+# and ``MPI_Fortran_<binding>_ASYNCPROT``, where ``<binding>`` is one of ``F77_HEADER``, ``F90_MODULE`` and
+# ``F08_MODULE``.
+# ``MPI_DETERMINE_LIBRARY_VERSION``
+# For each language, find the output of ``MPI_Get_library_version`` and make it available as ``MPI_<lang>_LIBRARY_VERSION``.
+# This information is usually tied to the runtime component of an MPI implementation and might differ depending on ``<lang>``.
+# Note that the return value is entirely implementation defined. This information might be used to identify
+# the MPI vendor and for example pick the correct one of multiple third party binaries that matches the MPI vendor.
+#
# Backward Compatibility
# ^^^^^^^^^^^^^^^^^^^^^^
#
@@ -92,52 +229,60 @@
#
# ::
#
-# MPI_FOUND MPI_COMPILER MPI_LIBRARY
-# MPI_COMPILE_FLAGS MPI_INCLUDE_PATH MPI_EXTRA_LIBRARY
-# MPI_LINK_FLAGS MPI_LIBRARIES
+# MPI_COMPILER MPI_LIBRARY MPI_EXTRA_LIBRARY
+# MPI_COMPILE_FLAGS MPI_INCLUDE_PATH MPI_LINK_FLAGS
+# MPI_LIBRARIES
#
# In new projects, please use the ``MPI_<lang>_XXX`` equivalents.
+# Additionally, the following variables are deprecated:
+#
+# ``MPI_<lang>_COMPILE_FLAGS``
+# Use ``MPI_<lang>_COMPILE_OPTIONS`` and ``MPI_<lang>_COMPILE_DEFINITIONS`` instead.
+# ``MPI_<lang>_INCLUDE_PATH``
+# For consumption use ``MPI_<lang>_INCLUDE_DIRS`` and for specifying folders use ``MPI_<lang>_ADDITIONAL_INCLUDE_DIRS`` instead.
+# ``MPIEXEC``
+# Use ``MPIEXEC_EXECUTABLE`` instead.
-include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
+cmake_policy(PUSH)
+cmake_policy(SET CMP0057 NEW) # if IN_LIST
-#
-# This part detects MPI compilers, attempting to wade through the mess of compiler names in
-# a sensible way.
-#
-# The compilers are detected in this order:
-#
-# 1. Try to find the most generic available MPI compiler, as this is usually set up by
-# cluster admins, e.g. if plain old mpicc is available, we'll use it and assume it's
-# the right compiler.
-#
-# 2. If a generic mpicc is NOT found, then we attempt to find one that matches
-# CMAKE_<lang>_COMPILER_ID. e.g. if you are using XL compilers, we'll try to find mpixlc
-# and company, but not mpiicc. This hopefully prevents toolchain mismatches.
-#
-# If you want to force a particular MPI compiler other than what we autodetect (e.g. if you
-# want to compile regular stuff with GNU and parallel stuff with Intel), you can always set
-# your favorite MPI_<lang>_COMPILER explicitly and this stuff will be ignored.
-#
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
-# Start out with the generic MPI compiler names, as these are most commonly used.
-set(_MPI_C_COMPILER_NAMES mpicc mpcc mpicc_r mpcc_r mpicc.bat)
-set(_MPI_CXX_COMPILER_NAMES mpicxx mpiCC mpcxx mpCC mpic++ mpc++
- mpicxx_r mpiCC_r mpcxx_r mpCC_r mpic++_r mpc++_r
- mpicxx.bat)
-set(_MPI_Fortran_COMPILER_NAMES mpif95 mpif95_r mpf95 mpf95_r
+# Generic compiler names
+set(_MPI_C_GENERIC_COMPILER_NAMES mpicc mpcc mpicc_r mpcc_r)
+set(_MPI_CXX_GENERIC_COMPILER_NAMES mpicxx mpiCC mpcxx mpCC mpic++ mpc++
+ mpicxx_r mpiCC_r mpcxx_r mpCC_r mpic++_r mpc++_r)
+set(_MPI_Fortran_GENERIC_COMPILER_NAMES mpif95 mpif95_r mpf95 mpf95_r
mpif90 mpif90_r mpf90 mpf90_r
- mpif77 mpif77_r mpf77 mpf77_r)
+ mpif77 mpif77_r mpf77 mpf77_r
+ mpifc)
# GNU compiler names
set(_MPI_GNU_C_COMPILER_NAMES mpigcc mpgcc mpigcc_r mpgcc_r)
-set(_MPI_GNU_CXX_COMPILER_NAMES mpig++ mpg++ mpig++_r mpg++_r)
+set(_MPI_GNU_CXX_COMPILER_NAMES mpig++ mpg++ mpig++_r mpg++_r mpigxx)
set(_MPI_GNU_Fortran_COMPILER_NAMES mpigfortran mpgfortran mpigfortran_r mpgfortran_r
mpig77 mpig77_r mpg77 mpg77_r)
-# Intel MPI compiler names
-set(_MPI_Intel_C_COMPILER_NAMES mpiicc mpiicc.bat)
-set(_MPI_Intel_CXX_COMPILER_NAMES mpiicpc mpiicxx mpiic++ mpiiCC mpiicpc.bat)
-set(_MPI_Intel_Fortran_COMPILER_NAMES mpiifort mpiif95 mpiif90 mpiif77 mpiifort.bat)
+# Intel MPI compiler names on Windows
+if(WIN32)
+ list(APPEND _MPI_C_GENERIC_COMPILER_NAMES mpicc.bat)
+ list(APPEND _MPI_CXX_GENERIC_COMPILER_NAMES mpicxx.bat)
+ list(APPEND _MPI_Fortran_GENERIC_COMPILER_NAMES mpifc.bat)
+
+ # Intel MPI compiler names
+ set(_MPI_Intel_C_COMPILER_NAMES mpiicc.bat)
+ set(_MPI_Intel_CXX_COMPILER_NAMES mpiicpc.bat)
+ set(_MPI_Intel_Fortran_COMPILER_NAMES mpiifort.bat mpif77.bat mpif90.bat)
+
+ # Intel MPI compiler names for MSMPI
+ set(_MPI_MSVC_C_COMPILER_NAMES mpicl.bat)
+ set(_MPI_MSVC_CXX_COMPILER_NAMES mpicl.bat)
+else()
+ # Intel compiler names
+ set(_MPI_Intel_C_COMPILER_NAMES mpiicc)
+ set(_MPI_Intel_CXX_COMPILER_NAMES mpiicpc mpiicxx mpiic++)
+ set(_MPI_Intel_Fortran_COMPILER_NAMES mpiifort mpiif95 mpiif90 mpiif77)
+endif()
# PGI compiler names
set(_MPI_PGI_C_COMPILER_NAMES mpipgcc mppgcc)
@@ -153,524 +298,1127 @@ set(_MPI_XL_Fortran_COMPILER_NAMES mpixlf95 mpixlf95_r mpxlf95 mpxlf95
mpixlf77 mpixlf77_r mpxlf77 mpxlf77_r
mpixlf mpixlf_r mpxlf mpxlf_r)
-# append vendor-specific compilers to the list if we either don't know the compiler id,
-# or if we know it matches the regular compiler.
-foreach (lang C CXX Fortran)
- foreach (id GNU Intel PGI XL)
- if (NOT CMAKE_${lang}_COMPILER_ID OR CMAKE_${lang}_COMPILER_ID STREQUAL id)
- list(APPEND _MPI_${lang}_COMPILER_NAMES ${_MPI_${id}_${lang}_COMPILER_NAMES})
+# Prepend vendor-specific compiler wrappers to the list. If we don't know the compiler,
+# attempt all of them.
+# By attempting vendor-specific compiler names first, we should avoid situations where the compiler wrapper
+# stems from a proprietary MPI and won't know which compiler it's being used for. For instance, Intel MPI
+# controls its settings via the I_MPI_CC environment variables if the generic name is being used.
+# If we know which compiler we're working with, we can use the most specialized wrapper there is in order to
+# pick up the right settings for it.
+foreach (LANG IN ITEMS C CXX Fortran)
+ set(_MPI_${LANG}_COMPILER_NAMES "")
+ foreach (id IN ITEMS GNU Intel MSVC PGI XL)
+ if (NOT CMAKE_${LANG}_COMPILER_ID OR CMAKE_${LANG}_COMPILER_ID STREQUAL id)
+ list(APPEND _MPI_${LANG}_COMPILER_NAMES ${_MPI_${id}_${LANG}_COMPILER_NAMES}${MPI_EXECUTABLE_SUFFIX})
endif()
- unset(_MPI_${id}_${lang}_COMPILER_NAMES) # clean up the namespace here
+ unset(_MPI_${id}_${LANG}_COMPILER_NAMES)
endforeach()
+ list(APPEND _MPI_${LANG}_COMPILER_NAMES ${_MPI_${LANG}_GENERIC_COMPILER_NAMES}${MPI_EXECUTABLE_SUFFIX})
+ unset(_MPI_${LANG}_GENERIC_COMPILER_NAMES)
endforeach()
+# Names to try for mpiexec
+# Only mpiexec commands are guaranteed to behave as described in the standard,
+# mpirun commands are not covered by the standard in any way whatsoever.
+# lamexec is the executable for LAM/MPI, srun is for SLURM or Open MPI with SLURM support.
+# srun -n X <executable> is however a valid command, so it behaves 'like' mpiexec.
+set(_MPIEXEC_NAMES_BASE mpiexec mpiexec.hydra mpiexec.mpd mpirun lamexec srun)
-# Names to try for MPI exec
-set(_MPI_EXEC_NAMES mpiexec mpirun lamexec srun)
-
-# Grab the path to MPI from the registry if we're on windows.
-set(_MPI_PREFIX_PATH)
-if(WIN32)
- # MSMPI
- file(TO_CMAKE_PATH "$ENV{MSMPI_BIN}" msmpi_bin_path) # The default path ends with a '\' and doesn't mix with ';' when appending.
- list(APPEND _MPI_PREFIX_PATH "${msmpi_bin_path}")
- unset(msmpi_bin_path)
- list(APPEND _MPI_PREFIX_PATH "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MPI;InstallRoot]/Bin")
- list(APPEND _MPI_PREFIX_PATH "$ENV{MSMPI_INC}/..") # The SDK is installed separately from the runtime
- # MPICH
- list(APPEND _MPI_PREFIX_PATH "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MPICH\\SMPD;binary]/..")
- list(APPEND _MPI_PREFIX_PATH "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MPICH2;Path]")
- list(APPEND _MPI_PREFIX_PATH "$ENV{ProgramW6432}/MPICH2/")
-endif()
-
-# Build a list of prefixes to search for MPI.
-foreach(SystemPrefixDir ${CMAKE_SYSTEM_PREFIX_PATH})
- foreach(MpiPackageDir ${_MPI_PREFIX_PATH})
- if(EXISTS ${SystemPrefixDir}/${MpiPackageDir})
- list(APPEND _MPI_PREFIX_PATH "${SystemPrefixDir}/${MpiPackageDir}")
- endif()
- endforeach()
+unset(_MPIEXEC_NAMES)
+foreach(_MPIEXEC_NAME IN LISTS _MPIEXEC_NAMES_BASE)
+ list(APPEND _MPIEXEC_NAMES "${_MPIEXEC_NAME}${MPI_EXECUTABLE_SUFFIX}")
endforeach()
+unset(_MPIEXEC_NAMES_BASE)
-function (_mpi_check_compiler compiler options cmdvar resvar)
+function (_MPI_check_compiler LANG QUERY_FLAG OUTPUT_VARIABLE RESULT_VARIABLE)
+ if(DEFINED MPI_${LANG}_COMPILER_FLAGS)
+ separate_arguments(_MPI_COMPILER_WRAPPER_OPTIONS NATIVE_COMMAND "${MPI_${LANG}_COMPILER_FLAGS}")
+ else()
+ separate_arguments(_MPI_COMPILER_WRAPPER_OPTIONS NATIVE_COMMAND "${MPI_COMPILER_FLAGS}")
+ endif()
execute_process(
- COMMAND "${compiler}" ${options}
- OUTPUT_VARIABLE cmdline OUTPUT_STRIP_TRAILING_WHITESPACE
- ERROR_VARIABLE cmdline ERROR_STRIP_TRAILING_WHITESPACE
- RESULT_VARIABLE success)
- # Intel MPI 5.0.1 will return a zero return code even when the
- # argument to the MPI compiler wrapper is unknown. Attempt to
- # catch this case.
- if(cmdline MATCHES "undefined reference" OR cmdline MATCHES "unrecognized")
- set(success 255 )
- endif()
- set(${cmdvar} "${cmdline}" PARENT_SCOPE)
- set(${resvar} "${success}" PARENT_SCOPE)
+ COMMAND ${MPI_${LANG}_COMPILER} ${_MPI_COMPILER_WRAPPER_OPTIONS} ${QUERY_FLAG}
+ OUTPUT_VARIABLE WRAPPER_OUTPUT OUTPUT_STRIP_TRAILING_WHITESPACE
+ ERROR_VARIABLE WRAPPER_OUTPUT ERROR_STRIP_TRAILING_WHITESPACE
+ RESULT_VARIABLE WRAPPER_RETURN)
+ # Some compiler wrappers will yield spurious zero return values, for example
+ # Intel MPI tolerates unknown arguments and if the MPI wrappers loads a shared
+ # library that has invalid or missing version information there would be warning
+ # messages emitted by ld.so in the compiler output. In either case, we'll treat
+ # the output as invalid.
+ if("${WRAPPER_OUTPUT}" MATCHES "undefined reference|unrecognized|need to set|no version information available")
+ set(WRAPPER_RETURN 255)
+ endif()
+ # Ensure that no error output might be passed upwards.
+ if(NOT WRAPPER_RETURN EQUAL 0)
+ unset(WRAPPER_OUTPUT)
+ endif()
+ set(${OUTPUT_VARIABLE} "${WRAPPER_OUTPUT}" PARENT_SCOPE)
+ set(${RESULT_VARIABLE} "${WRAPPER_RETURN}" PARENT_SCOPE)
endfunction()
-#
-# interrogate_mpi_compiler(lang try_libs)
-#
-# Attempts to extract compiler and linker args from an MPI compiler. The arguments set
-# by this function are:
-#
-# MPI_<lang>_INCLUDE_PATH MPI_<lang>_LINK_FLAGS MPI_<lang>_FOUND
-# MPI_<lang>_COMPILE_FLAGS MPI_<lang>_LIBRARIES
-#
-# MPI_<lang>_COMPILER must be set beforehand to the absolute path to an MPI compiler for
-# <lang>. Additionally, MPI_<lang>_INCLUDE_PATH and MPI_<lang>_LIBRARIES may be set
-# to skip autodetection.
-#
-# If try_libs is TRUE, this will also attempt to find plain MPI libraries in the usual
-# way. In general, this is not as effective as interrogating the compilers, as it
-# ignores language-specific flags and libraries. However, some MPI implementations
-# (Windows implementations) do not have compiler wrappers, so this approach must be used.
-#
-function (interrogate_mpi_compiler lang try_libs)
- # MPI_${lang}_NO_INTERROGATE will be set to a compiler name when the *regular* compiler was
- # discovered to be the MPI compiler. This happens on machines like the Cray XE6 that use
- # modules to set cc, CC, and ftn to the MPI compilers. If the user force-sets another MPI
- # compiler, MPI_${lang}_COMPILER won't be equal to MPI_${lang}_NO_INTERROGATE, and we'll
- # inspect that compiler anew. This allows users to set new compilers w/o rm'ing cache.
- string(COMPARE NOTEQUAL "${MPI_${lang}_NO_INTERROGATE}" "${MPI_${lang}_COMPILER}" interrogate)
-
- # If MPI is set already in the cache, don't bother with interrogating the compiler.
- if (interrogate AND ((NOT MPI_${lang}_INCLUDE_PATH) OR (NOT MPI_${lang}_LIBRARIES)))
- if (MPI_${lang}_COMPILER)
- # Check whether the -showme:compile option works. This indicates that we have either OpenMPI
- # or a newer version of LAM-MPI, and implies that -showme:link will also work.
- _mpi_check_compiler("${MPI_${lang}_COMPILER}" "-showme:compile" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN)
- if (MPI_COMPILER_RETURN EQUAL 0)
- # If we appear to have -showme:compile, then we should
- # also have -showme:link. Try it.
- execute_process(
- COMMAND ${MPI_${lang}_COMPILER} -showme:link
- OUTPUT_VARIABLE MPI_LINK_CMDLINE OUTPUT_STRIP_TRAILING_WHITESPACE
- ERROR_VARIABLE MPI_LINK_CMDLINE ERROR_STRIP_TRAILING_WHITESPACE
- RESULT_VARIABLE MPI_COMPILER_RETURN)
-
- if (MPI_COMPILER_RETURN EQUAL 0)
- # We probably have -showme:incdirs and -showme:libdirs as well,
- # so grab that while we're at it.
- execute_process(
- COMMAND ${MPI_${lang}_COMPILER} -showme:incdirs
- OUTPUT_VARIABLE MPI_INCDIRS OUTPUT_STRIP_TRAILING_WHITESPACE
- ERROR_VARIABLE MPI_INCDIRS ERROR_STRIP_TRAILING_WHITESPACE)
-
- execute_process(
- COMMAND ${MPI_${lang}_COMPILER} -showme:libdirs
- OUTPUT_VARIABLE MPI_LIBDIRS OUTPUT_STRIP_TRAILING_WHITESPACE
- ERROR_VARIABLE MPI_LIBDIRS ERROR_STRIP_TRAILING_WHITESPACE)
+function (_MPI_interrogate_compiler lang)
+ unset(MPI_COMPILE_CMDLINE)
+ unset(MPI_LINK_CMDLINE)
+
+ unset(MPI_COMPILE_OPTIONS_WORK)
+ unset(MPI_COMPILE_DEFINITIONS_WORK)
+ unset(MPI_INCLUDE_DIRS_WORK)
+ unset(MPI_LINK_FLAGS_WORK)
+ unset(MPI_LIB_NAMES_WORK)
+ unset(MPI_LIB_FULLPATHS_WORK)
+
+ # Check whether the -showme:compile option works. This indicates that we have either Open MPI
+ # or a newer version of LAM/MPI, and implies that -showme:link will also work.
+ # Open MPI also supports -show, but separates linker and compiler information
+ _MPI_check_compiler(${LANG} "-showme:compile" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN)
+ if (MPI_COMPILER_RETURN EQUAL 0)
+ _MPI_check_compiler(${LANG} "-showme:link" MPI_LINK_CMDLINE MPI_COMPILER_RETURN)
+
+ if (NOT MPI_COMPILER_RETURN EQUAL 0)
+ unset(MPI_COMPILE_CMDLINE)
+ endif()
+ endif()
- else()
- # reset things here if something went wrong.
- set(MPI_COMPILE_CMDLINE)
- set(MPI_LINK_CMDLINE)
- endif()
- endif ()
+ # MPICH and MVAPICH offer -compile-info and -link-info.
+ # For modern versions, both do the same as -show. However, for old versions, they do differ
+ # when called for mpicxx and mpif90 and it's necessary to use them over -show in order to find the
+ # removed MPI C++ bindings.
+ if (NOT MPI_COMPILER_RETURN EQUAL 0)
+ _MPI_check_compiler(${LANG} "-compile-info" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN)
+
+ if (MPI_COMPILER_RETURN EQUAL 0)
+ _MPI_check_compiler(${LANG} "-link-info" MPI_LINK_CMDLINE MPI_COMPILER_RETURN)
- # Older versions of LAM-MPI have "-showme". Try to find that.
if (NOT MPI_COMPILER_RETURN EQUAL 0)
- _mpi_check_compiler("${MPI_${lang}_COMPILER}" "-showme" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN)
+ unset(MPI_COMPILE_CMDLINE)
endif()
+ endif()
+ endif()
- # MVAPICH uses -compile-info and -link-info. Try them.
- if (NOT MPI_COMPILER_RETURN EQUAL 0)
- _mpi_check_compiler("${MPI_${lang}_COMPILER}" "-compile-info" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN)
-
- # If we have compile-info, also have link-info.
- if (MPI_COMPILER_RETURN EQUAL 0)
- execute_process(
- COMMAND ${MPI_${lang}_COMPILER} -link-info
- OUTPUT_VARIABLE MPI_LINK_CMDLINE OUTPUT_STRIP_TRAILING_WHITESPACE
- ERROR_VARIABLE MPI_LINK_CMDLINE ERROR_STRIP_TRAILING_WHITESPACE
- RESULT_VARIABLE MPI_COMPILER_RETURN)
- endif()
+ # MPICH, MVAPICH2 and Intel MPI just use "-show". Open MPI also offers this, but the
+ # -showme commands are more specialized.
+ if (NOT MPI_COMPILER_RETURN EQUAL 0)
+ _MPI_check_compiler(${LANG} "-show" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN)
+ endif()
- # make sure we got compile and link. Reset vars if something's wrong.
- if (NOT MPI_COMPILER_RETURN EQUAL 0)
- set(MPI_COMPILE_CMDLINE)
- set(MPI_LINK_CMDLINE)
- endif()
- endif()
+ # Older versions of LAM/MPI have "-showme". Open MPI also supports this.
+ # Unknown to MPICH, MVAPICH and Intel MPI.
+ if (NOT MPI_COMPILER_RETURN EQUAL 0)
+ _MPI_check_compiler(${LANG} "-showme" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN)
+ endif()
- # MPICH just uses "-show". Try it.
- if (NOT MPI_COMPILER_RETURN EQUAL 0)
- _mpi_check_compiler("${MPI_${lang}_COMPILER}" "-show" MPI_COMPILE_CMDLINE MPI_COMPILER_RETURN)
- endif()
+ if (NOT (MPI_COMPILER_RETURN EQUAL 0) OR NOT (DEFINED MPI_COMPILE_CMDLINE))
+ # Cannot interrogate this compiler, so exit.
+ set(MPI_${LANG}_WRAPPER_FOUND FALSE PARENT_SCOPE)
+ return()
+ endif()
+ unset(MPI_COMPILER_RETURN)
- if (MPI_COMPILER_RETURN EQUAL 0)
- # We have our command lines, but we might need to copy MPI_COMPILE_CMDLINE
- # into MPI_LINK_CMDLINE, if we didn't find the link line.
- if (NOT MPI_LINK_CMDLINE)
- set(MPI_LINK_CMDLINE ${MPI_COMPILE_CMDLINE})
- endif()
+ # We have our command lines, but we might need to copy MPI_COMPILE_CMDLINE
+ # into MPI_LINK_CMDLINE, if we didn't find the link line.
+ if (NOT DEFINED MPI_LINK_CMDLINE)
+ set(MPI_LINK_CMDLINE "${MPI_COMPILE_CMDLINE}")
+ endif()
+
+ # At this point, we obtained some output from a compiler wrapper that works.
+ # We'll now try to parse it into variables with meaning to us.
+ if("${LANG}" STREQUAL "Fortran")
+ # Some MPICH-1 and MVAPICH-1 versions return a three command answer for Fortran, consisting
+ # out of a symlink command for mpif.h, the actual compiler command and a deletion of the
+ # created symlink. We need to detect that case, remember the include path and drop the
+ # symlink/deletion operation to obtain the link/compile lines we'd usually expect.
+ if("${MPI_COMPILE_CMDLINE}" MATCHES "^ln -s ([^\" ]+|\"[^\"]+\") mpif.h")
+ get_filename_component(MPI_INCLUDE_DIRS_WORK "${CMAKE_MATCH_1}" DIRECTORY)
+ string(REGEX REPLACE "^ln -s ([^\" ]+|\"[^\"]+\") mpif.h\n" "" MPI_COMPILE_CMDLINE "${MPI_COMPILE_CMDLINE}")
+ string(REGEX REPLACE "^ln -s ([^\" ]+|\"[^\"]+\") mpif.h\n" "" MPI_LINK_CMDLINE "${MPI_LINK_CMDLINE}")
+ string(REGEX REPLACE "\nrm -f mpif.h$" "" MPI_COMPILE_CMDLINE "${MPI_COMPILE_CMDLINE}")
+ string(REGEX REPLACE "\nrm -f mpif.h$" "" MPI_LINK_CMDLINE "${MPI_LINK_CMDLINE}")
+ endif()
+ endif()
+
+ # The Intel MPI wrapper on Linux will emit some objcopy commands after its compile command
+ # if -static_mpi was passed to the wrapper. To avoid spurious matches, we need to drop these lines.
+ if(UNIX)
+ string(REGEX REPLACE "(^|\n)objcopy[^\n]+(\n|$)" "" MPI_COMPILE_CMDLINE "${MPI_COMPILE_CMDLINE}")
+ string(REGEX REPLACE "(^|\n)objcopy[^\n]+(\n|$)" "" MPI_LINK_CMDLINE "${MPI_LINK_CMDLINE}")
+ endif()
+
+ # Extract compile options from the compile command line.
+ string(REGEX MATCHALL "(^| )-f([^\" ]+|\"[^\"]+\")" MPI_ALL_COMPILE_OPTIONS "${MPI_COMPILE_CMDLINE}")
+
+ foreach(_MPI_COMPILE_OPTION IN LISTS MPI_ALL_COMPILE_OPTIONS)
+ string(REGEX REPLACE "^ " "" _MPI_COMPILE_OPTION "${_MPI_COMPILE_OPTION}")
+ # Ignore -fstack-protector directives: These occur on MPICH and MVAPICH when the libraries
+ # themselves were built with this flag. However, this flag is unrelated to using MPI, and
+ # 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(stack-protector|(no-|)strict-aliasing|PI[CE]|pi[ce])")
+ list(APPEND MPI_COMPILE_OPTIONS_WORK "${_MPI_COMPILE_OPTION}")
+ endif()
+ endforeach()
+
+ # Same deal, with the definitions. We also treat arguments passed to the preprocessor directly.
+ string(REGEX MATCHALL "(^| )(-Wp,|-Xpreprocessor |)[-/]D([^\" ]+|\"[^\"]+\")" MPI_ALL_COMPILE_DEFINITIONS "${MPI_COMPILE_CMDLINE}")
+
+ foreach(_MPI_COMPILE_DEFINITION IN LISTS MPI_ALL_COMPILE_DEFINITIONS)
+ string(REGEX REPLACE "^ ?(-Wp,|-Xpreprocessor )?[-/]D" "" _MPI_COMPILE_DEFINITION "${_MPI_COMPILE_DEFINITION}")
+ string(REPLACE "\"" "" _MPI_COMPILE_DEFINITION "${_MPI_COMPILE_DEFINITION}")
+ if(NOT "${_MPI_COMPILE_DEFINITION}" MATCHES "^_FORTIFY_SOURCE.*")
+ list(APPEND MPI_COMPILE_DEFINITIONS_WORK "${_MPI_COMPILE_DEFINITION}")
+ endif()
+ endforeach()
+
+ # Extract include paths from compile command line
+ string(REGEX MATCHALL "(^| )[-/]I([^\" ]+|\"[^\"]+\")" MPI_ALL_INCLUDE_PATHS "${MPI_COMPILE_CMDLINE}")
+
+ # If extracting failed to work, we'll try using -showme:incdirs.
+ if (NOT MPI_ALL_INCLUDE_PATHS)
+ _MPI_check_compiler(${LANG} "-showme:incdirs" MPI_INCDIRS_CMDLINE MPI_INCDIRS_COMPILER_RETURN)
+ if(MPI_INCDIRS_COMPILER_RETURN)
+ separate_arguments(MPI_ALL_INCLUDE_PATHS NATIVE_COMMAND "${MPI_INCDIRS_CMDLINE}")
+ endif()
+ endif()
+
+ foreach(_MPI_INCLUDE_PATH IN LISTS MPI_ALL_INCLUDE_PATHS)
+ string(REGEX REPLACE "^ ?[-/]I" "" _MPI_INCLUDE_PATH "${_MPI_INCLUDE_PATH}")
+ string(REPLACE "\"" "" _MPI_INCLUDE_PATH "${_MPI_INCLUDE_PATH}")
+ get_filename_component(_MPI_INCLUDE_PATH "${_MPI_INCLUDE_PATH}" REALPATH)
+ list(APPEND MPI_INCLUDE_DIRS_WORK "${_MPI_INCLUDE_PATH}")
+ endforeach()
+
+ # Extract linker paths from the link command line
+ string(REGEX MATCHALL "(^| )(-Wl,|-Xlinker |)(-L|[/-]LIBPATH:|[/-]libpath:)([^\" ]+|\"[^\"]+\")" MPI_ALL_LINK_PATHS "${MPI_LINK_CMDLINE}")
+
+ # If extracting failed to work, we'll try using -showme:libdirs.
+ if (NOT MPI_ALL_LINK_PATHS)
+ _MPI_check_compiler(${LANG} "-showme:libdirs" MPI_LIBDIRS_CMDLINE MPI_LIBDIRS_COMPILER_RETURN)
+ if(MPI_LIBDIRS_COMPILER_RETURN)
+ separate_arguments(MPI_ALL_LINK_PATHS NATIVE_COMMAND "${MPI_LIBDIRS_CMDLINE}")
+ endif()
+ endif()
+
+ foreach(_MPI_LPATH IN LISTS MPI_ALL_LINK_PATHS)
+ string(REGEX REPLACE "^ ?(-Wl,|-Xlinker )?(-L|[/-]LIBPATH:|[/-]libpath:)" "" _MPI_LPATH "${_MPI_LPATH}")
+ string(REPLACE "\"" "" _MPI_LPATH "${_MPI_LPATH}")
+ get_filename_component(_MPI_LPATH "${_MPI_LPATH}" REALPATH)
+ list(APPEND MPI_LINK_DIRECTORIES_WORK "${_MPI_LPATH}")
+ endforeach()
+
+ # Extract linker flags from the link command line
+ string(REGEX MATCHALL "(^| )(-Wl,|-Xlinker )([^\" ]+|\"[^\"]+\")" MPI_ALL_LINK_FLAGS "${MPI_LINK_CMDLINE}")
+
+ foreach(_MPI_LINK_FLAG IN LISTS MPI_ALL_LINK_FLAGS)
+ string(STRIP "${_MPI_LINK_FLAG}" _MPI_LINK_FLAG)
+ # MPI might be marked to build with non-executable stacks but this should not propagate.
+ if (NOT "${_MPI_LINK_FLAG}" MATCHES "(-Wl,|-Xlinker )-z,noexecstack")
+ if (MPI_LINK_FLAGS_WORK)
+ string(APPEND MPI_LINK_FLAGS_WORK " ${_MPI_LINK_FLAG}")
else()
- message(STATUS "Unable to determine MPI from MPI driver ${MPI_${lang}_COMPILER}")
- set(MPI_COMPILE_CMDLINE)
- set(MPI_LINK_CMDLINE)
+ set(MPI_LINK_FLAGS_WORK "${_MPI_LINK_FLAG}")
endif()
+ endif()
+ endforeach()
- # Here, we're done with the interrogation part, and we'll try to extract args we care
- # about from what we learned from the compiler wrapper scripts.
-
- # If interrogation came back with something, extract our variable from the MPI command line
- if (MPI_COMPILE_CMDLINE OR MPI_LINK_CMDLINE)
- # Extract compile flags from the compile command line.
- string(REGEX MATCHALL "(^| )-[Df]([^\" ]+|\"[^\"]+\")" MPI_ALL_COMPILE_FLAGS "${MPI_COMPILE_CMDLINE}")
- set(MPI_COMPILE_FLAGS_WORK)
+ # Extract the set of libraries to link against from the link command
+ # line
+ string(REGEX MATCHALL "(^| )-l([^\" ]+|\"[^\"]+\")" MPI_LIBNAMES "${MPI_LINK_CMDLINE}")
- foreach(FLAG ${MPI_ALL_COMPILE_FLAGS})
- string(REGEX REPLACE "^ " "" FLAG ${FLAG})
- if (MPI_COMPILE_FLAGS_WORK)
- string(APPEND MPI_COMPILE_FLAGS_WORK " ${FLAG}")
- else()
- set(MPI_COMPILE_FLAGS_WORK ${FLAG})
- endif()
- endforeach()
+ foreach(_MPI_LIB_NAME IN LISTS MPI_LIBNAMES)
+ string(REGEX REPLACE "^ ?-l" "" _MPI_LIB_NAME "${_MPI_LIB_NAME}")
+ string(REPLACE "\"" "" _MPI_LIB_NAME "${_MPI_LIB_NAME}")
+ get_filename_component(_MPI_LIB_PATH "${_MPI_LIB_NAME}" DIRECTORY)
+ if(NOT "${_MPI_LIB_PATH}" STREQUAL "")
+ list(APPEND MPI_LIB_FULLPATHS_WORK "${_MPI_LIB_NAME}")
+ else()
+ list(APPEND MPI_LIB_NAMES_WORK "${_MPI_LIB_NAME}")
+ endif()
+ endforeach()
- # Extract include paths from compile command line
- string(REGEX MATCHALL "(^| )-I([^\" ]+|\"[^\"]+\")" MPI_ALL_INCLUDE_PATHS "${MPI_COMPILE_CMDLINE}")
- set(MPI_INCLUDE_PATH_WORK)
+ if(WIN32)
+ # A compiler wrapper on Windows will just have the name of the
+ # library to link on its link line, potentially with a full path
+ string(REGEX MATCHALL "(^| )([^\" ]+\\.lib|\"[^\"]+\\.lib\")" MPI_LIBNAMES "${MPI_LINK_CMDLINE}")
+ foreach(_MPI_LIB_NAME IN LISTS MPI_LIBNAMES)
+ string(REGEX REPLACE "^ " "" _MPI_LIB_NAME "${_MPI_LIB_NAME}")
+ string(REPLACE "\"" "" _MPI_LIB_NAME "${_MPI_LIB_NAME}")
+ get_filename_component(_MPI_LIB_PATH "${_MPI_LIB_NAME}" DIRECTORY)
+ if(NOT "${_MPI_LIB_PATH}" STREQUAL "")
+ list(APPEND MPI_LIB_FULLPATHS_WORK "${_MPI_LIB_NAME}")
+ else()
+ list(APPEND MPI_LIB_NAMES_WORK "${_MPI_LIB_NAME}")
+ endif()
+ endforeach()
+ else()
+ # On UNIX platforms, archive libraries can be given with full path.
+ string(REGEX MATCHALL "(^| )([^\" ]+\\.a|\"[^\"]+\\.a\")" MPI_LIBFULLPATHS "${MPI_LINK_CMDLINE}")
+ foreach(_MPI_LIB_NAME IN LISTS MPI_LIBFULLPATHS)
+ string(REGEX REPLACE "^ " "" _MPI_LIB_NAME "${_MPI_LIB_NAME}")
+ string(REPLACE "\"" "" _MPI_LIB_NAME "${_MPI_LIB_NAME}")
+ get_filename_component(_MPI_LIB_PATH "${_MPI_LIB_NAME}" DIRECTORY)
+ if(NOT "${_MPI_LIB_PATH}" STREQUAL "")
+ list(APPEND MPI_LIB_FULLPATHS_WORK "${_MPI_LIB_NAME}")
+ else()
+ list(APPEND MPI_LIB_NAMES_WORK "${_MPI_LIB_NAME}")
+ endif()
+ endforeach()
+ endif()
- foreach(IPATH ${MPI_ALL_INCLUDE_PATHS})
- string(REGEX REPLACE "^ ?-I" "" IPATH ${IPATH})
- string(REPLACE "//" "/" IPATH ${IPATH})
- string(REPLACE "\"" "" IPATH ${IPATH})
- file(TO_CMAKE_PATH "${IPATH}" IPATH)
- list(APPEND MPI_INCLUDE_PATH_WORK ${IPATH})
- endforeach()
+ # An MPI compiler wrapper could have its MPI libraries in the implictly
+ # linked directories of the compiler itself.
+ if(DEFINED CMAKE_${LANG}_IMPLICIT_LINK_DIRECTORIES)
+ list(APPEND MPI_LINK_DIRECTORIES_WORK "${CMAKE_${LANG}_IMPLICIT_LINK_DIRECTORIES}")
+ endif()
- # try using showme:incdirs if extracting didn't work.
- if (NOT MPI_INCLUDE_PATH_WORK)
- set(MPI_INCLUDE_PATH_WORK ${MPI_INCDIRS})
- separate_arguments(MPI_INCLUDE_PATH_WORK)
- endif()
+ # Determine full path names for all of the libraries that one needs
+ # to link against in an MPI program
+ unset(MPI_PLAIN_LIB_NAMES_WORK)
+ foreach(_MPI_LIB_NAME IN LISTS MPI_LIB_NAMES_WORK)
+ get_filename_component(_MPI_PLAIN_LIB_NAME "${_MPI_LIB_NAME}" NAME_WE)
+ list(APPEND MPI_PLAIN_LIB_NAMES_WORK "${_MPI_PLAIN_LIB_NAME}")
+ find_library(MPI_${_MPI_PLAIN_LIB_NAME}_LIBRARY
+ NAMES "${_MPI_LIB_NAME}" "lib${_MPI_LIB_NAME}"
+ HINTS ${MPI_LINK_DIRECTORIES_WORK}
+ DOC "Location of the ${_MPI_PLAIN_LIB_NAME} library for MPI"
+ )
+ mark_as_advanced(MPI_${_MPI_PLAIN_LIB_NAME}_LIBRARY)
+ endforeach()
- # If all else fails, just search for mpi.h in the normal include paths.
- if (NOT MPI_INCLUDE_PATH_WORK)
- set(MPI_HEADER_PATH "MPI_HEADER_PATH-NOTFOUND" CACHE FILEPATH "Cleared" FORCE)
- find_path(MPI_HEADER_PATH mpi.h
- HINTS ${_MPI_BASE_DIR} ${_MPI_PREFIX_PATH}
- PATH_SUFFIXES include)
- set(MPI_INCLUDE_PATH_WORK ${MPI_HEADER_PATH})
- endif()
+ # Deal with the libraries given with full path next
+ unset(MPI_DIRECT_LIB_NAMES_WORK)
+ foreach(_MPI_LIB_FULLPATH IN LISTS MPI_LIB_FULLPATHS_WORK)
+ get_filename_component(_MPI_PLAIN_LIB_NAME "${_MPI_LIB_FULLPATH}" NAME_WE)
+ get_filename_component(_MPI_LIB_NAME "${_MPI_LIB_FULLPATH}" NAME)
+ get_filename_component(_MPI_LIB_PATH "${_MPI_LIB_FULLPATH}" DIRECTORY)
+ list(APPEND MPI_DIRECT_LIB_NAMES_WORK "${_MPI_PLAIN_LIB_NAME}")
+ find_library(MPI_${_MPI_PLAIN_LIB_NAME}_LIBRARY
+ NAMES "${_MPI_LIB_NAME}"
+ HINTS ${_MPI_LIB_PATH}
+ DOC "Location of the ${_MPI_PLAIN_LIB_NAME} library for MPI"
+ )
+ mark_as_advanced(MPI_${_MPI_PLAIN_LIB_NAME}_LIBRARY)
+ endforeach()
+ if(MPI_DIRECT_LIB_NAMES_WORK)
+ set(MPI_PLAIN_LIB_NAMES_WORK "${MPI_DIRECT_LIB_NAMES_WORK};${MPI_PLAIN_LIB_NAMES_WORK}")
+ endif()
- # Extract linker paths from the link command line
- string(REGEX MATCHALL "(^| |-Wl,)(-L|/LIBPATH:)([^\" ]+|\"[^\"]+\")" MPI_ALL_LINK_PATHS "${MPI_LINK_CMDLINE}")
- set(MPI_LINK_PATH)
- foreach(LPATH ${MPI_ALL_LINK_PATHS})
- string(REGEX REPLACE "^(| |-Wl,)(-L|/LIBPATH:)" "" LPATH ${LPATH})
- string(REPLACE "//" "/" LPATH ${LPATH})
- list(APPEND MPI_LINK_PATH ${LPATH})
- endforeach()
+ # MPI might require pthread to work. The above mechanism wouldn't detect it, but we need to
+ # link it in that case. -lpthread is covered by the normal library treatment on the other hand.
+ if("${MPI_COMPILE_CMDLINE}" MATCHES "-pthread")
+ list(APPEND MPI_COMPILE_OPTIONS_WORK "-pthread")
+ if(MPI_LINK_FLAGS_WORK)
+ string(APPEND MPI_LINK_FLAGS_WORK " -pthread")
+ else()
+ set(MPI_LINK_FLAGS_WORK "-pthread")
+ endif()
+ endif()
- # try using showme:libdirs if extracting didn't work.
- if (NOT MPI_LINK_PATH)
- set(MPI_LINK_PATH ${MPI_LIBDIRS})
- separate_arguments(MPI_LINK_PATH)
- endif()
+ # If we found MPI, set up all of the appropriate cache entries
+ if(NOT MPI_${LANG}_COMPILE_OPTIONS)
+ set(MPI_${LANG}_COMPILE_OPTIONS ${MPI_COMPILE_OPTIONS_WORK} CACHE STRING "MPI ${LANG} compilation options" FORCE)
+ endif()
+ if(NOT MPI_${LANG}_COMPILE_DEFINITIONS)
+ set(MPI_${LANG}_COMPILE_DEFINITIONS ${MPI_COMPILE_DEFINITIONS_WORK} CACHE STRING "MPI ${LANG} compilation definitions" FORCE)
+ endif()
+ if(NOT MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS)
+ set(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS ${MPI_INCLUDE_DIRS_WORK} CACHE STRING "MPI ${LANG} additional include directories" FORCE)
+ endif()
+ if(NOT MPI_${LANG}_LINK_FLAGS)
+ set(MPI_${LANG}_LINK_FLAGS ${MPI_LINK_FLAGS_WORK} CACHE STRING "MPI ${LANG} linker flags" FORCE)
+ endif()
+ if(NOT MPI_${LANG}_LIB_NAMES)
+ set(MPI_${LANG}_LIB_NAMES ${MPI_PLAIN_LIB_NAMES_WORK} CACHE STRING "MPI ${LANG} libraries to link against" FORCE)
+ endif()
+ set(MPI_${LANG}_WRAPPER_FOUND TRUE PARENT_SCOPE)
+endfunction()
- # Extract linker flags from the link command line
- string(REGEX MATCHALL "(^| )(-Wl,|-Xlinker )([^\" ]+|\"[^\"]+\")" MPI_ALL_LINK_FLAGS "${MPI_LINK_CMDLINE}")
- set(MPI_LINK_FLAGS_WORK)
- foreach(FLAG ${MPI_ALL_LINK_FLAGS})
- string(REGEX REPLACE "^ " "" FLAG ${FLAG})
- if (MPI_LINK_FLAGS_WORK)
- string(APPEND MPI_LINK_FLAGS_WORK " ${FLAG}")
- else()
- set(MPI_LINK_FLAGS_WORK ${FLAG})
- endif()
- endforeach()
+function(_MPI_guess_settings LANG)
+ set(MPI_GUESS_FOUND FALSE)
+ # Currently only MSMPI and MPICH2 on Windows are supported, so we can skip this search if we're not targeting that.
+ if(WIN32)
+ # MSMPI
+
+ # The environment variables MSMPI_INC and MSMPILIB32/64 are the only ways of locating the MSMPI_SDK,
+ # which is installed separately from the runtime. Thus it's possible to have mpiexec but not MPI headers
+ # or import libraries and vice versa.
+ if(NOT MPI_GUESS_LIBRARY_NAME OR "${MPI_GUESS_LIBRARY_NAME}" STREQUAL "MSMPI")
+ # We first attempt to locate the msmpi.lib. Should be find it, we'll assume that the MPI present is indeed
+ # Microsoft MPI.
+ if("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
+ set(MPI_MSMPI_LIB_PATH "$ENV{MSMPI_LIB64}")
+ set(MPI_MSMPI_INC_PATH_EXTRA "$ENV{MSMPI_INC}/x64")
+ else()
+ set(MPI_MSMPI_LIB_PATH "$ENV{MSMPI_LIB32}")
+ set(MPI_MSMPI_INC_PATH_EXTRA "$ENV{MSMPI_INC}/x86")
+ endif()
- # Extract the set of libraries to link against from the link command
- # line
- string(REGEX MATCHALL "(^| )-l([^\" ]+|\"[^\"]+\")" MPI_LIBNAMES "${MPI_LINK_CMDLINE}")
- if(WIN32)
- # The intel wrappers on windows link against static versions of the MPI libraries.
- # The static libraries are simply listed on the command line without -l.
- # For instance: " icl ... impi.lib "
- string(REGEX MATCHALL "(^| )([^\" ]+)\\.lib" tmp "${MPI_LINK_CMDLINE}")
- list(APPEND MPI_LIBNAMES ${tmp})
+ find_library(MPI_msmpi_LIBRARY
+ NAMES msmpi
+ HINTS ${MPI_MSMPI_LIB_PATH}
+ DOC "Location of the msmpi library for Microsoft MPI")
+ mark_as_advanced(MPI_msmpi_LIBRARY)
+
+ if(MPI_msmpi_LIBRARY)
+ # Next, we attempt to locate the MPI header. Note that for Fortran we know that mpif.h is a way
+ # MSMPI can be used and therefore that header has to be present.
+ if(NOT MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS)
+ get_filename_component(MPI_MSMPI_INC_DIR "$ENV{MSMPI_INC}" REALPATH)
+ set(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS "${MPI_MSMPI_INC_DIR}" CACHE STRING "MPI ${LANG} additional include directories" FORCE)
+ unset(MPI_MSMPI_INC_DIR)
endif()
- # add the compiler implicit directories because some compilers
- # such as the intel compiler have libraries that show up
- # in the showme list that can only be found in the implicit
- # link directories of the compiler.
- if (DEFINED CMAKE_${lang}_IMPLICIT_LINK_DIRECTORIES)
- string(APPEND MPI_LINK_PATH
- ";${CMAKE_${lang}_IMPLICIT_LINK_DIRECTORIES}")
- endif ()
-
- # Determine full path names for all of the libraries that one needs
- # to link against in an MPI program
- foreach(LIB ${MPI_LIBNAMES})
- string(REGEX REPLACE "^ ?-l" "" LIB ${LIB})
- if(WIN32)
- string(REGEX REPLACE "\\.lib$" "" LIB ${LIB})
+ # For MSMPI, one can compile the MPI module by building the mpi.f90 shipped with the MSMPI SDK,
+ # thus it might be present or provided by the user. Figuring out which is supported is done later on.
+ # The PGI Fortran compiler for instance ships a prebuilt set of modules in its own include folder.
+ # Should a user be employing PGI or have built its own set and provided it via cache variables, the
+ # splitting routine would have located the module files.
+
+ # For C and C++, we're done here (MSMPI does not ship the MPI-2 C++ bindings) - however, for Fortran
+ # we need some extra library to glue Fortran support together:
+ # MSMPI ships 2-4 Fortran libraries, each for different Fortran compiler behaviors. The library names
+ # ending with a c are using the cdecl calling convention, whereas those ending with an s are for Fortran
+ # implementations using stdcall. Therefore, the 64-bit MSMPI only ships those ending in 'c', whereas the 32-bit
+ # has both variants available.
+ # The second difference is the last but one letter, if it's an e(nd), the length of a string argument is
+ # passed by the Fortran compiler after all other arguments on the parameter list, if it's an m(ixed),
+ # it's passed immediately after the string address.
+
+ # To summarize:
+ # - msmpifec: CHARACTER length passed after the parameter list and using cdecl calling convention
+ # - msmpifmc: CHARACTER length passed directly after string address and using cdecl calling convention
+ # - msmpifes: CHARACTER length passed after the parameter list and using stdcall calling convention
+ # - msmpifms: CHARACTER length passed directly after string address and using stdcall calling convention
+ # 32-bit MSMPI ships all four libraries, 64-bit MSMPI ships only the first two.
+
+ # As is, Intel Fortran and PGI Fortran both use the 'ec' variant of the calling convention, whereas
+ # the old Compaq Visual Fortran compiler defaulted to the 'ms' version. It's possible to make Intel Fortran
+ # use the CVF calling convention using /iface:cvf, but we assume - and this is also assumed in FortranCInterface -
+ # this isn't the case. It's also possible to make CVF use the 'ec' variant, using /iface=(cref,nomixed_str_len_arg).
+
+ # Our strategy is now to locate all libraries, but enter msmpifec into the LIB_NAMES array.
+ # Should this not be adequate it's a straightforward way for a user to change the LIB_NAMES array and
+ # have his library found. Still, this should not be necessary outside of exceptional cases, as reasoned.
+ if ("${LANG}" STREQUAL "Fortran")
+ set(MPI_MSMPI_CALLINGCONVS c)
+ if("${CMAKE_SIZEOF_VOID_P}" EQUAL 4)
+ list(APPEND MPI_MSMPI_CALLINGCONVS s)
endif()
- string(STRIP ${LIB} LIB)
- # MPI_LIB is cached by find_library, but we don't want that. Clear it first.
- set(MPI_LIB "MPI_LIB-NOTFOUND" CACHE FILEPATH "Cleared" FORCE)
- find_library(MPI_LIB NAMES ${LIB} HINTS ${MPI_LINK_PATH})
-
- if (MPI_LIB)
- list(APPEND MPI_LIBRARIES_WORK ${MPI_LIB})
- elseif (NOT MPI_FIND_QUIETLY)
- message(WARNING "Unable to find MPI library ${LIB}")
+ foreach(mpistrlenpos IN ITEMS e m)
+ foreach(mpicallingconv IN LISTS MPI_MSMPI_CALLINGCONVS)
+ find_library(MPI_msmpif${mpistrlenpos}${mpicallingconv}_LIBRARY
+ NAMES msmpif${mpistrlenpos}${mpicallingconv}
+ HINTS "${MPI_MSMPI_LIB_PATH}"
+ DOC "Location of the msmpi${mpistrlenpos}${mpicallingconv} library for Microsoft MPI")
+ mark_as_advanced(MPI_msmpif${mpistrlenpos}${mpicallingconv}_LIBRARY)
+ endforeach()
+ endforeach()
+ if(NOT MPI_${LANG}_LIB_NAMES)
+ set(MPI_${LANG}_LIB_NAMES "msmpi;msmpifec" CACHE STRING "MPI ${LANG} libraries to link against" FORCE)
endif()
- endforeach()
- # Sanity check MPI_LIBRARIES to make sure there are enough libraries
- list(LENGTH MPI_LIBRARIES_WORK MPI_NUMLIBS)
- list(LENGTH MPI_LIBNAMES MPI_NUMLIBS_EXPECTED)
- if (NOT MPI_NUMLIBS EQUAL MPI_NUMLIBS_EXPECTED)
- set(MPI_LIBRARIES_WORK "MPI_${lang}_LIBRARIES-NOTFOUND")
+ # At this point we're *not* done. MSMPI requires an additional include file for Fortran giving the value
+ # of MPI_AINT. This file is called mpifptr.h located in the x64 and x86 subfolders, respectively.
+ find_path(MPI_mpifptr_INCLUDE_DIR
+ NAMES "mpifptr.h"
+ HINTS "${MPI_MSMPI_INC_PATH_EXTRA}"
+ DOC "Location of the mpifptr.h extra header for Microsoft MPI")
+ if(NOT MPI_${LANG}_ADDITIONAL_INCLUDE_VARS)
+ set(MPI_${LANG}_ADDITIONAL_INCLUDE_VARS "mpifptr" CACHE STRING "MPI ${LANG} additional include directory variables, given in the form MPI_<name>_INCLUDE_DIR." FORCE)
+ endif()
+ mark_as_advanced(MPI_${LANG}_ADDITIONAL_INCLUDE_VARS MPI_mpifptr_INCLUDE_DIR)
+ else()
+ if(NOT MPI_${LANG}_LIB_NAMES)
+ set(MPI_${LANG}_LIB_NAMES "msmpi" CACHE STRING "MPI ${LANG} libraries to link against" FORCE)
+ endif()
endif()
+ mark_as_advanced(MPI_${LANG}_LIB_NAMES)
+ set(MPI_GUESS_FOUND TRUE)
endif()
+ endif()
- elseif(try_libs)
- # If we didn't have an MPI compiler script to interrogate, attempt to find everything
- # with plain old find functions. This is nasty because MPI implementations have LOTS of
- # different library names, so this section isn't going to be very generic. We need to
- # make sure it works for MS MPI, though, since there are no compiler wrappers for that.
- find_path(MPI_HEADER_PATH mpi.h
- HINTS ${_MPI_BASE_DIR} ${_MPI_PREFIX_PATH}
- PATH_SUFFIXES include Inc)
- set(MPI_INCLUDE_PATH_WORK ${MPI_HEADER_PATH})
-
- # Decide between 32-bit and 64-bit libraries for Microsoft's MPI
- if("${CMAKE_SIZEOF_VOID_P}" EQUAL 8)
- set(MS_MPI_ARCH_DIR x64)
- set(MS_MPI_ARCH_DIR2 amd64)
- else()
- set(MS_MPI_ARCH_DIR x86)
- set(MS_MPI_ARCH_DIR2 i386)
- endif()
+ # At this point there's not many MPIs that we could still consider.
+ # OpenMPI 1.6.x and below supported Windows, but these ship compiler wrappers that still work.
+ # The only other relevant MPI implementation without a wrapper is MPICH2, which had Windows support in 1.4.1p1 and older.
+ if(NOT MPI_GUESS_LIBRARY_NAME OR "${MPI_GUESS_LIBRARY_NAME}" STREQUAL "MPICH2")
+ set(MPI_MPICH_PREFIX_PATHS
+ "$ENV{ProgramW6432}/MPICH2/lib"
+ "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MPICH\\SMPD;binary]/../lib"
+ "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MPICH2;Path]/lib"
+ )
- set(MPI_LIB "MPI_LIB-NOTFOUND" CACHE FILEPATH "Cleared" FORCE)
- find_library(MPI_LIB
- NAMES mpi mpich mpich2 msmpi
- HINTS ${_MPI_BASE_DIR} ${_MPI_PREFIX_PATH}
- PATH_SUFFIXES lib lib/${MS_MPI_ARCH_DIR} Lib Lib/${MS_MPI_ARCH_DIR} Lib/${MS_MPI_ARCH_DIR2})
- set(MPI_LIBRARIES_WORK ${MPI_LIB})
-
- # Right now, we only know about the extra libs for C++.
- # We could add Fortran here (as there is usually libfmpich, etc.), but
- # this really only has to work with MS MPI on Windows.
- # Assume that other MPI's are covered by the compiler wrappers.
- if (${lang} STREQUAL CXX)
- set(MPI_LIB "MPI_LIB-NOTFOUND" CACHE FILEPATH "Cleared" FORCE)
- find_library(MPI_LIB
- NAMES mpi++ mpicxx cxx mpi_cxx
- HINTS ${_MPI_BASE_DIR} ${_MPI_PREFIX_PATH}
- PATH_SUFFIXES lib)
- if (MPI_LIBRARIES_WORK AND MPI_LIB)
- list(APPEND MPI_LIBRARIES_WORK ${MPI_LIB})
+ # All of C, C++ and Fortran will need mpi.lib, so we'll look for this first
+ find_library(MPI_mpi_LIBRARY
+ NAMES mpi
+ HINTS ${MPI_MPICH_PREFIX_PATHS})
+ mark_as_advanced(MPI_mpi_LIBRARY)
+ # If we found mpi.lib, we detect the rest of MPICH2
+ if(MPI_mpi_LIBRARY)
+ set(MPI_MPICH_LIB_NAMES "mpi")
+ # If MPI-2 C++ bindings are requested, we need to locate cxx.lib as well.
+ # Otherwise, MPICH_SKIP_MPICXX will be defined and these bindings aren't needed.
+ if("${LANG}" STREQUAL "CXX" AND NOT MPI_CXX_SKIP_MPICXX)
+ find_library(MPI_cxx_LIBRARY
+ NAMES cxx
+ HINTS ${MPI_MPICH_PREFIX_PATHS})
+ mark_as_advanced(MPI_cxx_LIBRARY)
+ list(APPEND MPI_MPICH_LIB_NAMES "cxx")
+ # For Fortran, MPICH2 provides three different libraries:
+ # fmpich2.lib which uses uppercase symbols and cdecl,
+ # fmpich2s.lib which uses uppercase symbols and stdcall (32-bit only),
+ # fmpich2g.lib which uses lowercase symbols with double underscores and cdecl.
+ # fmpich2s.lib would be useful for Compaq Visual Fortran, fmpich2g.lib has to be used with GNU g77 and is also
+ # provided in the form of an .a archive for MinGW and Cygwin. From our perspective, fmpich2.lib is the only one
+ # we need to try, and if it doesn't work with the given Fortran compiler we'd find out later on during validation
+ elseif("${LANG}" STREQUAL "Fortran")
+ find_library(MPI_fmpich2_LIBRARY
+ NAMES fmpich2
+ HINTS ${MPI_MPICH_PREFIX_PATHS})
+ find_library(MPI_fmpich2s_LIBRARY
+ NAMES fmpich2s
+ HINTS ${MPI_MPICH_PREFIX_PATHS})
+ find_library(MPI_fmpich2g_LIBRARY
+ NAMES fmpich2g
+ HINTS ${MPI_MPICH_PREFIX_PATHS})
+ mark_as_advanced(MPI_fmpich2_LIBRARY MPI_fmpich2s_LIBRARY MPI_fmpich2g_LIBRARY)
+ list(APPEND MPI_MPICH_LIB_NAMES "fmpich2")
endif()
- endif()
- if (NOT MPI_LIBRARIES_WORK)
- set(MPI_LIBRARIES_WORK "MPI_${lang}_LIBRARIES-NOTFOUND")
+ if(NOT MPI_${LANG}_LIB_NAMES)
+ set(MPI_${LANG}_LIB_NAMES "${MPI_MPICH_LIB_NAMES}" CACHE STRING "MPI ${LANG} libraries to link against" FORCE)
+ endif()
+ unset(MPI_MPICH_LIB_NAMES)
+
+ if(NOT MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS)
+ # For MPICH2, the include folder would be in ../include relative to the library folder.
+ get_filename_component(MPI_MPICH_ROOT_DIR "${MPI_mpi_LIBRARY}" DIRECTORY)
+ get_filename_component(MPI_MPICH_ROOT_DIR "${MPI_MPICH_ROOT_DIR}" DIRECTORY)
+ if(IS_DIRECTORY "${MPI_MPICH_ROOT_DIR}/include")
+ set(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS "${MPI_MPICH_ROOT_DIR}/include" CACHE STRING "MPI ${LANG} additional include directory variables, given in the form MPI_<name>_INCLUDE_DIR." FORCE)
+ endif()
+ unset(MPI_MPICH_ROOT_DIR)
+ endif()
+ set(MPI_GUESS_FOUND TRUE)
endif()
+ unset(MPI_MPICH_PREFIX_PATHS)
endif()
+ endif()
+ set(MPI_${LANG}_GUESS_FOUND "${MPI_GUESS_FOUND}" PARENT_SCOPE)
+endfunction()
- # If we found MPI, set up all of the appropriate cache entries
- set(MPI_${lang}_COMPILE_FLAGS ${MPI_COMPILE_FLAGS_WORK} CACHE STRING "MPI ${lang} compilation flags" FORCE)
- set(MPI_${lang}_INCLUDE_PATH ${MPI_INCLUDE_PATH_WORK} CACHE STRING "MPI ${lang} include path" FORCE)
- set(MPI_${lang}_LINK_FLAGS ${MPI_LINK_FLAGS_WORK} CACHE STRING "MPI ${lang} linking flags" FORCE)
- set(MPI_${lang}_LIBRARIES ${MPI_LIBRARIES_WORK} CACHE STRING "MPI ${lang} libraries to link against" FORCE)
- mark_as_advanced(MPI_${lang}_COMPILE_FLAGS MPI_${lang}_INCLUDE_PATH MPI_${lang}_LINK_FLAGS MPI_${lang}_LIBRARIES)
+function(_MPI_adjust_compile_definitions LANG)
+ if("${LANG}" STREQUAL "CXX")
+ # To disable the C++ bindings, we need to pass some definitions since the mpi.h header has to deal with both C and C++
+ # bindings in MPI-2.
+ if(MPI_CXX_SKIP_MPICXX AND NOT MPI_${LANG}_COMPILE_DEFINITIONS MATCHES "SKIP_MPICXX")
+ # MPICH_SKIP_MPICXX is being used in MPICH and derivatives like MVAPICH or Intel MPI
+ # OMPI_SKIP_MPICXX is being used in Open MPI
+ # _MPICC_H is being used for IBM Platform MPI
+ list(APPEND MPI_${LANG}_COMPILE_DEFINITIONS "MPICH_SKIP_MPICXX" "OMPI_SKIP_MPICXX" "_MPICC_H")
+ set(MPI_${LANG}_COMPILE_DEFINITIONS "${MPI_${LANG}_COMPILE_DEFINITIONS}" CACHE STRING "MPI ${LANG} compilation definitions" FORCE)
+ endif()
+ endif()
+endfunction()
+
+macro(_MPI_assemble_libraries LANG)
+ set(MPI_${LANG}_LIBRARIES "")
+ foreach(mpilib IN LISTS MPI_${LANG}_LIB_NAMES)
+ list(APPEND MPI_${LANG}_LIBRARIES ${MPI_${mpilib}_LIBRARY})
+ endforeach()
+endmacro()
+
+macro(_MPI_assemble_include_dirs LANG)
+ set(MPI_${LANG}_INCLUDE_DIRS "${MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS}")
+ if("${LANG}" MATCHES "(C|CXX)")
+ if(MPI_${LANG}_HEADER_DIR)
+ list(APPEND MPI_${LANG}_INCLUDE_DIRS "${MPI_${LANG}_HEADER_DIR}")
+ endif()
+ else() # Fortran
+ if(MPI_${LANG}_F77_HEADER_DIR)
+ list(APPEND MPI_${LANG}_INCLUDE_DIRS "${MPI_${LANG}_F77_HEADER_DIR}")
+ endif()
+ if(MPI_${LANG}_MODULE_DIR AND NOT "${MPI_${LANG}_MODULE_DIR}" IN_LIST MPI_${LANG}_INCLUDE_DIRS)
+ list(APPEND MPI_${LANG}_INCLUDE_DIRS "${MPI_${LANG}_MODULE_DIR}")
+ endif()
+ endif()
+ if(MPI_${LANG}_ADDITIONAL_INCLUDE_VARS)
+ foreach(mpiadditionalinclude IN LISTS MPI_${LANG}_ADDITIONAL_INCLUDE_VARS)
+ list(APPEND MPI_${LANG}_INCLUDE_DIRS "${MPI_${mpiadditionalinclude}_INCLUDE_DIR}")
+ endforeach()
+ endif()
+endmacro()
- # clear out our temporary lib/header detection variable here.
- set(MPI_LIB "MPI_LIB-NOTFOUND" CACHE INTERNAL "Scratch variable for MPI lib detection" FORCE)
- set(MPI_HEADER_PATH "MPI_HEADER_PATH-NOTFOUND" CACHE INTERNAL "Scratch variable for MPI header detection" FORCE)
+function(_MPI_split_include_dirs LANG)
+ # Backwards compatibility: Search INCLUDE_PATH if given.
+ if(MPI_${LANG}_INCLUDE_PATH)
+ list(APPEND MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS "${MPI_${LANG}_INCLUDE_PATH}")
endif()
- # finally set a found variable for each MPI language
- if (MPI_${lang}_INCLUDE_PATH AND MPI_${lang}_LIBRARIES)
- set(MPI_${lang}_FOUND TRUE PARENT_SCOPE)
- else()
- set(MPI_${lang}_FOUND FALSE PARENT_SCOPE)
+ # We try to find the headers/modules among those paths (and system paths)
+ # For C/C++, we just need to have a look for mpi.h.
+ if("${LANG}" MATCHES "(C|CXX)")
+ find_path(MPI_${LANG}_HEADER_DIR "mpi.h"
+ HINTS ${MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS}
+ )
+ mark_as_advanced(MPI_${LANG}_HEADER_DIR)
+ if(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS)
+ list(REMOVE_ITEM MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS "${MPI_${LANG}_HEADER_DIR}")
+ endif()
+ # Fortran is more complicated here: An implementation could provide
+ # any of the Fortran 77/90/2008 APIs for MPI. For example, MSMPI
+ # only provides Fortran 77 and - if mpi.f90 is built - potentially
+ # a Fortran 90 module.
+ elseif("${LANG}" STREQUAL "Fortran")
+ find_path(MPI_${LANG}_F77_HEADER_DIR "mpif.h"
+ HINTS ${MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS}
+ )
+ find_path(MPI_${LANG}_MODULE_DIR
+ NAMES "mpi.mod" "mpi_f08.mod"
+ HINTS ${MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS}
+ )
+ if(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS)
+ list(REMOVE_ITEM MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS
+ "${MPI_${LANG}_F77_HEADER_DIR}"
+ "${MPI_${LANG}_MODULE_DIR}"
+ )
+ endif()
+ mark_as_advanced(MPI_${LANG}_F77_HEADER_DIR MPI_${LANG}_MODULE_DIR)
endif()
+ set(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS ${MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS} CACHE STRING "MPI ${LANG} additional include directories" FORCE)
endfunction()
+macro(_MPI_create_imported_target LANG)
+ if(NOT TARGET MPI::MPI_${LANG})
+ add_library(MPI::MPI_${LANG} INTERFACE IMPORTED)
+ endif()
+
+ set_property(TARGET MPI::MPI_${LANG} PROPERTY INTERFACE_COMPILE_OPTIONS "${MPI_${LANG}_COMPILE_OPTIONS}")
+ set_property(TARGET MPI::MPI_${LANG} PROPERTY INTERFACE_COMPILE_DEFINITIONS "${MPI_${LANG}_COMPILE_DEFINITIONS}")
-# This function attempts to compile with the regular compiler, to see if MPI programs
-# work with it. This is a last ditch attempt after we've tried interrogating mpicc and
-# friends, and after we've tried to find generic libraries. Works on machines like
-# Cray XE6, where the modules environment changes what MPI version cc, CC, and ftn use.
-function(try_regular_compiler lang success)
- set(scratch_directory ${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY})
- if (${lang} STREQUAL Fortran)
- set(test_file ${scratch_directory}/cmake_mpi_test.f90)
- file(WRITE ${test_file}
- "program hello\n"
- "include 'mpif.h'\n"
- "integer ierror\n"
- "call MPI_INIT(ierror)\n"
- "call MPI_FINALIZE(ierror)\n"
- "end\n")
+ set_property(TARGET MPI::MPI_${LANG} PROPERTY INTERFACE_LINK_LIBRARIES "")
+ if(MPI_${LANG}_LINK_FLAGS)
+ set_property(TARGET MPI::MPI_${LANG} APPEND PROPERTY INTERFACE_LINK_LIBRARIES "${MPI_${LANG}_LINK_FLAGS}")
+ endif()
+ # If the compiler links MPI implicitly, no libraries will be found as they're contained within
+ # CMAKE_<LANG>_IMPLICIT_LINK_LIBRARIES already.
+ if(MPI_${LANG}_LIBRARIES)
+ set_property(TARGET MPI::MPI_${LANG} APPEND PROPERTY INTERFACE_LINK_LIBRARIES "${MPI_${LANG}_LIBRARIES}")
+ endif()
+ # Given the new design of FindMPI, INCLUDE_DIRS will always be located, even under implicit linking.
+ set_property(TARGET MPI::MPI_${LANG} PROPERTY INTERFACE_INCLUDE_DIRECTORIES "${MPI_${LANG}_INCLUDE_DIRS}")
+endmacro()
+
+function(_MPI_try_staged_settings LANG MPI_TEST_FILE_NAME MODE RUN_BINARY)
+ set(WORK_DIR "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindMPI")
+ set(SRC_DIR "${CMAKE_ROOT}/Modules/FindMPI")
+ set(BIN_FILE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindMPI/${MPI_TEST_FILE_NAME}_${LANG}.bin")
+ unset(MPI_TEST_COMPILE_DEFINITIONS)
+ if("${LANG}" STREQUAL "Fortran")
+ if("${MODE}" STREQUAL "F90_MODULE")
+ set(MPI_Fortran_INCLUDE_LINE "use mpi\n implicit none")
+ elseif("${MODE}" STREQUAL "F08_MODULE")
+ set(MPI_Fortran_INCLUDE_LINE "use mpi_f08\n implicit none")
+ else() # F77 header
+ set(MPI_Fortran_INCLUDE_LINE "implicit none\n include 'mpif.h'")
+ endif()
+ configure_file("${SRC_DIR}/${MPI_TEST_FILE_NAME}.f90.in" "${WORK_DIR}/${MPI_TEST_FILE_NAME}.f90" @ONLY)
+ set(MPI_TEST_SOURCE_FILE "${WORK_DIR}/${MPI_TEST_FILE_NAME}.f90")
+ elseif("${LANG}" STREQUAL "CXX")
+ configure_file("${SRC_DIR}/${MPI_TEST_FILE_NAME}.c" "${WORK_DIR}/${MPI_TEST_FILE_NAME}.cpp" COPYONLY)
+ set(MPI_TEST_SOURCE_FILE "${WORK_DIR}/${MPI_TEST_FILE_NAME}.cpp")
+ if("${MODE}" STREQUAL "TEST_MPICXX")
+ set(MPI_TEST_COMPILE_DEFINITIONS TEST_MPI_MPICXX)
+ endif()
+ else() # C
+ set(MPI_TEST_SOURCE_FILE "${SRC_DIR}/${MPI_TEST_FILE_NAME}.c")
+ endif()
+ if(RUN_BINARY)
+ try_run(MPI_RUN_RESULT_${LANG}_${MPI_TEST_FILE_NAME}_${MODE} MPI_RESULT_${LANG}_${MPI_TEST_FILE_NAME}_${MODE}
+ "${CMAKE_BINARY_DIR}" SOURCES "${MPI_TEST_SOURCE_FILE}"
+ COMPILE_DEFINITIONS ${MPI_TEST_COMPILE_DEFINITIONS}
+ LINK_LIBRARIES MPI::MPI_${LANG}
+ RUN_OUTPUT_VARIABLE MPI_RUN_OUTPUT_${LANG}_${MPI_TEST_FILE_NAME}_${MODE})
+ set(MPI_RUN_OUTPUT_${LANG}_${MPI_TEST_FILE_NAME}_${MODE} "${MPI_RUN_OUTPUT_${LANG}_${MPI_TEST_FILE_NAME}_${MODE}}" PARENT_SCOPE)
else()
- if (${lang} STREQUAL CXX)
- set(test_file ${scratch_directory}/cmake_mpi_test.cpp)
- else()
- set(test_file ${scratch_directory}/cmake_mpi_test.c)
- endif()
- file(WRITE ${test_file}
- "#include <mpi.h>\n"
- "int main(int argc, char **argv) {\n"
- " MPI_Init(&argc, &argv);\n"
- " MPI_Finalize();\n"
- "}\n")
- endif()
- try_compile(compiler_has_mpi ${scratch_directory} ${test_file})
- if (compiler_has_mpi)
- set(MPI_${lang}_NO_INTERROGATE ${CMAKE_${lang}_COMPILER} CACHE STRING "Whether to interrogate MPI ${lang} compiler" FORCE)
- set(MPI_${lang}_COMPILER ${CMAKE_${lang}_COMPILER} CACHE STRING "MPI ${lang} compiler" FORCE)
- set(MPI_${lang}_COMPILE_FLAGS "" CACHE STRING "MPI ${lang} compilation flags" FORCE)
- set(MPI_${lang}_INCLUDE_PATH "" CACHE STRING "MPI ${lang} include path" FORCE)
- set(MPI_${lang}_LINK_FLAGS "" CACHE STRING "MPI ${lang} linking flags" FORCE)
- set(MPI_${lang}_LIBRARIES "" CACHE STRING "MPI ${lang} libraries to link against" FORCE)
- endif()
- set(${success} ${compiler_has_mpi} PARENT_SCOPE)
- unset(compiler_has_mpi CACHE)
+ try_compile(MPI_RESULT_${LANG}_${MPI_TEST_FILE_NAME}_${MODE}
+ "${CMAKE_BINARY_DIR}" SOURCES "${MPI_TEST_SOURCE_FILE}"
+ COMPILE_DEFINITIONS ${MPI_TEST_COMPILE_DEFINITIONS}
+ LINK_LIBRARIES MPI::MPI_${LANG}
+ COPY_FILE "${BIN_FILE}")
+ endif()
endfunction()
-# End definitions, commence real work here.
+macro(_MPI_check_lang_works LANG)
+ # For Fortran we may have by the MPI-3 standard an implementation that provides:
+ # - the mpi_f08 module
+ # - *both*, the mpi module and 'mpif.h'
+ # Since older MPI standards (MPI-1) did not define anything but 'mpif.h', we need to check all three individually.
+ if( NOT MPI_${LANG}_WORKS )
+ if("${LANG}" STREQUAL "Fortran")
+ set(MPI_Fortran_INTEGER_LINE "(kind=MPI_INTEGER_KIND)")
+ _MPI_try_staged_settings(${LANG} test_mpi F77_HEADER FALSE)
+ _MPI_try_staged_settings(${LANG} test_mpi F90_MODULE FALSE)
+ _MPI_try_staged_settings(${LANG} test_mpi F08_MODULE FALSE)
+
+ set(MPI_${LANG}_WORKS FALSE)
+
+ foreach(mpimethod IN ITEMS F77_HEADER F08_MODULE F90_MODULE)
+ if(MPI_RESULT_${LANG}_test_mpi_${mpimethod})
+ set(MPI_${LANG}_WORKS TRUE)
+ set(MPI_${LANG}_HAVE_${mpimethod} TRUE)
+ else()
+ set(MPI_${LANG}_HAVE_${mpimethod} FALSE)
+ endif()
+ endforeach()
+ # MPI-1 versions had no MPI_INTGER_KIND defined, so we need to try without it.
+ # However, MPI-1 also did not define the Fortran 90 and 08 modules, so we only try the F77 header.
+ unset(MPI_Fortran_INTEGER_LINE)
+ if(NOT MPI_${LANG}_WORKS)
+ _MPI_try_staged_settings(${LANG} test_mpi F77_HEADER_NOKIND FALSE)
+ if(MPI_RESULT_${LANG}_test_mpi_F77_HEADER_NOKIND)
+ set(MPI_${LANG}_WORKS TRUE)
+ set(MPI_${LANG}_HAVE_F77_HEADER TRUE)
+ endif()
+ endif()
+ else()
+ _MPI_try_staged_settings(${LANG} test_mpi normal FALSE)
+ # If 'test_mpi' built correctly, we've found valid MPI settings. There might not be MPI-2 C++ support, but there can't
+ # be MPI-2 C++ support without the C bindings being present, so checking for them is sufficient.
+ set(MPI_${LANG}_WORKS "${MPI_RESULT_${LANG}_test_mpi_normal}")
+ endif()
+ endif()
+endmacro()
+
+# Some systems install various MPI implementations in separate folders in some MPI prefix
+# This macro enumerates all such subfolders and adds them to the list of hints that will be searched.
+macro(MPI_search_mpi_prefix_folder PREFIX_FOLDER)
+ if(EXISTS "${PREFIX_FOLDER}")
+ file(GLOB _MPI_folder_children RELATIVE "${PREFIX_FOLDER}" "${PREFIX_FOLDER}/*")
+ foreach(_MPI_folder_child IN LISTS _MPI_folder_children)
+ if(IS_DIRECTORY "${PREFIX_FOLDER}/${_MPI_folder_child}")
+ list(APPEND MPI_HINT_DIRS "${PREFIX_FOLDER}/${_MPI_folder_child}")
+ endif()
+ endforeach()
+ endif()
+endmacro()
+
+set(MPI_HINT_DIRS ${MPI_HOME} $ENV{MPI_HOME} $ENV{I_MPI_ROOT})
+if("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Linux")
+ # SUSE Linux Enterprise Server stores its MPI implementations under /usr/lib64/mpi/gcc/<name>
+ # We enumerate the subfolders and append each as a prefix
+ MPI_search_mpi_prefix_folder("/usr/lib64/mpi/gcc")
+elseif("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows")
+ # MSMPI stores its runtime in a special folder, this adds the possible locations to the hints.
+ list(APPEND MPI_HINT_DIRS $ENV{MSMPI_BIN} "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\MPI;InstallRoot]")
+elseif("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "FreeBSD")
+ # FreeBSD ships mpich under the normal system paths - but available openmpi implementations
+ # will be found in /usr/local/mpi/<name>
+ MPI_search_mpi_prefix_folder("/usr/local/mpi/")
+endif()
-# Most mpi distros have some form of mpiexec which gives us something we can reliably look for.
-find_program(MPIEXEC
- NAMES ${_MPI_EXEC_NAMES}
- HINTS ${MPI_HOME} $ENV{MPI_HOME}
- PATHS ${_MPI_PREFIX_PATH}
- PATH_SUFFIXES bin
+# Most MPI distributions have some form of mpiexec or mpirun which gives us something we can look for.
+# The MPI standard does not mandate the existence of either, but instead only makes requirements if a distribution
+# ships an mpiexec program (mpirun executables are not regulated by the standard).
+find_program(MPIEXEC_EXECUTABLE
+ NAMES ${_MPIEXEC_NAMES}
+ PATH_SUFFIXES bin sbin
+ HINTS ${MPI_HINT_DIRS}
DOC "Executable for running MPI programs.")
# call get_filename_component twice to remove mpiexec and the directory it exists in (typically bin).
# This gives us a fairly reliable base directory to search for /bin /lib and /include from.
-get_filename_component(_MPI_BASE_DIR "${MPIEXEC}" PATH)
+get_filename_component(_MPI_BASE_DIR "${MPIEXEC_EXECUTABLE}" PATH)
get_filename_component(_MPI_BASE_DIR "${_MPI_BASE_DIR}" PATH)
# According to the MPI standard, section 8.8 -n is a guaranteed, and the only guaranteed way to
# launch an MPI process using mpiexec if such a program exists.
-set(MPIEXEC_NUMPROC_FLAG "-n" CACHE STRING "Flag used by MPI to specify the number of processes for MPIEXEC; the next option will be the number of processes.")
-set(MPIEXEC_PREFLAGS "" CACHE STRING "These flags will be directly before the executable that is being run by MPIEXEC.")
-set(MPIEXEC_POSTFLAGS "" CACHE STRING "These flags will come after all flags given to MPIEXEC.")
-
-# Set the number of processes to the processor count and the previous default
-# of 2 if that couldn't be determined.
-include(${CMAKE_CURRENT_LIST_DIR}/ProcessorCount.cmake)
-ProcessorCount(_MPIEXEC_NUMPROCS)
-if("${_MPIEXEC_NUMPROCS}" EQUAL "0")
- set(_MPIEXEC_NUMPROCS 2)
-endif()
-set(MPIEXEC_MAX_NUMPROCS "${_MPIEXEC_NUMPROCS}" CACHE STRING "Maximum number of processors available to run MPI applications.")
-unset(_MPIEXEC_NUMPROCS)
-mark_as_advanced(MPIEXEC MPIEXEC_NUMPROC_FLAG MPIEXEC_PREFLAGS MPIEXEC_POSTFLAGS MPIEXEC_MAX_NUMPROCS)
+set(MPIEXEC_NUMPROC_FLAG "-n" CACHE STRING "Flag used by MPI to specify the number of processes for mpiexec; the next option will be the number of processes.")
+set(MPIEXEC_PREFLAGS "" CACHE STRING "These flags will be directly before the executable that is being run by mpiexec.")
+set(MPIEXEC_POSTFLAGS "" CACHE STRING "These flags will be placed after all flags passed to mpiexec.")
+# Set the number of processes to the physical processor count
+cmake_host_system_information(RESULT _MPIEXEC_NUMPROCS QUERY NUMBER_OF_PHYSICAL_CORES)
+set(MPIEXEC_MAX_NUMPROCS "${_MPIEXEC_NUMPROCS}" CACHE STRING "Maximum number of processors available to run MPI applications.")
+unset(_MPIEXEC_NUMPROCS)
+mark_as_advanced(MPIEXEC_EXECUTABLE MPIEXEC_NUMPROC_FLAG MPIEXEC_PREFLAGS MPIEXEC_POSTFLAGS MPIEXEC_MAX_NUMPROCS)
#=============================================================================
# Backward compatibility input hacks. Propagate the FindMPI hints to C and
# CXX if the respective new versions are not defined. Translate the old
-# MPI_LIBRARY and MPI_EXTRA_LIBRARY to respective MPI_${lang}_LIBRARIES.
+# MPI_LIBRARY and MPI_EXTRA_LIBRARY to respective MPI_${LANG}_LIBRARIES.
#
# Once we find the new variables, we translate them back into their old
# equivalents below.
-foreach (lang C CXX)
+foreach (LANG IN ITEMS C CXX)
# Old input variables.
set(_MPI_OLD_INPUT_VARS COMPILER COMPILE_FLAGS INCLUDE_PATH LINK_FLAGS)
# Set new vars based on their old equivalents, if the new versions are not already set.
foreach (var ${_MPI_OLD_INPUT_VARS})
- if (NOT MPI_${lang}_${var} AND MPI_${var})
- set(MPI_${lang}_${var} "${MPI_${var}}")
+ if (NOT MPI_${LANG}_${var} AND MPI_${var})
+ set(MPI_${LANG}_${var} "${MPI_${var}}")
endif()
endforeach()
- # Special handling for MPI_LIBRARY and MPI_EXTRA_LIBRARY, which we nixed in the
- # new FindMPI. These need to be merged into MPI_<lang>_LIBRARIES
- if (NOT MPI_${lang}_LIBRARIES AND (MPI_LIBRARY OR MPI_EXTRA_LIBRARY))
- set(MPI_${lang}_LIBRARIES ${MPI_LIBRARY} ${MPI_EXTRA_LIBRARY})
+ # Chop the old compile flags into options and definitions
+ if(MPI_${LANG}_COMPILE_FLAGS)
+ unset(MPI_${LANG}_COMPILE_OPTIONS)
+ unset(MPI_${LANG}_COMPILE_DEFINITIONS)
+ separate_arguments(MPI_SEPARATE_FLAGS NATIVE_COMMAND "${MPI_${LANG}_COMPILE_FLAGS}")
+ foreach(_MPI_FLAG IN LISTS MPI_SEPARATE_FLAGS)
+ if("${_MPI_FLAG}" MATCHES "^ *[-/D]([^ ]+)")
+ list(APPEND MPI_${LANG}_COMPILE_DEFINITIONS "${CMAKE_MATCH_1}")
+ else()
+ list(APPEND MPI_${LANG}_COMPILE_FLAGS "${_MPI_FLAG}")
+ endif()
+ endforeach()
+ unset(MPI_SEPARATE_FLAGS)
+ endif()
+
+ # If a list of libraries was given, we'll split it into new-style cache variables
+ if(NOT MPI_${LANG}_LIB_NAMES)
+ foreach(_MPI_LIB IN LISTS MPI_${LANG}_LIBRARIES MPI_LIBRARY MPI_EXTRA_LIBRARY)
+ get_filename_component(_MPI_PLAIN_LIB_NAME "${_MPI_LIB}" NAME_WE)
+ get_filename_component(_MPI_LIB_NAME "${_MPI_LIB}" NAME)
+ get_filename_component(_MPI_LIB_DIR "${_MPI_LIB}" DIRECTORY)
+ list(APPEND MPI_PLAIN_LIB_NAMES_WORK "${_MPI_PLAIN_LIB_NAME}")
+ find_library(MPI_${_MPI_PLAIN_LIB_NAME}_LIBRARY
+ NAMES "${_MPI_LIB_NAME}" "lib${_MPI_LIB_NAME}"
+ HINTS ${_MPI_LIB_DIR} $ENV{MPI_LIB}
+ DOC "Location of the ${_MPI_PLAIN_LIB_NAME} library for MPI"
+ )
+ mark_as_advanced(MPI_${_MPI_PLAIN_LIB_NAME}_LIBRARY)
+ endforeach()
endif()
endforeach()
#=============================================================================
+unset(MPI_VERSION)
+unset(MPI_VERSION_MAJOR)
+unset(MPI_VERSION_MINOR)
+
+unset(_MPI_MIN_VERSION)
# This loop finds the compilers and sends them off for interrogation.
-foreach (lang C CXX Fortran)
- if (CMAKE_${lang}_COMPILER_WORKS)
- # If the user supplies a compiler *name* instead of an absolute path, assume that we need to find THAT compiler.
- if (MPI_${lang}_COMPILER)
- if (NOT IS_ABSOLUTE "${MPI_${lang}_COMPILER}")
- # Get rid of our default list of names and just search for the name the user wants.
- set(_MPI_${lang}_COMPILER_NAMES ${MPI_${lang}_COMPILER})
- set(MPI_${lang}_COMPILER "MPI_${lang}_COMPILER-NOTFOUND" CACHE FILEPATH "Cleared" FORCE)
- endif()
- # If the user specifies a compiler, we don't want to try to search libraries either.
- set(try_libs FALSE)
+foreach(LANG IN ITEMS C CXX Fortran)
+ if(CMAKE_${LANG}_COMPILER_LOADED)
+ if(NOT MPI_FIND_COMPONENTS)
+ set(_MPI_FIND_${LANG} TRUE)
+ elseif( ${LANG} IN_LIST MPI_FIND_COMPONENTS)
+ set(_MPI_FIND_${LANG} TRUE)
+ elseif( ${LANG} STREQUAL CXX AND NOT MPI_CXX_SKIP_MPICXX AND MPICXX IN_LIST MPI_FIND_COMPONENTS )
+ set(_MPI_FIND_${LANG} TRUE)
else()
- set(try_libs TRUE)
+ set(_MPI_FIND_${LANG} FALSE)
+ endif()
+ else()
+ set(_MPI_FIND_${LANG} FALSE)
+ endif()
+ if(_MPI_FIND_${LANG})
+ if( ${LANG} STREQUAL CXX AND NOT MPICXX IN_LIST MPI_FIND_COMPONENTS )
+ set(MPI_CXX_SKIP_MPICXX FALSE CACHE BOOL "If true, the MPI-2 C++ bindings are disabled using definitions.")
+ mark_as_advanced(MPI_CXX_SKIP_MPICXX)
endif()
+ if(NOT (MPI_${LANG}_LIB_NAMES AND (MPI_${LANG}_INCLUDE_PATH OR MPI_${LANG}_INCLUDE_DIRS OR MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS)))
+ if(NOT MPI_${LANG}_COMPILER AND NOT MPI_ASSUME_NO_BUILTIN_MPI)
+ # Should the imported targets be empty, we effectively try whether the compiler supports MPI on its own, which is the case on e.g.
+ # Cray PrgEnv.
+ _MPI_create_imported_target(${LANG})
+ _MPI_check_lang_works(${LANG})
+
+ # If the compiler can build MPI code on its own, it functions as an MPI compiler and we'll set the variable to point to it.
+ if(MPI_${LANG}_WORKS)
+ set(MPI_${LANG}_COMPILER "${CMAKE_${LANG}_COMPILER}" CACHE FILEPATH "MPI compiler for ${LANG}" FORCE)
+ endif()
+ endif()
- find_program(MPI_${lang}_COMPILER
- NAMES ${_MPI_${lang}_COMPILER_NAMES}
- HINTS ${_MPI_BASE_DIR}/bin
- PATHS ${_MPI_PREFIX_PATH}
- )
- interrogate_mpi_compiler(${lang} ${try_libs})
- mark_as_advanced(MPI_${lang}_COMPILER)
+ # If the user specified a library name we assume they prefer that library over a wrapper. If not, they can disable skipping manually.
+ if(NOT DEFINED MPI_SKIP_COMPILER_WRAPPER AND MPI_GUESS_LIBRARY_NAME)
+ set(MPI_SKIP_COMPILER_WRAPPER TRUE)
+ endif()
+ if(NOT MPI_SKIP_COMPILER_WRAPPER)
+ if(MPI_${LANG}_COMPILER)
+ # If the user supplies a compiler *name* instead of an absolute path, assume that we need to find THAT compiler.
+ if (NOT IS_ABSOLUTE "${MPI_${LANG}_COMPILER}")
+ # Get rid of our default list of names and just search for the name the user wants.
+ set(_MPI_${LANG}_COMPILER_NAMES "${MPI_${LANG}_COMPILER}")
+ unset(MPI_${LANG}_COMPILER CACHE)
+ endif()
+ # If the user specifies a compiler, we don't want to try to search libraries either.
+ set(MPI_PINNED_COMPILER TRUE)
+ else()
+ set(MPI_PINNED_COMPILER FALSE)
+ endif()
+
+ # If we have an MPI base directory, we'll try all compiler names in that one first.
+ # This should prevent mixing different MPI environments
+ if(_MPI_BASE_DIR)
+ find_program(MPI_${LANG}_COMPILER
+ NAMES ${_MPI_${LANG}_COMPILER_NAMES}
+ PATH_SUFFIXES bin sbin
+ HINTS ${_MPI_BASE_DIR}
+ NO_DEFAULT_PATH
+ DOC "MPI compiler for ${LANG}"
+ )
+ endif()
+
+ # If the base directory did not help (for example because the mpiexec isn't in the same directory as the compilers),
+ # we shall try searching in the default paths.
+ find_program(MPI_${LANG}_COMPILER
+ NAMES ${_MPI_${LANG}_COMPILER_NAMES}
+ PATH_SUFFIXES bin sbin
+ DOC "MPI compiler for ${LANG}"
+ )
+
+ if(MPI_${LANG}_COMPILER STREQUAL CMAKE_${LANG}_COMPILER)
+ set(MPI_SKIP_GUESSING TRUE)
+ elseif(MPI_${LANG}_COMPILER)
+ _MPI_interrogate_compiler(${LANG})
+ else()
+ set(MPI_${LANG}_WRAPPER_FOUND FALSE)
+ endif()
+ else()
+ set(MPI_${LANG}_WRAPPER_FOUND FALSE)
+ set(MPI_PINNED_COMPILER FALSE)
+ endif()
- # last ditch try -- if nothing works so far, just try running the regular compiler and
- # see if we can create an MPI executable.
- set(regular_compiler_worked 0)
- if (NOT MPI_${lang}_LIBRARIES OR NOT MPI_${lang}_INCLUDE_PATH)
- try_regular_compiler(${lang} regular_compiler_worked)
+ if(NOT MPI_${LANG}_WRAPPER_FOUND AND NOT MPI_PINNED_COMPILER)
+ # For C++, we may use the settings for C. Should a given compiler wrapper for C++ not exist, but one for C does, we copy over the
+ # settings for C. An MPI distribution that is in this situation would be IBM Platform MPI.
+ if("${LANG}" STREQUAL "CXX" AND MPI_C_WRAPPER_FOUND)
+ set(MPI_${LANG}_COMPILE_OPTIONS ${MPI_C_COMPILE_OPTIONS} CACHE STRING "MPI ${LANG} compilation options" )
+ set(MPI_${LANG}_COMPILE_DEFINITIONS ${MPI_C_COMPILE_DEFINITIONS} CACHE STRING "MPI ${LANG} compilation definitions" )
+ set(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS ${MPI_C_INCLUDE_DIRS} CACHE STRING "MPI ${LANG} additional include directories")
+ set(MPI_${LANG}_LINK_FLAGS ${MPI_C_LINK_FLAGS} CACHE STRING "MPI ${LANG} linker flags" )
+ set(MPI_${LANG}_LIB_NAMES ${MPI_C_LIB_NAMES} CACHE STRING "MPI ${LANG} libraries to link against" )
+ set(MPI_${LANG}_WRAPPER_FOUND TRUE)
+ elseif(NOT MPI_SKIP_GUESSING)
+ _MPI_guess_settings(${LANG})
+ endif()
+ endif()
endif()
- set(MPI_${lang}_FIND_QUIETLY ${MPI_FIND_QUIETLY})
- set(MPI_${lang}_FIND_REQUIRED ${MPI_FIND_REQUIRED})
- set(MPI_${lang}_FIND_VERSION ${MPI_FIND_VERSION})
- set(MPI_${lang}_FIND_VERSION_EXACT ${MPI_FIND_VERSION_EXACT})
+ _MPI_split_include_dirs(${LANG})
+ if(NOT MPI_${LANG}_COMPILER STREQUAL CMAKE_${LANG}_COMPILER)
+ _MPI_assemble_include_dirs(${LANG})
+ _MPI_assemble_libraries(${LANG})
+ endif()
+ _MPI_adjust_compile_definitions(${LANG})
+ # We always create imported targets even if they're empty
+ _MPI_create_imported_target(${LANG})
- if (regular_compiler_worked)
- find_package_handle_standard_args(MPI_${lang} DEFAULT_MSG MPI_${lang}_COMPILER)
- else()
- find_package_handle_standard_args(MPI_${lang} DEFAULT_MSG MPI_${lang}_LIBRARIES MPI_${lang}_INCLUDE_PATH)
+ if(NOT MPI_${LANG}_WORKS)
+ _MPI_check_lang_works(${LANG})
endif()
- if(MPI_${lang}_FOUND)
- if(NOT TARGET MPI::MPI_${lang})
- add_library(MPI::MPI_${lang} INTERFACE IMPORTED)
+ # Next, we'll initialize the MPI variables that have not been previously set.
+ set(MPI_${LANG}_COMPILE_OPTIONS "" CACHE STRING "MPI ${LANG} compilation flags" )
+ set(MPI_${LANG}_COMPILE_DEFINITIONS "" CACHE STRING "MPI ${LANG} compilation definitions" )
+ set(MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS "" CACHE STRING "MPI ${LANG} additional include directories")
+ set(MPI_${LANG}_LINK_FLAGS "" CACHE STRING "MPI ${LANG} linker flags" )
+ set(MPI_${LANG}_LIB_NAMES "" CACHE STRING "MPI ${LANG} libraries to link against" )
+ mark_as_advanced(MPI_${LANG}_COMPILE_OPTIONS MPI_${LANG}_COMPILE_DEFINITIONS MPI_${LANG}_LINK_FLAGS
+ MPI_${LANG}_LIB_NAMES MPI_${LANG}_ADDITIONAL_INCLUDE_DIRS MPI_${LANG}_COMPILER)
+
+ # If we've found MPI, then we'll perform additional analysis: Determine the MPI version, MPI library version, supported
+ # MPI APIs (i.e. MPI-2 C++ bindings). For Fortran we also need to find specific parameters if we're under MPI-3.
+ if(MPI_${LANG}_WORKS)
+ if("${LANG}" STREQUAL "CXX" AND NOT DEFINED MPI_MPICXX_FOUND)
+ if(NOT MPI_CXX_SKIP_MPICXX AND NOT MPI_CXX_VALIDATE_SKIP_MPICXX)
+ _MPI_try_staged_settings(${LANG} test_mpi MPICXX FALSE)
+ if(MPI_RESULT_${LANG}_test_mpi_MPICXX)
+ set(MPI_MPICXX_FOUND TRUE)
+ else()
+ set(MPI_MPICXX_FOUND FALSE)
+ endif()
+ else()
+ set(MPI_MPICXX_FOUND FALSE)
+ endif()
+ endif()
+
+ # At this point, we know the bindings present but not the MPI version or anything else.
+ if(NOT DEFINED MPI_${LANG}_VERSION)
+ unset(MPI_${LANG}_VERSION_MAJOR)
+ unset(MPI_${LANG}_VERSION_MINOR)
+ endif()
+ set(MPI_BIN_FOLDER ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindMPI)
+
+ # For Fortran, we'll want to use the most modern MPI binding to test capabilities other than the
+ # Fortran parameters, since those depend on the method of consumption.
+ # For C++, we can always use the C bindings, and should do so, since the C++ bindings do not exist in MPI-3
+ # whereas the C bindings do, and the C++ bindings never offered any feature advantage over their C counterparts.
+ if("${LANG}" STREQUAL "Fortran")
+ if(MPI_${LANG}_HAVE_F08_MODULE)
+ set(MPI_${LANG}_HIGHEST_METHOD F08_MODULE)
+ elseif(MPI_${LANG}_HAVE_F90_MODULE)
+ set(MPI_${LANG}_HIGHEST_METHOD F90_MODULE)
+ else()
+ set(MPI_${LANG}_HIGHEST_METHOD F77_HEADER)
+ endif()
+
+ # Another difference between C and Fortran is that we can't use the preprocessor to determine whether MPI_VERSION
+ # and MPI_SUBVERSION are provided. These defines did not exist in MPI 1.0 and 1.1 and therefore might not
+ # exist. For C/C++, test_mpi.c will handle the MPI_VERSION extraction, but for Fortran, we need mpiver.f90.
+ if(NOT DEFINED MPI_${LANG}_VERSION)
+ _MPI_try_staged_settings(${LANG} mpiver ${MPI_${LANG}_HIGHEST_METHOD} FALSE)
+ if(MPI_RESULT_${LANG}_mpiver_${MPI_${LANG}_HIGHEST_METHOD})
+ file(STRINGS ${MPI_BIN_FOLDER}/mpiver_${LANG}.bin _MPI_VERSION_STRING LIMIT_COUNT 1 REGEX "INFO:MPI-VER")
+ if("${_MPI_VERSION_STRING}" MATCHES ".*INFO:MPI-VER\\[([0-9]+)\\.([0-9]+)\\].*")
+ set(MPI_${LANG}_VERSION_MAJOR "${CMAKE_MATCH_1}")
+ set(MPI_${LANG}_VERSION_MINOR "${CMAKE_MATCH_2}")
+ set(MPI_${LANG}_VERSION "${MPI_${LANG}_VERSION_MAJOR}.${MPI_${LANG}_VERSION_MINOR}")
+ endif()
+ endif()
+ endif()
+
+ # Finally, we want to find out which capabilities a given interface supports, compare the MPI-3 standard.
+ # This is determined by interface specific parameters MPI_SUBARRAYS_SUPPORTED and MPI_ASYNC_PROTECTS_NONBLOCKING
+ # and might vary between the different methods of consumption.
+ if(MPI_DETERMINE_Fortran_CAPABILITIES AND NOT MPI_Fortran_CAPABILITIES_DETERMINED)
+ foreach(mpimethod IN ITEMS F08_MODULE F90_MODULE F77_HEADER)
+ if(MPI_${LANG}_HAVE_${mpimethod})
+ set(MPI_${LANG}_${mpimethod}_SUBARRAYS FALSE)
+ set(MPI_${LANG}_${mpimethod}_ASYNCPROT FALSE)
+ _MPI_try_staged_settings(${LANG} fortranparam_mpi ${mpimethod} TRUE)
+ if(MPI_RESULT_${LANG}_fortranparam_mpi_${mpimethod} AND
+ NOT "${MPI_RUN_RESULT_${LANG}_fortranparam_mpi_${mpimethod}}" STREQUAL "FAILED_TO_RUN")
+ if("${MPI_RUN_OUTPUT_${LANG}_fortranparam_mpi_${mpimethod}}" MATCHES
+ ".*INFO:SUBARRAYS\\[ *([TF]) *\\]-ASYNCPROT\\[ *([TF]) *\\].*")
+ if("${CMAKE_MATCH_1}" STREQUAL "T")
+ set(MPI_${LANG}_${mpimethod}_SUBARRAYS TRUE)
+ endif()
+ if("${CMAKE_MATCH_2}" STREQUAL "T")
+ set(MPI_${LANG}_${mpimethod}_ASYNCPROT TRUE)
+ endif()
+ endif()
+ endif()
+ endif()
+ endforeach()
+ set(MPI_Fortran_CAPABILITIES_DETERMINED TRUE)
+ endif()
+ else()
+ set(MPI_${LANG}_HIGHEST_METHOD normal)
+
+ # By the MPI-2 standard, MPI_VERSION and MPI_SUBVERSION are valid for both C and C++ bindings.
+ if(NOT DEFINED MPI_${LANG}_VERSION)
+ file(STRINGS ${MPI_BIN_FOLDER}/test_mpi_${LANG}.bin _MPI_VERSION_STRING LIMIT_COUNT 1 REGEX "INFO:MPI-VER")
+ if("${_MPI_VERSION_STRING}" MATCHES ".*INFO:MPI-VER\\[([0-9]+)\\.([0-9]+)\\].*")
+ set(MPI_${LANG}_VERSION_MAJOR "${CMAKE_MATCH_1}")
+ set(MPI_${LANG}_VERSION_MINOR "${CMAKE_MATCH_2}")
+ set(MPI_${LANG}_VERSION "${MPI_${LANG}_VERSION_MAJOR}.${MPI_${LANG}_VERSION_MINOR}")
+ endif()
+ endif()
endif()
- if(MPI_${lang}_COMPILE_FLAGS)
- separate_arguments(_MPI_${lang}_COMPILE_OPTIONS NATIVE_COMMAND "${MPI_${lang}_COMPILE_FLAGS}")
- set_property(TARGET MPI::MPI_${lang} PROPERTY
- INTERFACE_COMPILE_OPTIONS "${_MPI_${lang}_COMPILE_OPTIONS}")
+
+ unset(MPI_BIN_FOLDER)
+
+ # At this point, we have dealt with determining the MPI version and parameters for each Fortran method available.
+ # The one remaining issue is to determine which MPI library is installed.
+ # Determining the version and vendor of the MPI library is only possible via MPI_Get_library_version() at runtime,
+ # and therefore we cannot do this while cross-compiling (a user may still define MPI_<lang>_LIBRARY_VERSION_STRING
+ # themselves and we'll attempt splitting it, which is equivalent to provide the try_run output).
+ # It's also worth noting that the installed version string can depend on the language, or on the system the binary
+ # runs on if MPI is not statically linked.
+ if(MPI_DETERMINE_LIBRARY_VERSION AND NOT MPI_${LANG}_LIBRARY_VERSION_STRING)
+ _MPI_try_staged_settings(${LANG} libver_mpi ${MPI_${LANG}_HIGHEST_METHOD} TRUE)
+ if(MPI_RESULT_${LANG}_libver_mpi_${MPI_${LANG}_HIGHEST_METHOD} AND
+ "${MPI_RUN_RESULT_${LANG}_libver_mpi_${MPI_${LANG}_HIGHEST_METHOD}}" EQUAL "0")
+ string(STRIP "${MPI_RUN_OUTPUT_${LANG}_libver_mpi_${MPI_${LANG}_HIGHEST_METHOD}}"
+ MPI_${LANG}_LIBRARY_VERSION_STRING)
+ else()
+ set(MPI_${LANG}_LIBRARY_VERSION_STRING "NOTFOUND")
+ endif()
endif()
+ endif()
- unset(_MPI_${lang}_LINK_LINE)
- if(MPI_${lang}_LINK_FLAGS)
- list(APPEND _MPI_${lang}_LINK_LINE "${MPI_${lang}_LINK_FLAGS}")
+ set(MPI_${LANG}_FIND_QUIETLY ${MPI_FIND_QUIETLY})
+ set(MPI_${LANG}_FIND_VERSION ${MPI_FIND_VERSION})
+ set(MPI_${LANG}_FIND_VERSION_EXACT ${MPI_FIND_VERSION_EXACT})
+
+ unset(MPI_${LANG}_REQUIRED_VARS)
+ if (MPI_${LANG}_WRAPPER_FOUND OR MPI_${LANG}_GUESS_FOUND)
+ foreach(mpilibname IN LISTS MPI_${LANG}_LIB_NAMES)
+ list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${mpilibname}_LIBRARY")
+ endforeach()
+ list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_LIB_NAMES")
+ if("${LANG}" STREQUAL "Fortran")
+ # For Fortran we only need one of the module or header directories to have *some* support for MPI.
+ if(NOT MPI_${LANG}_MODULE_DIR)
+ list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_F77_HEADER_DIR")
+ endif()
+ if(NOT MPI_${LANG}_F77_HEADER_DIR)
+ list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_MODULE_DIR")
+ endif()
+ else()
+ list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_HEADER_DIR")
+ endif()
+ if(MPI_${LANG}_ADDITIONAL_INCLUDE_VARS)
+ foreach(mpiincvar IN LISTS MPI_${LANG}_ADDITIONAL_INCLUDE_VARS)
+ list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${mpiincvar}_INCLUDE_DIR")
+ endforeach()
+ endif()
+ # Append the works variable now. If the settings did not work, this will show up properly.
+ list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_WORKS")
+ else()
+ # If the compiler worked implicitly, use its path as output.
+ # Should the compiler variable be set, we also require it to work.
+ list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_COMPILER")
+ if(MPI_${LANG}_COMPILER)
+ list(APPEND MPI_${LANG}_REQUIRED_VARS "MPI_${LANG}_WORKS")
endif()
- list(APPEND _MPI_${lang}_LINK_LINE "${MPI_${lang}_LIBRARIES}")
- set_property(TARGET MPI::MPI_${lang} PROPERTY
- INTERFACE_LINK_LIBRARIES "${_MPI_${lang}_LINK_LINE}")
+ endif()
+ find_package_handle_standard_args(MPI_${LANG} REQUIRED_VARS ${MPI_${LANG}_REQUIRED_VARS}
+ VERSION_VAR MPI_${LANG}_VERSION)
- set_property(TARGET MPI::MPI_${lang} PROPERTY
- INTERFACE_INCLUDE_DIRECTORIES "${MPI_${lang}_INCLUDE_PATH}")
+ if(DEFINED MPI_${LANG}_VERSION)
+ if(NOT _MPI_MIN_VERSION OR _MPI_MIN_VERSION VERSION_GREATER MPI_${LANG}_VERSION)
+ set(_MPI_MIN_VERSION MPI_${LANG}_VERSION)
+ endif()
endif()
endif()
endforeach()
+unset(_MPI_REQ_VARS)
+foreach(LANG IN ITEMS C CXX Fortran)
+ if((NOT MPI_FIND_COMPONENTS AND CMAKE_${LANG}_COMPILER_LOADED) OR LANG IN_LIST MPI_FIND_COMPONENTS)
+ list(APPEND _MPI_REQ_VARS "MPI_${LANG}_FOUND")
+ endif()
+endforeach()
+
+if(MPICXX IN_LIST MPI_FIND_COMPONENTS)
+ list(APPEND _MPI_REQ_VARS "MPI_MPICXX_FOUND")
+endif()
+
+find_package_handle_standard_args(MPI
+ REQUIRED_VARS ${_MPI_REQ_VARS}
+ VERSION_VAR ${_MPI_MIN_VERSION}
+ HANDLE_COMPONENTS)
#=============================================================================
# More backward compatibility stuff
-#
-# Bare MPI sans ${lang} vars are set to CXX then C, depending on what was found.
+
+# For compatibility reasons, we also define MPIEXEC
+set(MPIEXEC "${MPIEXEC_EXECUTABLE}")
+
+# Copy over MPI_<LANG>_INCLUDE_PATH from the assembled INCLUDE_DIRS.
+foreach(LANG IN ITEMS C CXX Fortran)
+ if(MPI_${LANG}_FOUND)
+ set(MPI_${LANG}_INCLUDE_PATH "${MPI_${LANG}_INCLUDE_DIRS}")
+ unset(MPI_${LANG}_COMPILE_FLAGS)
+ if(MPI_${LANG}_COMPILE_OPTIONS)
+ set(MPI_${LANG}_COMPILE_FLAGS "${MPI_${LANG}_COMPILE_OPTIONS}")
+ endif()
+ if(MPI_${LANG}_COMPILE_DEFINITIONS)
+ foreach(_MPI_DEF IN LISTS MPI_${LANG}_COMPILE_DEFINITIONS)
+ string(APPEND MPI_${LANG}_COMPILE_FLAGS " -D${_MPI_DEF}")
+ endforeach()
+ endif()
+ endif()
+endforeach()
+
+# Bare MPI sans ${LANG} vars are set to CXX then C, depending on what was found.
# This mimics the behavior of the old language-oblivious FindMPI.
-set(_MPI_OLD_VARS FOUND COMPILER INCLUDE_PATH COMPILE_FLAGS LINK_FLAGS LIBRARIES)
+set(_MPI_OLD_VARS COMPILER INCLUDE_PATH COMPILE_FLAGS LINK_FLAGS LIBRARIES)
if (MPI_CXX_FOUND)
foreach (var ${_MPI_OLD_VARS})
set(MPI_${var} ${MPI_CXX_${var}})
@@ -679,28 +1427,26 @@ elseif (MPI_C_FOUND)
foreach (var ${_MPI_OLD_VARS})
set(MPI_${var} ${MPI_C_${var}})
endforeach()
-else()
- # Note that we might still have found Fortran, but you'll need to use MPI_Fortran_FOUND
- set(MPI_FOUND FALSE)
endif()
# Chop MPI_LIBRARIES into the old-style MPI_LIBRARY and MPI_EXTRA_LIBRARY, and set them in cache.
if (MPI_LIBRARIES)
list(GET MPI_LIBRARIES 0 MPI_LIBRARY_WORK)
- set(MPI_LIBRARY ${MPI_LIBRARY_WORK} CACHE FILEPATH "MPI library to link against" FORCE)
+ set(MPI_LIBRARY "${MPI_LIBRARY_WORK}")
+ unset(MPI_LIBRARY_WORK)
else()
- set(MPI_LIBRARY "MPI_LIBRARY-NOTFOUND" CACHE FILEPATH "MPI library to link against" FORCE)
+ set(MPI_LIBRARY "MPI_LIBRARY-NOTFOUND")
endif()
list(LENGTH MPI_LIBRARIES MPI_NUMLIBS)
if (MPI_NUMLIBS GREATER 1)
- set(MPI_EXTRA_LIBRARY_WORK ${MPI_LIBRARIES})
+ set(MPI_EXTRA_LIBRARY_WORK "${MPI_LIBRARIES}")
list(REMOVE_AT MPI_EXTRA_LIBRARY_WORK 0)
- set(MPI_EXTRA_LIBRARY ${MPI_EXTRA_LIBRARY_WORK} CACHE STRING "Extra MPI libraries to link against" FORCE)
+ set(MPI_EXTRA_LIBRARY "${MPI_EXTRA_LIBRARY_WORK}")
+ unset(MPI_EXTRA_LIBRARY_WORK)
else()
- set(MPI_EXTRA_LIBRARY "MPI_EXTRA_LIBRARY-NOTFOUND" CACHE STRING "Extra MPI libraries to link against" FORCE)
+ set(MPI_EXTRA_LIBRARY "MPI_EXTRA_LIBRARY-NOTFOUND")
endif()
-mark_as_advanced(MPI_LIBRARY MPI_EXTRA_LIBRARY)
#=============================================================================
# unset these vars to cleanup namespace
@@ -708,5 +1454,7 @@ unset(_MPI_OLD_VARS)
unset(_MPI_PREFIX_PATH)
unset(_MPI_BASE_DIR)
foreach (lang C CXX Fortran)
- unset(_MPI_${lang}_COMPILER_NAMES)
+ unset(_MPI_${LANG}_COMPILER_NAMES)
endforeach()
+
+cmake_policy(POP)
diff --git a/Modules/FindMPI/fortranparam_mpi.f90.in b/Modules/FindMPI/fortranparam_mpi.f90.in
new file mode 100644
index 000000000..30f912c62
--- /dev/null
+++ b/Modules/FindMPI/fortranparam_mpi.f90.in
@@ -0,0 +1,4 @@
+ program mpi_ver
+ @MPI_Fortran_INCLUDE_LINE@
+ print *, 'INFO:SUBARRAYS[', MPI_SUBARRAYS_SUPPORTED, ']-ASYNCPROT[', MPI_ASYNC_PROTECTS_NONBLOCKING, ']'
+ end program mpi_ver
diff --git a/Modules/FindMPI/libver_mpi.c b/Modules/FindMPI/libver_mpi.c
new file mode 100644
index 000000000..be9d19d43
--- /dev/null
+++ b/Modules/FindMPI/libver_mpi.c
@@ -0,0 +1,19 @@
+#include <mpi.h>
+
+#ifdef __cplusplus
+#include <cstdio>
+#else
+#include <stdio.h>
+#endif
+
+int main(int argc, char* argv[])
+{
+ char mpilibver_str[MPI_MAX_LIBRARY_VERSION_STRING];
+ int mpilibver_len;
+ MPI_Get_library_version(mpilibver_str, &mpilibver_len);
+#ifdef __cplusplus
+ std::puts(mpilibver_str);
+#else
+ puts(mpilibver_str);
+#endif
+}
diff --git a/Modules/FindMPI/libver_mpi.f90.in b/Modules/FindMPI/libver_mpi.f90.in
new file mode 100644
index 000000000..793858716
--- /dev/null
+++ b/Modules/FindMPI/libver_mpi.f90.in
@@ -0,0 +1,7 @@
+ program mpi_ver
+ @MPI_Fortran_INCLUDE_LINE@
+ character(len=MPI_MAX_LIBRARY_VERSION_STRING) :: mpilibver_str
+ integer(kind=MPI_INTEGER_KIND) :: ierror, reslen
+ call MPI_GET_LIBRARY_VERSION(mpilibver_str, reslen, ierror)
+ print *, mpilibver_str
+ end program mpi_ver
diff --git a/Modules/FindMPI/mpiver.f90.in b/Modules/FindMPI/mpiver.f90.in
new file mode 100644
index 000000000..a25452385
--- /dev/null
+++ b/Modules/FindMPI/mpiver.f90.in
@@ -0,0 +1,10 @@
+ program mpi_ver
+ @MPI_Fortran_INCLUDE_LINE@
+ integer(kind=kind(MPI_VERSION)), parameter :: zero = ichar('0')
+ character, dimension(17), parameter :: mpiver_str =&
+ (/ 'I', 'N', 'F', 'O', ':', 'M', 'P', 'I', '-', 'V', 'E', 'R', '[', &
+ char(zero + MPI_VERSION), &
+ '.', &
+ char(zero + MPI_SUBVERSION), ']' /)
+ print *, mpiver_str
+ end program mpi_ver
diff --git a/Modules/FindMPI/test_mpi.c b/Modules/FindMPI/test_mpi.c
new file mode 100644
index 000000000..b8a308a4b
--- /dev/null
+++ b/Modules/FindMPI/test_mpi.c
@@ -0,0 +1,37 @@
+#include <mpi.h>
+
+#ifdef __cplusplus
+#include <cstdio>
+#else
+#include <stdio.h>
+#endif
+
+#if defined(MPI_VERSION) && defined(MPI_SUBVERSION)
+const char mpiver_str[] = { 'I', 'N',
+ 'F', 'O',
+ ':', 'M',
+ 'P', 'I',
+ '-', 'V',
+ 'E', 'R',
+ '[', ('0' + MPI_VERSION),
+ '.', ('0' + MPI_SUBVERSION),
+ ']', '\0' };
+#endif
+
+int main(int argc, char* argv[])
+{
+#if defined(MPI_VERSION) && defined(MPI_SUBVERSION)
+#ifdef __cplusplus
+ std::puts(mpiver_str);
+#else
+ puts(mpiver_str);
+#endif
+#endif
+#ifdef TEST_MPI_MPICXX
+ MPI::MPI_Init(&argc, &argv);
+ MPI::MPI_Finalize();
+#else
+ MPI_Init(&argc, &argv);
+ MPI_Finalize();
+#endif
+}
diff --git a/Modules/FindMPI/test_mpi.f90.in b/Modules/FindMPI/test_mpi.f90.in
new file mode 100644
index 000000000..4d43a04d6
--- /dev/null
+++ b/Modules/FindMPI/test_mpi.f90.in
@@ -0,0 +1,6 @@
+ program hello
+ @MPI_Fortran_INCLUDE_LINE@
+ integer@MPI_Fortran_INTEGER_LINE@ ierror
+ call MPI_INIT(ierror)
+ call MPI_FINALIZE(ierror)
+ end program
diff --git a/Modules/FindMatlab.cmake b/Modules/FindMatlab.cmake
index 80bcda36b..7d4ed6ad2 100644
--- a/Modules/FindMatlab.cmake
+++ b/Modules/FindMatlab.cmake
@@ -225,6 +225,7 @@ if(NOT MATLAB_ADDITIONAL_VERSIONS)
endif()
set(MATLAB_VERSIONS_MAPPING
+ "R2017b=9.3"
"R2017a=9.2"
"R2016b=9.1"
"R2016a=9.0"
@@ -236,7 +237,6 @@ set(MATLAB_VERSIONS_MAPPING
"R2013a=8.1"
"R2012b=8.0"
"R2012a=7.14"
-
"R2011b=7.13"
"R2011a=7.12"
"R2010b=7.11"
@@ -681,12 +681,12 @@ function(matlab_get_version_from_matlab_run matlab_binary_program matlab_list_ve
string(SUBSTRING ${_matlab_version_from_cmd} ${index} -1 substring_ans)
string(
- REGEX MATCHALL "ans[\r\n\t ]*=[\r\n\t ]*([0-9]+(\\.[0-9]+)?)"
+ REGEX MATCHALL "ans[\r\n\t ]*=[\r\n\t ]*'?([0-9]+(\\.[0-9]+)?)"
matlab_versions_regex
${substring_ans})
foreach(match IN LISTS matlab_versions_regex)
string(
- REGEX MATCH "ans[\r\n\t ]*=[\r\n\t ]*(([0-9]+)(\\.([0-9]+))?)"
+ REGEX MATCH "ans[\r\n\t ]*=[\r\n\t ]*'?(([0-9]+)(\\.([0-9]+))?)"
current_match ${match})
list(APPEND matlab_list_of_all_versions_tmp ${CMAKE_MATCH_1})
@@ -721,7 +721,7 @@ endfunction()
# matlab_add_unit_test(
# NAME <name>
# UNITTEST_FILE matlab_file_containing_unittest.m
-# [CUSTOM_MATLAB_COMMAND matlab_command_to_run_as_test]
+# [CUSTOM_TEST_COMMAND matlab_command_to_run_as_test]
# [UNITTEST_PRECOMMAND matlab_command_to_run]
# [TIMEOUT timeout]
# [ADDITIONAL_PATH path1 [path2 ...]]
@@ -737,7 +737,7 @@ endfunction()
# ``UNITTEST_FILE``
# the matlab unittest file. Its path will be automatically
# added to the Matlab path.
-# ``CUSTOM_MATLAB_COMMAND``
+# ``CUSTOM_TEST_COMMAND``
# Matlab script command to run as the test.
# If this is not set, then the following is run:
# ``runtests('matlab_file_name'), exit(max([ans(1,:).Failed]))``
@@ -1134,7 +1134,14 @@ else()
# testing if we are able to extract the needed information from the registry
set(_matlab_versions_from_registry)
- matlab_extract_all_installed_versions_from_registry(CMAKE_CL_64 _matlab_versions_from_registry)
+
+ if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+ set(_matlab_win64 ON)
+ else()
+ set(_matlab_win64 OFF)
+ endif()
+
+ matlab_extract_all_installed_versions_from_registry(_matlab_win64 _matlab_versions_from_registry)
# the returned list is empty, doing the search on all known versions
if(NOT _matlab_versions_from_registry)
diff --git a/Modules/FindOpenACC.cmake b/Modules/FindOpenACC.cmake
new file mode 100644
index 000000000..dc8321daa
--- /dev/null
+++ b/Modules/FindOpenACC.cmake
@@ -0,0 +1,257 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#[=======================================================================[.rst:
+FindOpenACC
+-----------
+
+Detect OpenACC support by the compiler.
+
+This module can be used to detect OpenACC support in a compiler.
+If the compiler supports OpenACC, the flags required to compile with
+OpenACC support are returned in variables for the different languages.
+Currently, only PGI, GNU and Cray compilers are supported.
+
+Variables
+^^^^^^^^^
+
+This module will set the following variables per language in your
+project, where ``<lang>`` is one of C, CXX, or Fortran:
+
+``OpenACC_<lang>_FOUND``
+ Variable indicating if OpenACC support for ``<lang>`` was detected.
+``OpenACC_<lang>_FLAGS``
+ OpenACC compiler flags for ``<lang>``, separated by spaces.
+
+The module will also try to provide the OpenACC version variables:
+
+``OpenACC_<lang>_SPEC_DATE``
+ Date of the OpenACC specification implemented by the ``<lang>`` compiler.
+``OpenACC_<lang>_VERSION_MAJOR``
+ Major version of OpenACC implemented by the ``<lang>`` compiler.
+``OpenACC_<lang>_VERSION_MINOR``
+ Minor version of OpenACC implemented by the ``<lang>`` compiler.
+``OpenACC_<lang>_VERSION``
+ OpenACC version implemented by the ``<lang>`` compiler.
+
+The specification date is formatted as given in the OpenACC standard:
+``yyyymm`` where ``yyyy`` and ``mm`` represents the year and month of
+the OpenACC specification implemented by the ``<lang>`` compiler.
+
+Input Variables
+^^^^^^^^^^^^^^^
+
+``OpenACC_ACCEL_TARGET=<target>``
+If set, will the correct target accelerator flag set to the <target> will
+be returned with OpenACC_<lang>_FLAGS.
+#]=======================================================================]
+
+set(OpenACC_C_CXX_TEST_SOURCE
+"
+int main(){
+#ifdef _OPENACC
+ return 0;
+#else
+ breaks_on_purpose
+#endif
+}
+"
+)
+set(OpenACC_Fortran_TEST_SOURCE
+"
+program test
+#ifdef _OPENACC
+ return 0;
+#else
+ breaks_on_purpose
+#endif
+endprogram test
+"
+)
+set(OpenACC_C_CXX_CHECK_VERSION_SOURCE
+"
+#include <stdio.h>
+const char accver_str[] = { 'I', 'N', 'F', 'O', ':', 'O', 'p', 'e', 'n', 'A',
+ 'C', 'C', '-', 'd', 'a', 't', 'e', '[',
+ ('0' + ((_OPENACC/100000)%10)),
+ ('0' + ((_OPENACC/10000)%10)),
+ ('0' + ((_OPENACC/1000)%10)),
+ ('0' + ((_OPENACC/100)%10)),
+ ('0' + ((_OPENACC/10)%10)),
+ ('0' + ((_OPENACC/1)%10)),
+ ']', '\\0' };
+int main()
+{
+ puts(accver_str);
+ return 0;
+}
+")
+set(OpenACC_Fortran_CHECK_VERSION_SOURCE
+"
+ program acc_ver
+ implicit none
+ integer, parameter :: zero = ichar('0')
+ character, dimension(25), parameter :: accver_str =&
+ (/ 'I', 'N', 'F', 'O', ':', 'O', 'p', 'e', 'n', 'A', 'C', 'C', '-',&
+ 'd', 'a', 't', 'e', '[',&
+ char(zero + mod(_OPENACC/100000, 10)),&
+ char(zero + mod(_OPENACC/10000, 10)),&
+ char(zero + mod(_OPENACC/1000, 10)),&
+ char(zero + mod(_OPENACC/100, 10)),&
+ char(zero + mod(_OPENACC/10, 10)),&
+ char(zero + mod(_OPENACC/1, 10)), ']' /)
+ print *, accver_str
+ end program acc_ver
+"
+)
+
+
+function(_OPENACC_WRITE_SOURCE_FILE LANG SRC_FILE_CONTENT_VAR SRC_FILE_NAME SRC_FILE_FULLPATH)
+ set(WORK_DIR ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindOpenACC)
+ if("${LANG}" STREQUAL "C")
+ set(SRC_FILE "${WORK_DIR}/${SRC_FILE_NAME}.c")
+ file(WRITE "${SRC_FILE}" "${OpenACC_C_CXX_${SRC_FILE_CONTENT_VAR}}")
+ elseif("${LANG}" STREQUAL "CXX")
+ set(SRC_FILE "${WORK_DIR}/${SRC_FILE_NAME}.cpp")
+ file(WRITE "${SRC_FILE}" "${OpenACC_C_CXX_${SRC_FILE_CONTENT_VAR}}")
+ elseif("${LANG}" STREQUAL "Fortran")
+ set(SRC_FILE "${WORK_DIR}/${SRC_FILE_NAME}.F90")
+ file(WRITE "${SRC_FILE}_in" "${OpenACC_Fortran_${SRC_FILE_CONTENT_VAR}}")
+ configure_file("${SRC_FILE}_in" "${SRC_FILE}" @ONLY)
+ endif()
+ set(${SRC_FILE_FULLPATH} "${SRC_FILE}" PARENT_SCOPE)
+endfunction()
+
+
+function(_OPENACC_GET_FLAGS_CANDIDATE LANG FLAG_VAR)
+ set(ACC_FLAG_PGI "-acc")
+ set(ACC_FLAG_GNU "-fopenacc")
+ set(ACC_FLAG_Cray "-h acc")
+
+ if(DEFINED ACC_FLAG_${CMAKE_${LANG}_COMPILER_ID})
+ set("${FLAG_VAR}" "${ACC_FLAG_${CMAKE_${LANG}_COMPILER_ID}}" PARENT_SCOPE)
+ else()
+ # Fall back to a few common flags.
+ set("${FLAG_VAR}" ${ACC_FLAG_GNU} ${ACC_FLAG_PGI})
+ endif()
+
+endfunction()
+
+
+function(_OPENACC_GET_ACCEL_TARGET_FLAG LANG TARGET FLAG_VAR)
+ # Find target accelerator flags.
+ set(ACC_TARGET_FLAG_PGI "-ta")
+ if(DEFINED ACC_TARGET_FLAG_${CMAKE_${LANG}_COMPILER_ID})
+ set("${FLAG_VAR}" "${ACC_TARGET_FLAG_${CMAKE_${LANG}_COMPILER_ID}}=${TARGET}" PARENT_SCOPE)
+ endif()
+endfunction()
+
+
+function(_OPENACC_GET_VERBOSE_FLAG LANG FLAG_VAR)
+ # Find compiler's verbose flag for OpenACC.
+ set(ACC_VERBOSE_FLAG_PGI "-Minfo=accel")
+ if(DEFINED ACC_VERBOSE_FLAG_${CMAKE_${LANG}_COMPILER_ID})
+ set("${FLAG_VAR}" "${ACC_VERBOSE_FLAG_${CMAKE_${LANG}_COMPILER_ID}}" PARENT_SCOPE)
+ endif()
+endfunction()
+
+
+function(_OPENACC_GET_FLAGS LANG FLAG_VAR)
+ set(FLAG_CANDIDATES "")
+ _OPENACC_GET_FLAGS_CANDIDATE("${LANG}" FLAG_CANDIDATES)
+ _OPENACC_WRITE_SOURCE_FILE("${LANG}" "TEST_SOURCE" OpenACCTryFlag _OPENACC_TEST_SRC)
+
+ foreach(FLAG IN LISTS FLAG_CANDIDATES)
+ try_compile(OpenACC_FLAG_TEST_RESULT ${CMAKE_BINARY_DIR} ${_OPENACC_TEST_SRC}
+ CMAKE_FLAGS "-DCOMPILE_DEFINITIONS:STRING=${FLAG}"
+ OUTPUT_VARIABLE OpenACC_TRY_COMPILE_OUTPUT
+ )
+ if(OpenACC_FLAG_TEST_RESULT)
+ set("${FLAG_VAR}" "${FLAG}")
+ if(DEFINED OpenACC_ACCEL_TARGET)
+ _OPENACC_GET_ACCEL_TARGET_FLAG("${LANG}" "${OpenACC_ACCEL_TARGET}" TARGET_FLAG)
+ string(APPEND "${FLAG_VAR}" " ${TARGET_FLAG}")
+ endif()
+
+ if(CMAKE_VERBOSE_MAKEFILE)
+ # -Minfo=accel prints out OpenACC's messages on optimizations.
+ _OPENACC_GET_VERBOSE_FLAG("${LANG}" OpenACC_VERBOSE_FLAG)
+ string(APPEND "${FLAG_VAR}" " ${OpenACC_VERBOSE_FLAG}")
+ endif()
+ set("${FLAG_VAR}" "${${FLAG_VAR}}" PARENT_SCOPE)
+ break()
+ endif()
+ endforeach()
+
+endfunction()
+
+
+function(_OPENACC_GET_SPEC_DATE LANG SPEC_DATE)
+ _OPENACC_WRITE_SOURCE_FILE("${LANG}" "CHECK_VERSION_SOURCE" OpenACCCheckVersion _OPENACC_TEST_SRC)
+
+ set(BIN_FILE "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindOpenACC/accver_${LANG}.bin")
+ try_compile(OpenACC_SPECTEST_${LANG} "${CMAKE_BINARY_DIR}" "${_OPENACC_TEST_SRC}"
+ CMAKE_FLAGS "-DCOMPILE_DEFINITIONS:STRING=${OpenACC_${LANG}_FLAGS}"
+ COPY_FILE ${BIN_FILE}
+ OUTPUT_VARIABLE OUTPUT)
+
+ if(${OpenACC_SPECTEST_${LANG}})
+ file(STRINGS ${BIN_FILE} specstr LIMIT_COUNT 1 REGEX "INFO:OpenACC-date")
+ set(regex_spec_date ".*INFO:OpenACC-date\\[0*([^]]*)\\].*")
+ if("${specstr}" MATCHES "${regex_spec_date}")
+ set(${SPEC_DATE} "${CMAKE_MATCH_1}" PARENT_SCOPE)
+ endif()
+ endif()
+endfunction()
+
+
+macro(_OPENACC_SET_VERSION_BY_SPEC_DATE LANG)
+ set(OpenACC_SPEC_DATE_MAP
+ # Combined versions, 2.5 onwards
+ "201510=2.5"
+ # 2013 08 is the corrected version.
+ "201308=2.0"
+ "201306=2.0"
+ "201111=1.0"
+ )
+
+ string(REGEX MATCHALL "${OpenACC_${LANG}_SPEC_DATE}=([0-9]+)\\.([0-9]+)" _version_match "${OpenACC_SPEC_DATE_MAP}")
+ if(NOT _version_match STREQUAL "")
+ set(OpenACC_${LANG}_VERSION_MAJOR ${CMAKE_MATCH_1})
+ set(OpenACC_${LANG}_VERSION_MINOR ${CMAKE_MATCH_2})
+ set(OpenACC_${LANG}_VERSION "${OpenACC_${LANG}_VERSION_MAJOR}.${OpenACC_${LANG}_VERSION_MINOR}")
+ else()
+ unset(OpenACC_${LANG}_VERSION_MAJOR)
+ unset(OpenACC_${LANG}_VERSION_MINOR)
+ unset(OpenACC_${LANG}_VERSION)
+ endif()
+ unset(_version_match)
+ unset(OpenACC_SPEC_DATE_MAP)
+endmacro()
+
+
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
+foreach (LANG IN ITEMS C CXX Fortran)
+ if(CMAKE_${LANG}_COMPILER_LOADED)
+ set(OpenACC_${LANG}_FIND_QUIETLY ${OpenACC_FIND_QUIETLY})
+ set(OpenACC_${LANG}_FIND_REQUIRED ${OpenACC_FIND_REQUIRED})
+ set(OpenACC_${LANG}_FIND_VERSION ${OpenACC_FIND_VERSION})
+ set(OpenACC_${LANG}_FIND_VERSION_EXACT ${OpenACC_FIND_VERSION_EXACT})
+
+ if(NOT DEFINED OpenACC_${LANG}_FLAGS)
+ _OPENACC_GET_FLAGS("${LANG}" OpenACC_${LANG}_FLAGS)
+ endif()
+ _OPENACC_GET_SPEC_DATE("${LANG}" OpenACC_${LANG}_SPEC_DATE)
+ _OPENACC_SET_VERSION_BY_SPEC_DATE("${LANG}")
+
+ find_package_handle_standard_args(OpenACC_${LANG}
+ REQUIRED_VARS OpenACC_${LANG}_FLAGS
+ VERSION_VAR OpenACC_${LANG}_VERSION
+ )
+ endif()
+endforeach()
+
+unset(OpenACC_C_CXX_TEST_SOURCE)
+unset(OpenACC_Fortran_TEST_SOURCE)
+unset(OpenACC_C_CXX_CHECK_VERSION_SOURCE)
+unset(OpenACC_Fortran_CHECK_VERSION_SOURCE)
diff --git a/Modules/FindOpenCL.cmake b/Modules/FindOpenCL.cmake
index b8a7d822f..0db2dd280 100644
--- a/Modules/FindOpenCL.cmake
+++ b/Modules/FindOpenCL.cmake
@@ -37,7 +37,7 @@ function(_FIND_OPENCL_VERSION)
set(CMAKE_REQUIRED_QUIET ${OpenCL_FIND_QUIETLY})
CMAKE_PUSH_CHECK_STATE()
- foreach(VERSION "2_0" "1_2" "1_1" "1_0")
+ foreach(VERSION "2_2" "2_1" "2_0" "1_2" "1_1" "1_0")
set(CMAKE_REQUIRED_INCLUDES "${OpenCL_INCLUDE_DIR}")
if(APPLE)
diff --git a/Modules/FindOpenGL.cmake b/Modules/FindOpenGL.cmake
index af83fb735..906349273 100644
--- a/Modules/FindOpenGL.cmake
+++ b/Modules/FindOpenGL.cmake
@@ -7,15 +7,28 @@
#
# FindModule for OpenGL and GLU.
#
+# Optional COMPONENTS
+# ^^^^^^^^^^^^^^^^^^^
+#
+# This module respects several optional COMPONENTS: ``EGL``, ``GLX``, and
+# ``OpenGL``. There are corresponding import targets for each of these flags.
+#
# IMPORTED Targets
# ^^^^^^^^^^^^^^^^
#
# This module defines the :prop_tgt:`IMPORTED` targets:
#
# ``OpenGL::GL``
-# Defined if the system has OpenGL.
+# Defined to the platform-specific OpenGL libraries if the system has OpenGL.
+# ``OpenGL::OpenGL``
+# Defined to libOpenGL if the system is GLVND-based.
+# ``OpenGL::GL``
# ``OpenGL::GLU``
# Defined if the system has GLU.
+# ``OpenGL::GLX``
+# Defined if the system has GLX.
+# ``OpenGL::EGL``
+# Defined if the system has EGL.
#
# Result Variables
# ^^^^^^^^^^^^^^^^
@@ -23,40 +36,103 @@
# This module sets the following variables:
#
# ``OPENGL_FOUND``
-# True, if the system has OpenGL.
+# True, if the system has OpenGL and all components are found.
# ``OPENGL_XMESA_FOUND``
# True, if the system has XMESA.
# ``OPENGL_GLU_FOUND``
# True, if the system has GLU.
+# ``OpenGL_OpenGL_FOUND``
+# True, if the system has an OpenGL library.
+# ``OpenGL_GLX_FOUND``
+# True, if the system has GLX.
+# ``OpenGL_EGL_FOUND``
+# True, if the system has EGL.
# ``OPENGL_INCLUDE_DIR``
# Path to the OpenGL include directory.
+# ``OPENGL_EGL_INCLUDE_DIRS``
+# Path to the EGL include directory.
# ``OPENGL_LIBRARIES``
-# Paths to the OpenGL and GLU libraries.
+# Paths to the OpenGL library, windowing system libraries, and GLU libraries.
+# On Linux, this assumes GLX and is never correct for EGL-based targets.
+# Clients are encouraged to use the ``OpenGL::*`` import targets instead.
#
-# If you want to use just GL you can use these values:
+# Cache variables
+# ^^^^^^^^^^^^^^^
#
-# ``OPENGL_gl_LIBRARY``
-# Path to the OpenGL library.
+# The following cache variables may also be set:
+#
+# ``OPENGL_egl_LIBRARY``
+# Path to the EGL library.
# ``OPENGL_glu_LIBRARY``
# Path to the GLU library.
+# ``OPENGL_glx_LIBRARY``
+# Path to the GLVND 'GLX' library.
+# ``OPENGL_opengl_LIBRARY``
+# Path to the GLVND 'OpenGL' library
+# ``OPENGL_gl_LIBRARY``
+# Path to the OpenGL library. New code should prefer the ``OpenGL::*`` import
+# targets.
+#
+# Linux-specific
+# ^^^^^^^^^^^^^^
+#
+# Some Linux systems utilize GLVND as a new ABI for OpenGL. GLVND separates
+# context libraries from OpenGL itself; OpenGL lives in "libOpenGL", and
+# contexts are defined in "libGLX" or "libEGL". GLVND is currently the only way
+# to get OpenGL 3+ functionality via EGL in a manner portable across vendors.
+# Projects may use GLVND explicitly with target ``OpenGL::OpenGL`` and either
+# ``OpenGL::GLX`` or ``OpenGL::EGL``.
+#
+# Projects may use the ``OpenGL::GL`` target (or ``OPENGL_LIBRARIES`` variable)
+# to use legacy GL interfaces. These will use the legacy GL library located
+# by ``OPENGL_gl_LIBRARY``, if available. If ``OPENGL_gl_LIBRARY`` is empty or
+# not found and GLVND is available, the ``OpenGL::GL`` target will use GLVND
+# ``OpenGL::OpenGL`` and ``OpenGL::GLX`` (and the ``OPENGL_LIBRARIES``
+# variable will use the corresponding libraries). Thus, for non-EGL-based
+# Linux targets, the ``OpenGL::GL`` target is most portable.
+#
+# A ``OpenGL_GL_PREFERENCE`` variable may be set to specify the preferred way
+# to provide legacy GL interfaces in case multiple choices are available.
+# The value may be one of:
+#
+# ``GLVND``
+# If the GLVND OpenGL and GLX libraries are available, prefer them.
+# This forces ``OPENGL_gl_LIBRARY`` to be empty.
+# This is the default if components were requested (since components
+# correspond to GLVND libraries).
+#
+# ``LEGACY``
+# Prefer to use the legacy libGL library, if available.
+# This is the default if no components were requested.
+#
+# For EGL targets the client must rely on GLVND support on the user's system.
+# Linking should use the ``OpenGL::OpenGL OpenGL::EGL`` targets. Using GLES*
+# libraries is theoretically possible in place of ``OpenGL::OpenGL``, but this
+# module does not currently support that; contributions welcome.
#
-# OSX Specific
-# ^^^^^^^^^^^^
+# ``OPENGL_egl_LIBRARY`` and ``OPENGL_EGL_INCLUDE_DIRS`` are defined in the case of
+# GLVND. For non-GLVND Linux and other systems these are left undefined.
#
-# On OSX default to using the framework version of OpenGL. People will
-# have to change the cache values of OPENGL_glu_LIBRARY and
+# macOS-Specific
+# ^^^^^^^^^^^^^^
+#
+# On OSX FindOpenGL defaults to using the framework version of OpenGL. People
+# will have to change the cache values of OPENGL_glu_LIBRARY and
# OPENGL_gl_LIBRARY to use OpenGL with X11 on OSX.
-
set(_OpenGL_REQUIRED_VARS OPENGL_gl_LIBRARY)
-if (CYGWIN)
+# Provide OPENGL_USE_<C> variables for each component.
+foreach(component ${OpenGL_FIND_COMPONENTS})
+ string(TOUPPER ${component} _COMPONENT)
+ set(OPENGL_USE_${_COMPONENT} 1)
+endforeach()
+if (CYGWIN)
find_path(OPENGL_INCLUDE_DIR GL/gl.h )
list(APPEND _OpenGL_REQUIRED_VARS OPENGL_INCLUDE_DIR)
find_library(OPENGL_gl_LIBRARY opengl32 )
-
find_library(OPENGL_glu_LIBRARY glu32 )
elseif (WIN32)
@@ -70,7 +146,6 @@ elseif (WIN32)
endif()
elseif (APPLE)
-
# The OpenGL.framework provides both gl and glu
find_library(OPENGL_gl_LIBRARY OpenGL DOC "OpenGL library for OS X")
find_library(OPENGL_glu_LIBRARY OpenGL DOC
@@ -104,29 +179,142 @@ else()
# fail since the compiler finds the Mesa headers but NVidia's library.
# Make sure the NVIDIA directory comes BEFORE the others.
# - Atanas Georgiev <atanas@cs.columbia.edu>
-
find_path(OPENGL_INCLUDE_DIR GL/gl.h
/usr/share/doc/NVIDIA_GLX-1.0/include
/usr/openwin/share/include
/opt/graphics/OpenGL/include /usr/X11R6/include
${_OPENGL_INCLUDE_PATH}
)
- list(APPEND _OpenGL_REQUIRED_VARS OPENGL_INCLUDE_DIR)
-
+ find_path(OPENGL_GLX_INCLUDE_DIR GL/glx.h ${_OPENGL_INCLUDE_PATH})
+ find_path(OPENGL_EGL_INCLUDE_DIR EGL/egl.h ${_OPENGL_INCLUDE_PATH})
find_path(OPENGL_xmesa_INCLUDE_DIR GL/xmesa.h
/usr/share/doc/NVIDIA_GLX-1.0/include
/usr/openwin/share/include
/opt/graphics/OpenGL/include /usr/X11R6/include
)
- find_library(OPENGL_gl_LIBRARY
- NAMES GL MesaGL
- PATHS /opt/graphics/OpenGL/lib
+ # Search for the GLVND libraries. We do this regardless of COMPONENTS; we'll
+ # take into account the COMPONENTS logic later.
+ find_library(OPENGL_opengl_LIBRARY
+ NAMES OpenGL
+ PATHS /usr/X11R6/lib
+ ${_OPENGL_LIB_PATH}
+ )
+
+ find_library(OPENGL_glx_LIBRARY
+ NAMES GLX
+ PATHS /usr/X11R6/lib
+ ${_OPENGL_LIB_PATH}
+ )
+
+ find_library(OPENGL_egl_LIBRARY
+ NAMES EGL
+ PATHS ${_OPENGL_LIB_PATH}
+ )
+
+ find_library(OPENGL_glu_LIBRARY
+ NAMES GLU MesaGLU
+ PATHS ${OPENGL_gl_LIBRARY}
+ /opt/graphics/OpenGL/lib
/usr/openwin/lib
/usr/shlib /usr/X11R6/lib
- ${_OPENGL_LIB_PATH}
)
+ if(NOT DEFINED OpenGL_GL_PREFERENCE)
+ set(OpenGL_GL_PREFERENCE "")
+ endif()
+ if(NOT OpenGL_GL_PREFERENCE STREQUAL "")
+ # A preference has been explicitly specified.
+ if(NOT OpenGL_GL_PREFERENCE MATCHES "^(GLVND|LEGACY)$")
+ message(FATAL_ERROR
+ "OpenGL_GL_PREFERENCE value '${OpenGL_GL_PREFERENCE}' not recognized. "
+ "Allowed values are 'GLVND' and 'LEGACY'."
+ )
+ endif()
+ elseif(OpenGL_FIND_COMPONENTS)
+ # No preference was explicitly specified, but the caller did request
+ # at least one GLVND component. Prefer GLVND for legacy GL.
+ set(OpenGL_GL_PREFERENCE "GLVND")
+ else()
+ # No preference was explicitly specified and no GLVND components were
+ # requested. Prefer libGL for legacy GL.
+ set(OpenGL_GL_PREFERENCE "LEGACY")
+ endif()
+
+ if("x${OpenGL_GL_PREFERENCE}x" STREQUAL "xGLVNDx" AND OPENGL_opengl_LIBRARY AND OPENGL_glx_LIBRARY)
+ # We can provide legacy GL using GLVND libraries.
+ # Do not use any legacy GL library.
+ set(OPENGL_gl_LIBRARY "")
+ else()
+ # We cannot provide legacy GL using GLVND libraries.
+ # Search for the legacy GL library.
+ find_library(OPENGL_gl_LIBRARY
+ NAMES GL MesaGL
+ PATHS /opt/graphics/OpenGL/lib
+ /usr/openwin/lib
+ /usr/shlib /usr/X11R6/lib
+ ${_OPENGL_LIB_PATH}
+ )
+ endif()
+
+ # FPHSA cannot handle "this OR that is required", so we conditionally set what
+ # it must look for. First clear any previous config we might have done:
+ set(_OpenGL_REQUIRED_VARS)
+
+ # now we append the libraries as appropriate. The complicated logic
+ # basically comes down to "use libOpenGL when we can, and add in specific
+ # context mechanisms when requested, or we need them to preserve the previous
+ # default where glx is always available."
+ if((NOT OPENGL_USE_EGL AND
+ NOT OPENGL_opengl_LIBRARY AND
+ OPENGL_glx_LIBRARY AND
+ NOT OPENGL_gl_LIBRARY) OR
+ (NOT OPENGL_USE_EGL AND
+ NOT OPENGL_glx_LIBRARY AND
+ NOT OPENGL_gl_LIBRARY) OR
+ (NOT OPENGL_USE_EGL AND
+ OPENGL_opengl_LIBRARY AND
+ OPENGL_glx_LIBRARY) OR
+ ( OPENGL_USE_EGL))
+ list(APPEND _OpenGL_REQUIRED_VARS OPENGL_opengl_LIBRARY)
+ endif()
+
+ # GLVND GLX library. Preferred when available.
+ if((NOT OPENGL_USE_OPENGL AND
+ NOT OPENGL_USE_GLX AND
+ NOT OPENGL_USE_EGL AND
+ NOT OPENGL_glx_LIBRARY AND
+ NOT OPENGL_gl_LIBRARY) OR
+ ( OPENGL_USE_GLX AND
+ NOT OPENGL_USE_EGL AND
+ NOT OPENGL_glx_LIBRARY AND
+ NOT OPENGL_gl_LIBRARY) OR
+ (NOT OPENGL_USE_EGL AND
+ OPENGL_opengl_LIBRARY AND
+ OPENGL_glx_LIBRARY) OR
+ (OPENGL_USE_GLX AND OPENGL_USE_EGL))
+ list(APPEND _OpenGL_REQUIRED_VARS OPENGL_glx_LIBRARY)
+ endif()
+
+ # GLVND EGL library.
+ if(OPENGL_USE_EGL)
+ list(APPEND _OpenGL_REQUIRED_VARS OPENGL_egl_LIBRARY)
+ endif()
+
+ # Old-style "libGL" library: used as a fallback when GLVND isn't available.
+ if((NOT OPENGL_USE_EGL AND
+ NOT OPENGL_opengl_LIBRARY AND
+ OPENGL_glx_LIBRARY AND
+ OPENGL_gl_LIBRARY) OR
+ (NOT OPENGL_USE_EGL AND
+ NOT OPENGL_glx_LIBRARY AND
+ OPENGL_gl_LIBRARY))
+ list(APPEND _OpenGL_REQUIRED_VARS OPENGL_gl_LIBRARY)
+ endif()
+
+ # We always need the 'gl.h' include dir.
+ list(APPEND _OpenGL_REQUIRED_VARS OPENGL_INCLUDE_DIR)
+
unset(_OPENGL_INCLUDE_PATH)
unset(_OPENGL_LIB_PATH)
@@ -137,42 +325,89 @@ else()
/usr/openwin/lib
/usr/shlib /usr/X11R6/lib
)
-
endif ()
-if(OPENGL_gl_LIBRARY)
+if(OPENGL_xmesa_INCLUDE_DIR)
+ set( OPENGL_XMESA_FOUND "YES" )
+else()
+ set( OPENGL_XMESA_FOUND "NO" )
+endif()
- if(OPENGL_xmesa_INCLUDE_DIR)
- set( OPENGL_XMESA_FOUND "YES" )
- else()
- set( OPENGL_XMESA_FOUND "NO" )
- endif()
+if(OPENGL_glu_LIBRARY)
+ set( OPENGL_GLU_FOUND "YES" )
+else()
+ set( OPENGL_GLU_FOUND "NO" )
+endif()
- set( OPENGL_LIBRARIES ${OPENGL_gl_LIBRARY} ${OPENGL_LIBRARIES})
- if(OPENGL_glu_LIBRARY)
- set( OPENGL_GLU_FOUND "YES" )
- if(NOT "${OPENGL_glu_LIBRARY}" STREQUAL "${OPENGL_gl_LIBRARY}")
- set( OPENGL_LIBRARIES ${OPENGL_glu_LIBRARY} ${OPENGL_LIBRARIES} )
- endif()
- else()
- set( OPENGL_GLU_FOUND "NO" )
- endif()
+# OpenGL_OpenGL_FOUND is a bit unique in that it is okay if /either/ libOpenGL
+# or libGL is found.
+# Using libGL with libEGL is never okay, though; we handle that case later.
+if(NOT OPENGL_opengl_LIBRARY AND NOT OPENGL_gl_LIBRARY)
+ set(OpenGL_OpenGL_FOUND FALSE)
+else()
+ set(OpenGL_OpenGL_FOUND TRUE)
+endif()
- # This deprecated setting is for backward compatibility with CMake1.4
- set (OPENGL_LIBRARY ${OPENGL_LIBRARIES})
+if(OPENGL_glx_LIBRARY AND OPENGL_GLX_INCLUDE_DIR)
+ set(OpenGL_GLX_FOUND TRUE)
+else()
+ set(OpenGL_GLX_FOUND FALSE)
+endif()
+if(OPENGL_egl_LIBRARY AND OPENGL_EGL_INCLUDE_DIR)
+ set(OpenGL_EGL_FOUND TRUE)
+else()
+ set(OpenGL_EGL_FOUND FALSE)
endif()
-# This deprecated setting is for backward compatibility with CMake1.4
-set(OPENGL_INCLUDE_PATH ${OPENGL_INCLUDE_DIR})
+# User-visible names should be plural.
+if(OPENGL_EGL_INCLUDE_DIR)
+ set(OPENGL_EGL_INCLUDE_DIRS ${OPENGL_EGL_INCLUDE_DIR})
+endif()
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
-FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenGL REQUIRED_VARS ${_OpenGL_REQUIRED_VARS})
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(OpenGL REQUIRED_VARS ${_OpenGL_REQUIRED_VARS}
+ HANDLE_COMPONENTS)
unset(_OpenGL_REQUIRED_VARS)
# OpenGL:: targets
if(OPENGL_FOUND)
- if(NOT TARGET OpenGL::GL)
+ # ::OpenGL is a GLVND library, and thus Linux-only: we don't bother checking
+ # for a framework version of this library.
+ if(OPENGL_opengl_LIBRARY AND NOT TARGET OpenGL::OpenGL)
+ if(IS_ABSOLUTE "${OPENGL_opengl_LIBRARY}")
+ add_library(OpenGL::OpenGL UNKNOWN IMPORTED)
+ set_target_properties(OpenGL::OpenGL PROPERTIES IMPORTED_LOCATION
+ "${OPENGL_opengl_LIBRARY}")
+ else()
+ add_library(OpenGL::OpenGL INTERFACE IMPORTED)
+ set_target_properties(OpenGL::OpenGL PROPERTIES IMPORTED_LIBNAME
+ "${OPENGL_opengl_LIBRARY}")
+ endif()
+ set_target_properties(OpenGL::OpenGL PROPERTIES INTERFACE_INCLUDE_DIRECTORIES
+ "${OPENGL_INCLUDE_DIR}")
+ endif()
+
+ # ::GLX is a GLVND library, and thus Linux-only: we don't bother checking
+ # for a framework version of this library.
+ if(OpenGL_GLX_FOUND AND NOT TARGET OpenGL::GLX)
+ if(IS_ABSOLUTE "${OPENGL_glx_LIBRARY}")
+ add_library(OpenGL::GLX UNKNOWN IMPORTED)
+ set_target_properties(OpenGL::GLX PROPERTIES IMPORTED_LOCATION
+ "${OPENGL_glx_LIBRARY}")
+ else()
+ add_library(OpenGL::GLX INTERFACE IMPORTED)
+ set_target_properties(OpenGL::GLX PROPERTIES IMPORTED_LIBNAME
+ "${OPENGL_glx_LIBRARY}")
+ endif()
+ set_target_properties(OpenGL::GLX PROPERTIES INTERFACE_LINK_LIBRARIES
+ OpenGL::OpenGL)
+ set_target_properties(OpenGL::GLX PROPERTIES INTERFACE_INCLUDE_DIRECTORIES
+ "${OPENGL_GLX_INCLUDE_DIR}")
+ endif()
+
+ if(OPENGL_gl_LIBRARY AND NOT TARGET OpenGL::GL)
+ # A legacy GL library is available, so use it for the legacy GL target.
if(IS_ABSOLUTE "${OPENGL_gl_LIBRARY}")
add_library(OpenGL::GL UNKNOWN IMPORTED)
if(OPENGL_gl_LIBRARY MATCHES "/([^/]+)\\.framework$")
@@ -193,6 +428,38 @@ if(OPENGL_FOUND)
endif()
set_target_properties(OpenGL::GL PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES "${OPENGL_INCLUDE_DIR}")
+ elseif(NOT TARGET OpenGL::GL AND TARGET OpenGL::OpenGL AND TARGET OpenGL::GLX)
+ # A legacy GL library is not available, but we can provide the legacy GL
+ # target using GLVND OpenGL+GLX.
+ add_library(OpenGL::GL INTERFACE IMPORTED)
+ set_target_properties(OpenGL::GL PROPERTIES INTERFACE_LINK_LIBRARIES
+ OpenGL::OpenGL)
+ set_property(TARGET OpenGL::GL APPEND PROPERTY INTERFACE_LINK_LIBRARIES
+ OpenGL::GLX)
+ set_target_properties(OpenGL::GL PROPERTIES INTERFACE_INCLUDE_DIRECTORIES
+ "${OPENGL_INCLUDE_DIR}")
+ endif()
+
+ # ::EGL is a GLVND library, and thus Linux-only: we don't bother checking
+ # for a framework version of this library.
+ # Note we test for OpenGL::OpenGL as a target. When this module is updated to
+ # support GLES, we would additionally want to check for the hypothetical GLES
+ # target and enable EGL if either ::GLES or ::OpenGL is created.
+ if(TARGET OpenGL::OpenGL AND OpenGL_EGL_FOUND AND NOT TARGET OpenGL::EGL)
+ if(IS_ABSOLUTE "${OPENGL_egl_LIBRARY}")
+ add_library(OpenGL::EGL UNKNOWN IMPORTED)
+ set_target_properties(OpenGL::EGL PROPERTIES IMPORTED_LOCATION
+ "${OPENGL_egl_LIBRARY}")
+ else()
+ add_library(OpenGL::EGL INTERFACE IMPORTED)
+ set_target_properties(OpenGL::EGL PROPERTIES IMPORTED_LIBNAME
+ "${OPENGL_egl_LIBRARY}")
+ endif()
+ set_target_properties(OpenGL::EGL PROPERTIES INTERFACE_LINK_LIBRARIES
+ OpenGL::OpenGL)
+ # Note that EGL's include directory is different from OpenGL/GLX's!
+ set_target_properties(OpenGL::EGL PROPERTIES INTERFACE_INCLUDE_DIRECTORIES
+ "${OPENGL_EGL_INCLUDE_DIR}")
endif()
if(OPENGL_GLU_FOUND AND NOT TARGET OpenGL::GLU)
@@ -217,11 +484,34 @@ if(OPENGL_FOUND)
set_target_properties(OpenGL::GLU PROPERTIES
INTERFACE_LINK_LIBRARIES OpenGL::GL)
endif()
+
+ # OPENGL_LIBRARIES mirrors OpenGL::GL's logic ...
+ if(OPENGL_gl_LIBRARY)
+ set(OPENGL_LIBRARIES ${OPENGL_gl_LIBRARY})
+ elseif(TARGET OpenGL::OpenGL AND TARGET OpenGL::GLX)
+ set(OPENGL_LIBRARIES ${OPENGL_opengl_LIBRARY} ${OPENGL_glx_LIBRARY})
+ else()
+ set(OPENGL_LIBRARIES "")
+ endif()
+ # ... and also includes GLU, if available.
+ if(TARGET OpenGL::GLU)
+ list(APPEND OPENGL_LIBRARIES ${OPENGL_glu_LIBRARY})
+ endif()
endif()
+# This deprecated setting is for backward compatibility with CMake1.4
+set(OPENGL_LIBRARY ${OPENGL_LIBRARIES})
+# This deprecated setting is for backward compatibility with CMake1.4
+set(OPENGL_INCLUDE_PATH ${OPENGL_INCLUDE_DIR})
+
mark_as_advanced(
OPENGL_INCLUDE_DIR
OPENGL_xmesa_INCLUDE_DIR
+ OPENGL_egl_LIBRARY
OPENGL_glu_LIBRARY
+ OPENGL_glx_LIBRARY
OPENGL_gl_LIBRARY
+ OPENGL_opengl_LIBRARY
+ OPENGL_EGL_INCLUDE_DIR
+ OPENGL_GLX_INCLUDE_DIR
)
diff --git a/Modules/FindOpenMP.cmake b/Modules/FindOpenMP.cmake
index ee74a1afe..489476b19 100644
--- a/Modules/FindOpenMP.cmake
+++ b/Modules/FindOpenMP.cmake
@@ -16,6 +16,19 @@
# Variables
# ^^^^^^^^^
#
+# The module exposes the components ``C``, ``CXX``, and ``Fortran``.
+# Each of these controls the various languages to search OpenMP support for.
+#
+# Depending on the enabled components the following variables will be set:
+#
+# ``OpenMP_FOUND``
+# Variable indicating that OpenMP flags for all requested languages have been found.
+# If no components are specified, this is true if OpenMP settings for all enabled languages
+# were detected.
+# ``OpenMP_VERSION``
+# Minimal version of the OpenMP standard detected among the requested languages,
+# or all enabled languages if no components were specified.
+#
# This module will set the following variables per language in your
# project, where ``<lang>`` is one of C, CXX, or Fortran:
#
@@ -60,18 +73,9 @@
# The specification date is formatted as given in the OpenMP standard:
# ``yyyymm`` where ``yyyy`` and ``mm`` represents the year and month of
# the OpenMP specification implemented by the ``<lang>`` compiler.
-#
-# Backward Compatibility
-# ^^^^^^^^^^^^^^^^^^^^^^
-#
-# For backward compatibility with older versions of FindOpenMP, these
-# variables are set, but deprecated::
-#
-# OpenMP_FOUND
-#
-# In new projects, please use the ``OpenMP_<lang>_XXX`` equivalents.
cmake_policy(PUSH)
+cmake_policy(SET CMP0054 NEW) # if() quoted variables not dereferenced
cmake_policy(SET CMP0057 NEW) # if IN_LIST
function(_OPENMP_FLAG_CANDIDATES LANG)
@@ -95,10 +99,11 @@ function(_OPENMP_FLAG_CANDIDATES LANG)
set(OMP_FLAG_NAG "-openmp")
set(OMP_FLAG_Absoft "-openmp")
set(OMP_FLAG_PGI "-mp")
+ set(OMP_FLAG_Flang "-fopenmp")
set(OMP_FLAG_SunPro "-xopenmp")
set(OMP_FLAG_XL "-qsmp=omp")
- # Cray compiles with OpenMP automatically
- set(OMP_FLAG_Cray " ")
+ # Cray compiler activate OpenMP with -h omp, which is enabled by default.
+ set(OMP_FLAG_Cray " " "-h omp")
# If we know the correct flags, use those
if(DEFINED OMP_FLAG_${CMAKE_${LANG}_COMPILER_ID})
@@ -118,7 +123,9 @@ set(OpenMP_C_CXX_TEST_SOURCE
"
#include <omp.h>
int main() {
-#ifndef _OPENMP
+#ifdef _OPENMP
+ return 0;
+#else
breaks_on_purpose
#endif
}
@@ -161,14 +168,23 @@ function(_OPENMP_GET_FLAGS LANG FLAG_MODE OPENMP_FLAG_VAR OPENMP_LIB_NAMES_VAR)
_OPENMP_FLAG_CANDIDATES("${LANG}")
_OPENMP_WRITE_SOURCE_FILE("${LANG}" "TEST_SOURCE" OpenMPTryFlag _OPENMP_TEST_SRC)
+ unset(OpenMP_VERBOSE_COMPILE_OPTIONS)
+ separate_arguments(OpenMP_VERBOSE_OPTIONS NATIVE_COMMAND "${CMAKE_${LANG}_VERBOSE_FLAG}")
+ foreach(_VERBOSE_OPTION IN LISTS OpenMP_VERBOSE_OPTIONS)
+ if(NOT _VERBOSE_OPTION MATCHES "^-Wl,")
+ list(APPEND OpenMP_VERBOSE_COMPILE_OPTIONS ${_VERBOSE_OPTION})
+ endif()
+ endforeach()
+
foreach(OPENMP_FLAG IN LISTS OpenMP_${LANG}_FLAG_CANDIDATES)
set(OPENMP_FLAGS_TEST "${OPENMP_FLAG}")
- if(CMAKE_${LANG}_VERBOSE_FLAG)
- string(APPEND OPENMP_FLAGS_TEST " ${CMAKE_${LANG}_VERBOSE_FLAG}")
+ if(OpenMP_VERBOSE_COMPILE_OPTIONS)
+ string(APPEND OPENMP_FLAGS_TEST " ${OpenMP_VERBOSE_COMPILE_OPTIONS}")
endif()
string(REGEX REPLACE "[-/=+]" "" OPENMP_PLAIN_FLAG "${OPENMP_FLAG}")
try_compile( OpenMP_COMPILE_RESULT_${FLAG_MODE}_${OPENMP_PLAIN_FLAG} ${CMAKE_BINARY_DIR} ${_OPENMP_TEST_SRC}
CMAKE_FLAGS "-DCOMPILE_DEFINITIONS:STRING=${OPENMP_FLAGS_TEST}"
+ LINK_LIBRARIES ${CMAKE_${LANG}_VERBOSE_FLAG}
OUTPUT_VARIABLE OpenMP_TRY_COMPILE_OUTPUT
)
@@ -197,13 +213,27 @@ function(_OPENMP_GET_FLAGS LANG FLAG_MODE OPENMP_FLAG_VAR OPENMP_LIB_NAMES_VAR)
unset(_OPENMP_LIB_NAMES)
foreach(_OPENMP_IMPLICIT_LIB IN LISTS OpenMP_${LANG}_IMPLICIT_LIBRARIES)
- if(NOT "${_OPENMP_IMPLICIT_LIB}" IN_LIST CMAKE_${LANG}_IMPLICIT_LINK_LIBRARIES)
- find_library(OpenMP_${_OPENMP_IMPLICIT_LIB}_LIBRARY
- NAMES "${_OPENMP_IMPLICIT_LIB}"
- HINTS ${OpenMP_${LANG}_IMPLICIT_LINK_DIRS}
- )
- mark_as_advanced(OpenMP_${_OPENMP_IMPLICIT_LIB}_LIBRARY)
- list(APPEND _OPENMP_LIB_NAMES ${_OPENMP_IMPLICIT_LIB})
+ get_filename_component(_OPENMP_IMPLICIT_LIB_DIR "${_OPENMP_IMPLICIT_LIB}" DIRECTORY)
+ get_filename_component(_OPENMP_IMPLICIT_LIB_NAME "${_OPENMP_IMPLICIT_LIB}" NAME)
+ get_filename_component(_OPENMP_IMPLICIT_LIB_PLAIN "${_OPENMP_IMPLICIT_LIB}" NAME_WE)
+ string(REGEX REPLACE "([][+.*?()^$])" "\\\\\\1" _OPENMP_IMPLICIT_LIB_PLAIN_ESC "${_OPENMP_IMPLICIT_LIB_PLAIN}")
+ string(REGEX REPLACE "([][+.*?()^$])" "\\\\\\1" _OPENMP_IMPLICIT_LIB_PATH_ESC "${_OPENMP_IMPLICIT_LIB}")
+ if(NOT ( "${_OPENMP_IMPLICIT_LIB}" IN_LIST CMAKE_${LANG}_IMPLICIT_LINK_LIBRARIES
+ OR "${CMAKE_${LANG}_STANDARD_LIBRARIES}" MATCHES "(^| )(-Wl,)?(-l)?(${_OPENMP_IMPLICIT_LIB_PLAIN_ESC}|${_OPENMP_IMPLICIT_LIB_PATH_ESC})( |$)"
+ OR "${CMAKE_${LANG}_LINK_EXECUTABLE}" MATCHES "(^| )(-Wl,)?(-l)?(${_OPENMP_IMPLICIT_LIB_PLAIN_ESC}|${_OPENMP_IMPLICIT_LIB_PATH_ESC})( |$)" ) )
+ if(_OPENMP_IMPLICIT_LIB_DIR)
+ set(OpenMP_${_OPENMP_IMPLICIT_LIB_PLAIN}_LIBRARY "${_OPENMP_IMPLICIT_LIB}" CACHE FILEPATH
+ "Path to the ${_OPENMP_IMPLICIT_LIB_PLAIN} library for OpenMP")
+ else()
+ find_library(OpenMP_${_OPENMP_IMPLICIT_LIB_PLAIN}_LIBRARY
+ NAMES "${_OPENMP_IMPLICIT_LIB_NAME}"
+ DOC "Path to the ${_OPENMP_IMPLICIT_LIB_PLAIN} library for OpenMP"
+ HINTS ${OpenMP_${LANG}_IMPLICIT_LINK_DIRS}
+ CMAKE_FIND_ROOT_PATH_BOTH
+ )
+ endif()
+ mark_as_advanced(OpenMP_${_OPENMP_IMPLICIT_LIB_PLAIN}_LIBRARY)
+ list(APPEND _OPENMP_LIB_NAMES ${_OPENMP_IMPLICIT_LIB_PLAIN})
endif()
endforeach()
set("${OPENMP_LIB_NAMES_VAR}" "${_OPENMP_LIB_NAMES}" PARENT_SCOPE)
@@ -225,6 +255,8 @@ function(_OPENMP_GET_FLAGS LANG FLAG_MODE OPENMP_FLAG_VAR OPENMP_LIB_NAMES_VAR)
set("${OPENMP_LIB_NAMES_VAR}" "NOTFOUND" PARENT_SCOPE)
set("${OPENMP_FLAG_VAR}" "NOTFOUND" PARENT_SCOPE)
endforeach()
+
+ unset(OpenMP_VERBOSE_COMPILE_OPTIONS)
endfunction()
set(OpenMP_C_CXX_CHECK_VERSION_SOURCE
@@ -243,6 +275,7 @@ const char ompver_str[] = { 'I', 'N', 'F', 'O', ':', 'O', 'p', 'e', 'n', 'M',
int main()
{
puts(ompver_str);
+ return 0;
}
")
@@ -285,6 +318,8 @@ endfunction()
macro(_OPENMP_SET_VERSION_BY_SPEC_DATE LANG)
set(OpenMP_SPEC_DATE_MAP
+ # Preview versions
+ "201611=5.0" # OpenMP 5.0 preview 1
# Combined versions, 2.5 onwards
"201511=4.5"
"201307=4.0"
@@ -303,7 +338,11 @@ macro(_OPENMP_SET_VERSION_BY_SPEC_DATE LANG)
"199710=1.0"
)
- string(REGEX MATCHALL "${OpenMP_${LANG}_SPEC_DATE}=([0-9]+)\\.([0-9]+)" _version_match "${OpenMP_SPEC_DATE_MAP}")
+ if(OpenMP_${LANG}_SPEC_DATE)
+ string(REGEX MATCHALL "${OpenMP_${LANG}_SPEC_DATE}=([0-9]+)\\.([0-9]+)" _version_match "${OpenMP_SPEC_DATE_MAP}")
+ else()
+ set(_version_match "")
+ endif()
if(NOT _version_match STREQUAL "")
set(OpenMP_${LANG}_VERSION_MAJOR ${CMAKE_MATCH_1})
set(OpenMP_${LANG}_VERSION_MINOR ${CMAKE_MATCH_2})
@@ -372,11 +411,17 @@ if(CMAKE_Fortran_COMPILER_LOADED)
endif()
endif()
-set(OPENMP_FOUND TRUE)
+if(NOT OpenMP_FIND_COMPONENTS)
+ set(OpenMP_FINDLIST C CXX Fortran)
+else()
+ set(OpenMP_FINDLIST ${OpenMP_FIND_COMPONENTS})
+endif()
-foreach(LANG IN ITEMS C CXX Fortran)
+unset(_OpenMP_MIN_VERSION)
+
+foreach(LANG IN LISTS OpenMP_FINDLIST)
if(CMAKE_${LANG}_COMPILER_LOADED)
- if (NOT OpenMP_${LANG}_SPEC_DATE)
+ if (NOT OpenMP_${LANG}_SPEC_DATE AND OpenMP_${LANG}_FLAGS)
_OPENMP_GET_SPEC_DATE("${LANG}" OpenMP_${LANG}_SPEC_DATE_INTERNAL)
set(OpenMP_${LANG}_SPEC_DATE "${OpenMP_${LANG}_SPEC_DATE_INTERNAL}" CACHE
INTERNAL "${LANG} compiler's OpenMP specification date")
@@ -405,6 +450,11 @@ foreach(LANG IN ITEMS C CXX Fortran)
)
if(OpenMP_${LANG}_FOUND)
+ if(DEFINED OpenMP_${LANG}_VERSION)
+ if(NOT _OpenMP_MIN_VERSION OR _OpenMP_MIN_VERSION VERSION_GREATER OpenMP_${LANG}_VERSION)
+ set(_OpenMP_MIN_VERSION OpenMP_${LANG}_VERSION)
+ endif()
+ endif()
set(OpenMP_${LANG}_LIBRARIES "")
foreach(_OPENMP_IMPLICIT_LIB IN LISTS OpenMP_${LANG}_LIB_NAMES)
list(APPEND OpenMP_${LANG}_LIBRARIES "${OpenMP_${_OPENMP_IMPLICIT_LIB}_LIBRARY}")
@@ -423,13 +473,23 @@ foreach(LANG IN ITEMS C CXX Fortran)
set_property(TARGET OpenMP::OpenMP_${LANG} PROPERTY
INTERFACE_LINK_LIBRARIES "${OpenMP_${LANG}_LIBRARIES}")
endif()
- else()
- set(OPENMP_FOUND FALSE)
endif()
endif()
endforeach()
-set(OpenMP_FOUND ${OPENMP_FOUND})
+unset(_OpenMP_REQ_VARS)
+foreach(LANG IN ITEMS C CXX Fortran)
+ if((NOT OpenMP_FIND_COMPONENTS AND CMAKE_${LANG}_COMPILER_LOADED) OR LANG IN_LIST OpenMP_FIND_COMPONENTS)
+ list(APPEND _OpenMP_REQ_VARS "OpenMP_${LANG}_FOUND")
+ endif()
+endforeach()
+
+find_package_handle_standard_args(OpenMP
+ REQUIRED_VARS ${_OpenMP_REQ_VARS}
+ VERSION_VAR ${_OpenMP_MIN_VERSION}
+ HANDLE_COMPONENTS)
+
+set(OPENMP_FOUND ${OpenMP_FOUND})
if(CMAKE_Fortran_COMPILER_LOADED AND OpenMP_Fortran_FOUND)
if(NOT DEFINED OpenMP_Fortran_HAVE_OMPLIB_MODULE)
diff --git a/Modules/FindOpenSSL.cmake b/Modules/FindOpenSSL.cmake
index f32eb501d..0187e0d66 100644
--- a/Modules/FindOpenSSL.cmake
+++ b/Modules/FindOpenSSL.cmake
@@ -149,6 +149,7 @@ if(WIN32 AND NOT CYGWIN)
libcryptod
libeay32${_OPENSSL_MSVC_RT_MODE}d
libeay32d
+ cryptod
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES
@@ -176,6 +177,7 @@ if(WIN32 AND NOT CYGWIN)
libssld
ssleay32${_OPENSSL_MSVC_RT_MODE}d
ssleay32d
+ ssld
NAMES_PER_DIR
${_OPENSSL_ROOT_HINTS_AND_PATHS}
PATH_SUFFIXES
diff --git a/Modules/FindPackageHandleStandardArgs.cmake b/Modules/FindPackageHandleStandardArgs.cmake
index b851a90ff..67f6bd6f2 100644
--- a/Modules/FindPackageHandleStandardArgs.cmake
+++ b/Modules/FindPackageHandleStandardArgs.cmake
@@ -175,11 +175,12 @@ endmacro()
function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
-# set up the arguments for CMAKE_PARSE_ARGUMENTS and check whether we are in
-# new extended or in the "old" mode:
+# Set up the arguments for `cmake_parse_arguments`.
set(options CONFIG_MODE HANDLE_COMPONENTS)
set(oneValueArgs FAIL_MESSAGE VERSION_VAR FOUND_VAR)
set(multiValueArgs REQUIRED_VARS)
+
+# Check whether we are in 'simple' or 'extended' mode:
set(_KEYWORDS_FOR_EXTENDED_MODE ${options} ${oneValueArgs} ${multiValueArgs} )
list(FIND _KEYWORDS_FOR_EXTENDED_MODE "${_FIRST_ARG}" INDEX)
@@ -188,8 +189,7 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
set(FPHSA_REQUIRED_VARS ${ARGN})
set(FPHSA_VERSION_VAR)
else()
-
- CMAKE_PARSE_ARGUMENTS(FPHSA "${options}" "${oneValueArgs}" "${multiValueArgs}" ${_FIRST_ARG} ${ARGN})
+ cmake_parse_arguments(FPHSA "${options}" "${oneValueArgs}" "${multiValueArgs}" ${_FIRST_ARG} ${ARGN})
if(FPHSA_UNPARSED_ARGUMENTS)
message(FATAL_ERROR "Unknown keywords given to FIND_PACKAGE_HANDLE_STANDARD_ARGS(): \"${FPHSA_UNPARSED_ARGUMENTS}\"")
@@ -198,6 +198,18 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
if(NOT FPHSA_FAIL_MESSAGE)
set(FPHSA_FAIL_MESSAGE "DEFAULT_MSG")
endif()
+
+ # In config-mode, we rely on the variable <package>_CONFIG, which is set by find_package()
+ # when it successfully found the config-file, including version checking:
+ if(FPHSA_CONFIG_MODE)
+ list(INSERT FPHSA_REQUIRED_VARS 0 ${_NAME}_CONFIG)
+ list(REMOVE_DUPLICATES FPHSA_REQUIRED_VARS)
+ set(FPHSA_VERSION_VAR ${_NAME}_VERSION)
+ endif()
+
+ if(NOT FPHSA_REQUIRED_VARS)
+ message(FATAL_ERROR "No REQUIRED_VARS specified for FIND_PACKAGE_HANDLE_STANDARD_ARGS()")
+ endif()
endif()
# now that we collected all arguments, process them
@@ -206,18 +218,6 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
set(FPHSA_FAIL_MESSAGE "Could NOT find ${_NAME}")
endif()
- # In config-mode, we rely on the variable <package>_CONFIG, which is set by find_package()
- # when it successfully found the config-file, including version checking:
- if(FPHSA_CONFIG_MODE)
- list(INSERT FPHSA_REQUIRED_VARS 0 ${_NAME}_CONFIG)
- list(REMOVE_DUPLICATES FPHSA_REQUIRED_VARS)
- set(FPHSA_VERSION_VAR ${_NAME}_VERSION)
- endif()
-
- if(NOT FPHSA_REQUIRED_VARS)
- message(FATAL_ERROR "No REQUIRED_VARS specified for FIND_PACKAGE_HANDLE_STANDARD_ARGS()")
- endif()
-
list(GET FPHSA_REQUIRED_VARS 0 _FIRST_REQUIRED_VAR)
string(TOUPPER ${_NAME} _NAME_UPPER)
@@ -289,15 +289,15 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
# version handling:
set(VERSION_MSG "")
set(VERSION_OK TRUE)
- set(VERSION ${${FPHSA_VERSION_VAR}})
# check with DEFINED here as the requested or found version may be "0"
if (DEFINED ${_NAME}_FIND_VERSION)
if(DEFINED ${FPHSA_VERSION_VAR})
+ set(_FOUND_VERSION ${${FPHSA_VERSION_VAR}})
if(${_NAME}_FIND_VERSION_EXACT) # exact version required
# count the dots in the version string
- string(REGEX REPLACE "[^.]" "" _VERSION_DOTS "${VERSION}")
+ string(REGEX REPLACE "[^.]" "" _VERSION_DOTS "${_FOUND_VERSION}")
# add one dot because there is one dot more than there are components
string(LENGTH "${_VERSION_DOTS}." _VERSION_DOTS)
if (_VERSION_DOTS GREATER ${_NAME}_FIND_VERSION_COUNT)
@@ -312,31 +312,31 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
else ()
set(_VERSION_REGEX "[^.]*\\.[^.]*\\.[^.]*\\.[^.]*")
endif ()
- string(REGEX REPLACE "^(${_VERSION_REGEX})\\..*" "\\1" _VERSION_HEAD "${VERSION}")
+ string(REGEX REPLACE "^(${_VERSION_REGEX})\\..*" "\\1" _VERSION_HEAD "${_FOUND_VERSION}")
unset(_VERSION_REGEX)
if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL _VERSION_HEAD)
- set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
+ set(VERSION_MSG "Found unsuitable version \"${_FOUND_VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
set(VERSION_OK FALSE)
else ()
- set(VERSION_MSG "(found suitable exact version \"${VERSION}\")")
+ set(VERSION_MSG "(found suitable exact version \"${_FOUND_VERSION}\")")
endif ()
unset(_VERSION_HEAD)
else ()
- if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL VERSION)
- set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
+ if (NOT ${_NAME}_FIND_VERSION VERSION_EQUAL _FOUND_VERSION)
+ set(VERSION_MSG "Found unsuitable version \"${_FOUND_VERSION}\", but required is exact version \"${${_NAME}_FIND_VERSION}\"")
set(VERSION_OK FALSE)
else ()
- set(VERSION_MSG "(found suitable exact version \"${VERSION}\")")
+ set(VERSION_MSG "(found suitable exact version \"${_FOUND_VERSION}\")")
endif ()
endif ()
unset(_VERSION_DOTS)
else() # minimum version specified:
- if (${_NAME}_FIND_VERSION VERSION_GREATER VERSION)
- set(VERSION_MSG "Found unsuitable version \"${VERSION}\", but required is at least \"${${_NAME}_FIND_VERSION}\"")
+ if (${_NAME}_FIND_VERSION VERSION_GREATER _FOUND_VERSION)
+ set(VERSION_MSG "Found unsuitable version \"${_FOUND_VERSION}\", but required is at least \"${${_NAME}_FIND_VERSION}\"")
set(VERSION_OK FALSE)
else ()
- set(VERSION_MSG "(found suitable version \"${VERSION}\", minimum required is \"${${_NAME}_FIND_VERSION}\")")
+ set(VERSION_MSG "(found suitable version \"${_FOUND_VERSION}\", minimum required is \"${${_NAME}_FIND_VERSION}\")")
endif ()
endif()
@@ -351,13 +351,14 @@ function(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FIRST_ARG)
endif()
else ()
- if(VERSION)
- set(VERSION_MSG "(found version \"${VERSION}\")")
+ # Check with DEFINED as the found version may be 0.
+ if(DEFINED ${FPHSA_VERSION_VAR})
+ set(VERSION_MSG "(found version \"${${FPHSA_VERSION_VAR}}\")")
endif()
endif ()
if(VERSION_OK)
- string(APPEND DETAILS "[v${VERSION}(${${_NAME}_FIND_VERSION})]")
+ string(APPEND DETAILS "[v${${FPHSA_VERSION_VAR}}(${${_NAME}_FIND_VERSION})]")
else()
set(${_NAME}_FOUND FALSE)
endif()
diff --git a/Modules/FindPatch.cmake b/Modules/FindPatch.cmake
new file mode 100644
index 000000000..3ebcae909
--- /dev/null
+++ b/Modules/FindPatch.cmake
@@ -0,0 +1,68 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+#.rst:
+# FindPatch
+# ---------
+#
+# The module defines the following variables:
+#
+# ``Patch_EXECUTABLE``
+# Path to patch command-line executable.
+# ``Patch_FOUND``
+# True if the patch command-line executable was found.
+#
+# The following :prop_tgt:`IMPORTED` targets are also defined:
+#
+# ``Patch::patch``
+# The command-line executable.
+#
+# Example usage:
+#
+# .. code-block:: cmake
+#
+# find_package(Patch)
+# if(Patch_FOUND)
+# message("Patch found: ${Patch_EXECUTABLE}")
+# endif()
+
+set(_doc "Patch command line executable")
+set(_patch_path )
+
+if(CMAKE_HOST_WIN32)
+ set(_patch_path
+ "$ENV{LOCALAPPDATA}/Programs/Git/bin"
+ "$ENV{LOCALAPPDATA}/Programs/Git/usr/bin"
+ "$ENV{APPDATA}/Programs/Git/bin"
+ "$ENV{APPDATA}/Programs/Git/usr/bin"
+ )
+endif()
+
+# First search the PATH
+find_program(Patch_EXECUTABLE
+ NAME patch
+ PATHS ${_patch_path}
+ DOC ${_doc}
+ )
+
+if(CMAKE_HOST_WIN32)
+ # Now look for installations in Git/ directories under typical installation
+ # prefixes on Windows.
+ find_program(Patch_EXECUTABLE
+ NAMES patch
+ PATH_SUFFIXES Git/usr/bin Git/bin GnuWin32/bin
+ DOC ${_doc}
+ )
+endif()
+
+if(Patch_EXECUTABLE AND NOT TARGET Patch::patch)
+ add_executable(Patch::patch IMPORTED)
+ set_property(TARGET Patch::patch PROPERTY IMPORTED_LOCATION ${Patch_EXECUTABLE})
+endif()
+
+unset(_patch_path)
+unset(_doc)
+
+include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
+find_package_handle_standard_args(Patch
+ REQUIRED_VARS Patch_EXECUTABLE)
diff --git a/Modules/FindPkgConfig.cmake b/Modules/FindPkgConfig.cmake
index a5357fa1c..76afa8a5d 100644
--- a/Modules/FindPkgConfig.cmake
+++ b/Modules/FindPkgConfig.cmake
@@ -323,6 +323,9 @@ macro(_pkg_check_modules_internal _is_required _is_silent _no_cmake_path _no_cma
endif()
endif()
endif()
+ if(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD" AND NOT CMAKE_CROSSCOMPILING)
+ list(APPEND _lib_dirs "libdata/pkgconfig")
+ endif()
list(APPEND _lib_dirs "lib/pkgconfig")
list(APPEND _lib_dirs "share/pkgconfig")
@@ -584,7 +587,9 @@ endmacro()
macro(pkg_check_modules _prefix _module0)
_pkgconfig_parse_options(_pkg_modules _pkg_is_required _pkg_is_silent _no_cmake_path _no_cmake_environment_path _imp_target "${_module0}" ${ARGN})
# check cached value
- if (NOT DEFINED __pkg_config_checked_${_prefix} OR __pkg_config_checked_${_prefix} LESS ${PKG_CONFIG_VERSION} OR NOT ${_prefix}_FOUND OR NOT "${__pkg_config_arguments_${_prefix}}" STREQUAL "${_module0};${ARGN}")
+ if (NOT DEFINED __pkg_config_checked_${_prefix} OR __pkg_config_checked_${_prefix} LESS ${PKG_CONFIG_VERSION} OR NOT ${_prefix}_FOUND OR
+ (NOT "${ARGN}" STREQUAL "" AND NOT "${__pkg_config_arguments_${_prefix}}" STREQUAL "${_module0};${ARGN}") OR
+ ( "${ARGN}" STREQUAL "" AND NOT "${__pkg_config_arguments_${_prefix}}" STREQUAL "${_module0}"))
_pkg_check_modules_internal("${_pkg_is_required}" "${_pkg_is_silent}" ${_no_cmake_path} ${_no_cmake_environment_path} ${_imp_target} "${_prefix}" ${_pkg_modules})
_pkgconfig_set(__pkg_config_checked_${_prefix} ${PKG_CONFIG_VERSION})
diff --git a/Modules/FindProtobuf.cmake b/Modules/FindProtobuf.cmake
index 33262f3d6..e1a715e66 100644
--- a/Modules/FindProtobuf.cmake
+++ b/Modules/FindProtobuf.cmake
@@ -48,6 +48,8 @@
# The protobuf lite library.
# ``protobuf::libprotoc``
# The protoc library.
+# ``protobuf::protoc``
+# The protoc compiler.
#
# The following cache variables are also available to set or use:
#
@@ -77,6 +79,7 @@
# include_directories(${CMAKE_CURRENT_BINARY_DIR})
# protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS foo.proto)
# protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS EXPORT_MACRO DLL_EXPORT foo.proto)
+# protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS DESCRIPTORS PROTO_DESCS foo.proto)
# protobuf_generate_python(PROTO_PY foo.proto)
# add_executable(bar bar.cc ${PROTO_SRCS} ${PROTO_HDRS})
# target_link_libraries(bar ${Protobuf_LIBRARIES})
@@ -90,12 +93,15 @@
#
# Add custom commands to process ``.proto`` files to C++::
#
-# protobuf_generate_cpp (<SRCS> <HDRS> [EXPORT_MACRO <MACRO>] [<ARGN>...])
+# protobuf_generate_cpp (<SRCS> <HDRS>
+# [DESCRIPTORS <DESC>] [EXPORT_MACRO <MACRO>] [<ARGN>...])
#
# ``SRCS``
# Variable to define with autogenerated source files
# ``HDRS``
# Variable to define with autogenerated header files
+# ``DESCRIPTORS``
+# Variable to define with autogenerated descriptor files, if requested.
# ``EXPORT_MACRO``
# is a macro which should expand to ``__declspec(dllexport)`` or
# ``__declspec(dllimport)`` depending on what is being compiled.
@@ -114,7 +120,7 @@
# ``.proto`` filess
function(PROTOBUF_GENERATE_CPP SRCS HDRS)
- cmake_parse_arguments(protobuf "" "EXPORT_MACRO" "" ${ARGN})
+ cmake_parse_arguments(protobuf "" "EXPORT_MACRO;DESCRIPTORS" "" ${ARGN})
set(PROTO_FILES "${protobuf_UNPARSED_ARGUMENTS}")
if(NOT PROTO_FILES)
@@ -156,6 +162,10 @@ function(PROTOBUF_GENERATE_CPP SRCS HDRS)
set(${SRCS})
set(${HDRS})
+ if (protobuf_DESCRIPTORS)
+ set(${protobuf_DESCRIPTORS})
+ endif()
+
foreach(FIL ${PROTO_FILES})
get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
get_filename_component(FIL_WE ${FIL} NAME_WE)
@@ -166,22 +176,38 @@ function(PROTOBUF_GENERATE_CPP SRCS HDRS)
endif()
endif()
- list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc")
- list(APPEND ${HDRS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h")
+ set(_protobuf_protoc_src "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc")
+ set(_protobuf_protoc_hdr "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h")
+ list(APPEND ${SRCS} "${_protobuf_protoc_src}")
+ list(APPEND ${HDRS} "${_protobuf_protoc_hdr}")
+
+ if(protobuf_DESCRIPTORS)
+ set(_protobuf_protoc_desc "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.desc")
+ set(_protobuf_protoc_flags "--descriptor_set_out=${_protobuf_protoc_desc}")
+ list(APPEND ${protobuf_DESCRIPTORS} "${_protobuf_protoc_desc}")
+ else()
+ set(_protobuf_protoc_desc "")
+ set(_protobuf_protoc_flags "")
+ endif()
add_custom_command(
- OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc"
- "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h"
- COMMAND ${Protobuf_PROTOC_EXECUTABLE}
- ARGS "--cpp_out=${DLL_EXPORT_DECL}${CMAKE_CURRENT_BINARY_DIR}" ${_protobuf_include_path} ${ABS_FIL}
- DEPENDS ${ABS_FIL} ${Protobuf_PROTOC_EXECUTABLE}
+ OUTPUT "${_protobuf_protoc_src}"
+ "${_protobuf_protoc_hdr}"
+ ${_protobuf_protoc_desc}
+ COMMAND protobuf::protoc
+ "--cpp_out=${DLL_EXPORT_DECL}${CMAKE_CURRENT_BINARY_DIR}"
+ ${_protobuf_protoc_flags}
+ ${_protobuf_include_path} ${ABS_FIL}
+ DEPENDS ${ABS_FIL} protobuf::protoc
COMMENT "Running C++ protocol buffer compiler on ${FIL}"
VERBATIM )
endforeach()
- set_source_files_properties(${${SRCS}} ${${HDRS}} PROPERTIES GENERATED TRUE)
- set(${SRCS} ${${SRCS}} PARENT_SCOPE)
- set(${HDRS} ${${HDRS}} PARENT_SCOPE)
+ set(${SRCS} "${${SRCS}}" PARENT_SCOPE)
+ set(${HDRS} "${${HDRS}}" PARENT_SCOPE)
+ if(protobuf_DESCRIPTORS)
+ set(${protobuf_DESCRIPTORS} "${${protobuf_DESCRIPTORS}}" PARENT_SCOPE)
+ endif()
endfunction()
function(PROTOBUF_GENERATE_PYTHON SRCS)
@@ -232,8 +258,8 @@ function(PROTOBUF_GENERATE_PYTHON SRCS)
list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}_pb2.py")
add_custom_command(
OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}_pb2.py"
- COMMAND ${Protobuf_PROTOC_EXECUTABLE} --python_out ${CMAKE_CURRENT_BINARY_DIR} ${_protobuf_include_path} ${ABS_FIL}
- DEPENDS ${ABS_FIL} ${Protobuf_PROTOC_EXECUTABLE}
+ COMMAND protobuf::protoc --python_out ${CMAKE_CURRENT_BINARY_DIR} ${_protobuf_include_path} ${ABS_FIL}
+ DEPENDS ${ABS_FIL} protobuf::protoc
COMMENT "Running Python protocol buffer compiler on ${FIL}"
VERBATIM )
endforeach()
@@ -501,6 +527,16 @@ if(Protobuf_INCLUDE_DIR)
endif()
endif()
endif()
+
+ if(Protobuf_PROTOC_EXECUTABLE)
+ if(NOT TARGET protobuf::protoc)
+ add_executable(protobuf::protoc IMPORTED)
+ if(EXISTS "${Protobuf_PROTOC_EXECUTABLE}")
+ set_target_properties(protobuf::protoc PROPERTIES
+ IMPORTED_LOCATION "${Protobuf_PROTOC_EXECUTABLE}")
+ endif()
+ endif()
+ endif()
endif()
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
diff --git a/Modules/FindQt4.cmake b/Modules/FindQt4.cmake
index b0c49e564..c67d0beaa 100644
--- a/Modules/FindQt4.cmake
+++ b/Modules/FindQt4.cmake
@@ -355,19 +355,21 @@ macro (_QT4_ADJUST_LIB_VARS _camelCaseBasename)
if (QT_${basename}_LIBRARY_RELEASE)
set_property(TARGET Qt4::${_camelCaseBasename} APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
- if(QT_USE_FRAMEWORKS)
- set_property(TARGET Qt4::${_camelCaseBasename} PROPERTY IMPORTED_LOCATION_RELEASE "${QT_${basename}_LIBRARY_RELEASE}/${_camelCaseBasename}" )
+ set(_location "${QT_${basename}_LIBRARY_RELEASE}")
+ if(QT_USE_FRAMEWORKS AND EXISTS ${_location}/${_camelCaseBasename})
+ set_property(TARGET Qt4::${_camelCaseBasename} PROPERTY IMPORTED_LOCATION_RELEASE "${_location}/${_camelCaseBasename}" )
else()
- set_property(TARGET Qt4::${_camelCaseBasename} PROPERTY IMPORTED_LOCATION_RELEASE "${QT_${basename}_LIBRARY_RELEASE}" )
+ set_property(TARGET Qt4::${_camelCaseBasename} PROPERTY IMPORTED_LOCATION_RELEASE "${_location}" )
endif()
endif ()
if (QT_${basename}_LIBRARY_DEBUG)
set_property(TARGET Qt4::${_camelCaseBasename} APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG)
- if(QT_USE_FRAMEWORKS)
- set_property(TARGET Qt4::${_camelCaseBasename} PROPERTY IMPORTED_LOCATION_DEBUG "${QT_${basename}_LIBRARY_DEBUG}/${_camelCaseBasename}" )
+ set(_location "${QT_${basename}_LIBRARY_DEBUG}")
+ if(QT_USE_FRAMEWORKS AND EXISTS ${_location}/${_camelCaseBasename})
+ set_property(TARGET Qt4::${_camelCaseBasename} PROPERTY IMPORTED_LOCATION_DEBUG "${_location}/${_camelCaseBasename}" )
else()
- set_property(TARGET Qt4::${_camelCaseBasename} PROPERTY IMPORTED_LOCATION_DEBUG "${QT_${basename}_LIBRARY_DEBUG}" )
+ set_property(TARGET Qt4::${_camelCaseBasename} PROPERTY IMPORTED_LOCATION_DEBUG "${_location}" )
endif()
endif ()
set_property(TARGET Qt4::${_camelCaseBasename} PROPERTY
diff --git a/Modules/FindThreads.cmake b/Modules/FindThreads.cmake
index 2c6a58beb..a0148dd90 100644
--- a/Modules/FindThreads.cmake
+++ b/Modules/FindThreads.cmake
@@ -86,23 +86,16 @@ macro(_check_pthreads_flag)
set(_threads_src ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/FindThreads/CheckForPthreads.cxx)
configure_file(${CMAKE_CURRENT_LIST_DIR}/CheckForPthreads.c "${_threads_src}" COPYONLY)
endif()
- try_run(THREADS_PTHREAD_ARG THREADS_HAVE_PTHREAD_ARG
+ try_compile(THREADS_HAVE_PTHREAD_ARG
${CMAKE_BINARY_DIR}
${_threads_src}
CMAKE_FLAGS -DLINK_LIBRARIES:STRING=-pthread
- COMPILE_OUTPUT_VARIABLE OUTPUT)
+ OUTPUT_VARIABLE OUTPUT)
unset(_threads_src)
if(THREADS_HAVE_PTHREAD_ARG)
- if(THREADS_PTHREAD_ARG STREQUAL "2")
- set(Threads_FOUND TRUE)
- message(STATUS "Check if compiler accepts -pthread - yes")
- else()
- message(STATUS "Check if compiler accepts -pthread - no")
- file(APPEND
- ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
- "Determining if compiler accepts -pthread returned ${THREADS_PTHREAD_ARG} instead of 2. The compiler had the following output:\n${OUTPUT}\n\n")
- endif()
+ set(Threads_FOUND TRUE)
+ message(STATUS "Check if compiler accepts -pthread - yes")
else()
message(STATUS "Check if compiler accepts -pthread - no")
file(APPEND
diff --git a/Modules/FindXCTest.cmake b/Modules/FindXCTest.cmake
index ffdf677cc..849733661 100644
--- a/Modules/FindXCTest.cmake
+++ b/Modules/FindXCTest.cmake
@@ -136,7 +136,7 @@ function(xctest_add_bundle target testee)
XCODE_ATTRIBUTE_TEST_HOST "$<TARGET_FILE:${testee}>")
if(NOT XCODE_VERSION VERSION_LESS 7.3)
set_target_properties(${target} PROPERTIES
- LIBRARY_OUTPUT_DIRECTORY "$<TARGET_FILE_DIR:${testee}>/../PlugIns")
+ LIBRARY_OUTPUT_DIRECTORY "$<TARGET_BUNDLE_CONTENT_DIR:${testee}>/PlugIns")
endif()
else(XCODE)
target_link_libraries(${target}
@@ -183,7 +183,7 @@ function(xctest_add_test name bundle)
add_test(
NAME ${name}
- COMMAND ${XCTest_EXECUTABLE} $<TARGET_LINKER_FILE_DIR:${bundle}>/../..)
+ COMMAND ${XCTest_EXECUTABLE} $<TARGET_BUNDLE_DIR:${bundle}>)
# point loader to testee in case rpath is disabled
diff --git a/Modules/FindXMLRPC.cmake b/Modules/FindXMLRPC.cmake
index f0b258397..e7ae9197d 100644
--- a/Modules/FindXMLRPC.cmake
+++ b/Modules/FindXMLRPC.cmake
@@ -43,20 +43,12 @@ endif()
# Lookup the include directories needed for the components requested.
if(XMLRPC_C_FOUND)
- # Use the newer EXECUTE_PROCESS command if it is available.
- if(COMMAND EXECUTE_PROCESS)
- execute_process(
- COMMAND ${XMLRPC_C_CONFIG} ${XMLRPC_FIND_COMPONENTS} --cflags
- OUTPUT_VARIABLE XMLRPC_C_CONFIG_CFLAGS
- OUTPUT_STRIP_TRAILING_WHITESPACE
- RESULT_VARIABLE XMLRPC_C_CONFIG_RESULT
- )
- else()
- exec_program(${XMLRPC_C_CONFIG} ARGS "${XMLRPC_FIND_COMPONENTS} --cflags"
- OUTPUT_VARIABLE XMLRPC_C_CONFIG_CFLAGS
- RETURN_VALUE XMLRPC_C_CONFIG_RESULT
- )
- endif()
+ execute_process(
+ COMMAND ${XMLRPC_C_CONFIG} ${XMLRPC_FIND_COMPONENTS} --cflags
+ OUTPUT_VARIABLE XMLRPC_C_CONFIG_CFLAGS
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ RESULT_VARIABLE XMLRPC_C_CONFIG_RESULT
+ )
# Parse the include flags.
if("${XMLRPC_C_CONFIG_RESULT}" STREQUAL "0")
@@ -65,6 +57,7 @@ if(XMLRPC_C_FOUND)
XMLRPC_C_CONFIG_CFLAGS "${XMLRPC_C_CONFIG_CFLAGS}")
# Look for -I options.
+ # FIXME: Use these as hints to a find_path call to find the headers.
set(XMLRPC_INCLUDE_DIRS)
foreach(flag ${XMLRPC_C_CONFIG_CFLAGS})
if("${flag}" MATCHES "^-I(.+)")
@@ -80,20 +73,12 @@ endif()
# Lookup the libraries needed for the components requested.
if(XMLRPC_C_FOUND)
- # Use the newer EXECUTE_PROCESS command if it is available.
- if(COMMAND EXECUTE_PROCESS)
- execute_process(
- COMMAND ${XMLRPC_C_CONFIG} ${XMLRPC_FIND_COMPONENTS} --libs
- OUTPUT_VARIABLE XMLRPC_C_CONFIG_LIBS
- OUTPUT_STRIP_TRAILING_WHITESPACE
- RESULT_VARIABLE XMLRPC_C_CONFIG_RESULT
- )
- else()
- exec_program(${XMLRPC_C_CONFIG} ARGS "${XMLRPC_FIND_COMPONENTS} --libs"
- OUTPUT_VARIABLE XMLRPC_C_CONFIG_LIBS
- RETURN_VALUE XMLRPC_C_CONFIG_RESULT
- )
- endif()
+ execute_process(
+ COMMAND ${XMLRPC_C_CONFIG} ${XMLRPC_FIND_COMPONENTS} --libs
+ OUTPUT_VARIABLE XMLRPC_C_CONFIG_LIBS
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ RESULT_VARIABLE XMLRPC_C_CONFIG_RESULT
+ )
# Parse the library names and directories.
if("${XMLRPC_C_CONFIG_RESULT}" STREQUAL "0")
@@ -139,5 +124,5 @@ endif()
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(
XMLRPC
- REQUIRED_VARS XMLRPC_C_FOUND XMLRPC_LIBRARIES XMLRPC_INCLUDE_DIRS
+ REQUIRED_VARS XMLRPC_C_FOUND XMLRPC_LIBRARIES
FAIL_MESSAGE "XMLRPC was not found. Make sure the entries XMLRPC_* are set.")
diff --git a/Modules/FindwxWidgets.cmake b/Modules/FindwxWidgets.cmake
index af4daf061..be8499953 100644
--- a/Modules/FindwxWidgets.cmake
+++ b/Modules/FindwxWidgets.cmake
@@ -527,8 +527,10 @@ if(wxWidgets_FIND_STYLE STREQUAL "win32")
mswunivu/wx/setup.h
mswunivud/wx/setup.h
PATHS
+ ${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_TOOLVER}_xp${_WX_ARCH}_dll # prefer shared
${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_TOOLVER}${_WX_ARCH}_dll # prefer shared
${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_ARCH}_dll # prefer shared
+ ${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_TOOLVER}_xp${_WX_ARCH}_lib
${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_TOOLVER}${_WX_ARCH}_lib
${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_ARCH}_lib
DOC "Path to wxWidgets libraries"
@@ -546,8 +548,10 @@ if(wxWidgets_FIND_STYLE STREQUAL "win32")
mswunivu/wx/setup.h
mswunivud/wx/setup.h
PATHS
+ ${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_TOOLVER}_xp${_WX_ARCH}_lib # prefer static
${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_TOOLVER}${_WX_ARCH}_lib # prefer static
${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_ARCH}_lib # prefer static
+ ${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_TOOLVER}_xp${_WX_ARCH}_dll
${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_TOOLVER}${_WX_ARCH}_dll
${WX_ROOT_DIR}/lib/${_WX_TOOL}${_WX_ARCH}_dll
DOC "Path to wxWidgets libraries"
@@ -778,28 +782,24 @@ else()
)
if(RET EQUAL 0)
string(STRIP "${wxWidgets_CXX_FLAGS}" wxWidgets_CXX_FLAGS)
- separate_arguments(wxWidgets_CXX_FLAGS)
+ separate_arguments(wxWidgets_CXX_FLAGS_LIST NATIVE_COMMAND "${wxWidgets_CXX_FLAGS}")
DBG_MSG_V("wxWidgets_CXX_FLAGS=${wxWidgets_CXX_FLAGS}")
- # parse definitions from cxxflags;
- # drop -D* from CXXFLAGS and the -D prefix
- string(REGEX MATCHALL "-D[^;]+"
- wxWidgets_DEFINITIONS "${wxWidgets_CXX_FLAGS}")
- string(REGEX REPLACE "-D[^;]+(;|$)" ""
- wxWidgets_CXX_FLAGS "${wxWidgets_CXX_FLAGS}")
- string(REGEX REPLACE ";$" ""
- wxWidgets_CXX_FLAGS "${wxWidgets_CXX_FLAGS}")
- string(REPLACE "-D" ""
- wxWidgets_DEFINITIONS "${wxWidgets_DEFINITIONS}")
-
- # parse include dirs from cxxflags; drop -I prefix
- string(REGEX MATCHALL "-I[^;]+"
- wxWidgets_INCLUDE_DIRS "${wxWidgets_CXX_FLAGS}")
- string(REGEX REPLACE "-I[^;]+;" ""
- wxWidgets_CXX_FLAGS "${wxWidgets_CXX_FLAGS}")
- string(REPLACE "-I" ""
- wxWidgets_INCLUDE_DIRS "${wxWidgets_INCLUDE_DIRS}")
+ # parse definitions and include dirs from cxxflags
+ # drop the -D and -I prefixes
+ set(wxWidgets_CXX_FLAGS)
+ foreach(arg IN LISTS wxWidgets_CXX_FLAGS_LIST)
+ if("${arg}" MATCHES "^-I(.*)$")
+ # include directory
+ list(APPEND wxWidgets_INCLUDE_DIRS "${CMAKE_MATCH_1}")
+ elseif("${arg}" MATCHES "^-D(.*)$")
+ # compile definition
+ list(APPEND wxWidgets_DEFINITIONS "${CMAKE_MATCH_1}")
+ else()
+ list(APPEND wxWidgets_CXX_FLAGS "${arg}")
+ endif()
+ endforeach()
DBG_MSG_V("wxWidgets_DEFINITIONS=${wxWidgets_DEFINITIONS}")
DBG_MSG_V("wxWidgets_INCLUDE_DIRS=${wxWidgets_INCLUDE_DIRS}")
diff --git a/Modules/GNUInstallDirs.cmake b/Modules/GNUInstallDirs.cmake
index 64bd09e68..91361d298 100644
--- a/Modules/GNUInstallDirs.cmake
+++ b/Modules/GNUInstallDirs.cmake
@@ -123,6 +123,9 @@
# allow users who create additional path variables to also compute
# absolute paths where necessary, using the same logic.
+cmake_policy(PUSH)
+cmake_policy(SET CMP0054 NEW) # if() quoted variables not dereferenced
+
# Convert a cache variable to PATH type
macro(_GNUInstallDirs_cache_convert_to_path var description)
@@ -371,3 +374,5 @@ foreach(dir
)
GNUInstallDirs_get_absolute_install_dir(CMAKE_INSTALL_FULL_${dir} CMAKE_INSTALL_${dir})
endforeach()
+
+cmake_policy(POP)
diff --git a/Modules/GetPrerequisites.cmake b/Modules/GetPrerequisites.cmake
index 4e52cb300..b81dd76aa 100644
--- a/Modules/GetPrerequisites.cmake
+++ b/Modules/GetPrerequisites.cmake
@@ -659,7 +659,6 @@ function(get_prerequisites target prerequisites_var exclude_system recurse exepa
if(NOT EXISTS "${target}")
message("warning: target '${target}' does not exist...")
- set(${prerequisites_var} "" PARENT_SCOPE)
return()
endif()
diff --git a/Modules/GoogleTest.cmake b/Modules/GoogleTest.cmake
index 7415e0681..41bd1dccd 100644
--- a/Modules/GoogleTest.cmake
+++ b/Modules/GoogleTest.cmake
@@ -5,7 +5,33 @@
GoogleTest
----------
-This module defines functions to help use the Google Test infrastructure.
+This module defines functions to help use the Google Test infrastructure. Two
+mechanisms for adding tests are provided. :command:`gtest_add_tests` has been
+around for some time, originally via ``find_package(GTest)``.
+:command:`gtest_discover_tests` was introduced in CMake 3.10.
+
+The (older) :command:`gtest_add_tests` scans source files to identify tests.
+This is usually effective, with some caveats, including in cross-compiling
+environments, and makes setting additional properties on tests more convenient.
+However, its handling of parameterized tests is less comprehensive, and it
+requires re-running CMake to detect changes to the list of tests.
+
+The (newer) :command:`gtest_discover_tests` discovers tests by asking the
+compiled test executable to enumerate its tests. This is more robust and
+provides better handling of parameterized tests, and does not require CMake
+to be re-run when tests change. However, it may not work in a cross-compiling
+environment, and setting test properties is less convenient.
+
+More details can be found in the documentation of the respective functions.
+
+Both commands are intended to replace use of :command:`add_test` to register
+tests, and will create a separate CTest test for each Google Test test case.
+Note that this is in some cases less efficient, as common set-up and tear-down
+logic cannot be shared by multiple test cases executing in the same instance.
+However, it provides more fine-grained pass/fail information to CTest, which is
+usually considered as more beneficial. By default, the CTest test name is the
+same as the Google Test name (i.e. ``suite.testcase``); see also
+``TEST_PREFIX`` and ``TEST_SUFFIX``.
.. command:: gtest_add_tests
@@ -22,12 +48,25 @@ This module defines functions to help use the Google Test infrastructure.
[TEST_LIST outVar]
)
+ ``gtest_add_tests`` attempts to identify tests by scanning source files.
+ Although this is generally effective, it uses only a basic regular expression
+ match, which can be defeated by atypical test declarations, and is unable to
+ fully "split" parameterized tests. Additionally, it requires that CMake be
+ re-run to discover any newly added, removed or renamed tests (by default,
+ this means that CMake is re-run when any test source file is changed, but see
+ ``SKIP_DEPENDENCY``). However, it has the advantage of declaring tests at
+ CMake time, which somewhat simplifies setting additional properties on tests,
+ and always works in a cross-compiling environment.
+
+ The options are:
+
``TARGET target``
- This must be a known CMake target. CMake will substitute the location of
- the built executable when running the test.
+ Specifies the Google Test executable, which must be a known CMake
+ executable target. CMake will substitute the location of the built
+ executable when running the test.
``SOURCES src1...``
- When provided, only the listed files will be scanned for test cases. If
+ When provided, only the listed files will be scanned for test cases. If
this option is not given, the :prop_tgt:`SOURCES` property of the
specified ``target`` will be used to obtain the list of sources.
@@ -35,31 +74,30 @@ This module defines functions to help use the Google Test infrastructure.
Any extra arguments to pass on the command line to each test case.
``WORKING_DIRECTORY dir``
- Specifies the directory in which to run the discovered test cases. If this
+ Specifies the directory in which to run the discovered test cases. If this
option is not provided, the current binary directory is used.
``TEST_PREFIX prefix``
- Allows the specified ``prefix`` to be prepended to the name of each
- discovered test case. This can be useful when the same source files are
- being used in multiple calls to ``gtest_add_test()`` but with different
- ``EXTRA_ARGS``.
+ Specifies a ``prefix`` to be prepended to the name of each discovered test
+ case. This can be useful when the same source files are being used in
+ multiple calls to ``gtest_add_test()`` but with different ``EXTRA_ARGS``.
``TEST_SUFFIX suffix``
Similar to ``TEST_PREFIX`` except the ``suffix`` is appended to the name of
- every discovered test case. Both ``TEST_PREFIX`` and ``TEST_SUFFIX`` can be
- specified.
+ every discovered test case. Both ``TEST_PREFIX`` and ``TEST_SUFFIX`` may
+ be specified.
``SKIP_DEPENDENCY``
Normally, the function creates a dependency which will cause CMake to be
- re-run if any of the sources being scanned are changed. This is to ensure
- that the list of discovered tests is updated. If this behavior is not
+ re-run if any of the sources being scanned are changed. This is to ensure
+ that the list of discovered tests is updated. If this behavior is not
desired (as may be the case while actually writing the test cases), this
option can be used to prevent the dependency from being added.
``TEST_LIST outVar``
The variable named by ``outVar`` will be populated in the calling scope
- with the list of discovered test cases. This allows the caller to do things
- like manipulate test properties of the discovered tests.
+ with the list of discovered test cases. This allows the caller to do
+ things like manipulate test properties of the discovered tests.
.. code-block:: cmake
@@ -77,7 +115,7 @@ This module defines functions to help use the Google Test infrastructure.
set_tests_properties(${noArgsTests} PROPERTIES TIMEOUT 10)
set_tests_properties(${withArgsTests} PROPERTIES TIMEOUT 20)
- For backward compatibility reasons, the following form is also supported::
+ For backward compatibility, the following form is also supported::
gtest_add_tests(exe args files...)
@@ -99,8 +137,89 @@ This module defines functions to help use the Google Test infrastructure.
add_executable(FooTest FooUnitTest.cxx)
gtest_add_tests(FooTest "${FooTestArgs}" AUTO)
+.. command:: gtest_discover_tests
+
+ Automatically add tests with CTest by querying the compiled test executable
+ for available tests::
+
+ gtest_discover_tests(target
+ [EXTRA_ARGS arg1...]
+ [WORKING_DIRECTORY dir]
+ [TEST_PREFIX prefix]
+ [TEST_SUFFIX suffix]
+ [NO_PRETTY_TYPES] [NO_PRETTY_VALUES]
+ [PROPERTIES name1 value1...]
+ [TEST_LIST var]
+ )
+
+ ``gtest_discover_tests`` sets up a post-build command on the test executable
+ that generates the list of tests by parsing the output from running the test
+ with the ``--gtest_list_tests`` argument. Compared to the source parsing
+ approach of :command:`gtest_add_tests`, this ensures that the full list of
+ tests, including instantiations of parameterized tests, is obtained. Since
+ test discovery occurs at build time, it is not necessary to re-run CMake when
+ the list of tests changes.
+ However, it requires that :prop_tgt:`CROSSCOMPILING_EMULATOR` is properly set
+ in order to function in a cross-compiling environment.
+
+ Additionally, setting properties on tests is somewhat less convenient, since
+ the tests are not available at CMake time. Additional test properties may be
+ assigned to the set of tests as a whole using the ``PROPERTIES`` option. If
+ more fine-grained test control is needed, custom content may be provided
+ through an external CTest script using the :prop_dir:`TEST_INCLUDE_FILES`
+ directory property. The set of discovered tests is made accessible to such a
+ script via the ``<target>_TESTS`` variable.
+
+ The options are:
+
+ ``target``
+ Specifies the Google Test executable, which must be a known CMake
+ executable target. CMake will substitute the location of the built
+ executable when running the test.
+
+ ``EXTRA_ARGS arg1...``
+ Any extra arguments to pass on the command line to each test case.
+
+ ``WORKING_DIRECTORY dir``
+ Specifies the directory in which to run the discovered test cases. If this
+ option is not provided, the current binary directory is used.
+
+ ``TEST_PREFIX prefix``
+ Specifies a ``prefix`` to be prepended to the name of each discovered test
+ case. This can be useful when the same test executable is being used in
+ multiple calls to ``gtest_discover_tests()`` but with different
+ ``EXTRA_ARGS``.
+
+ ``TEST_SUFFIX suffix``
+ Similar to ``TEST_PREFIX`` except the ``suffix`` is appended to the name of
+ every discovered test case. Both ``TEST_PREFIX`` and ``TEST_SUFFIX`` may
+ be specified.
+
+ ``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
+ (e.g. because the type names are unwieldy), this option will suppress this
+ behavior.
+
+ ``NO_PRETTY_VALUES``
+ By default, the value index of value-parameterized tests is replaced by the
+ actual value in the CTest test name. If this behavior is undesirable
+ (e.g. because the value strings are unwieldy), this option will suppress
+ this behavior.
+
+ ``PROPERTIES name1 value1...``
+ Specifies additional properties to be set on all tests discovered by this
+ invocation of ``gtest_discover_tests``.
+
+ ``TEST_LIST var``
+ Make the list of tests available in the variable ``var``, rather than the
+ default ``<target>_TESTS``. This can be useful when the same test
+ executable is being used in multiple calls to ``gtest_discover_tests()``.
+ Note that this variable is only available in CTest.
+
#]=======================================================================]
+#------------------------------------------------------------------------------
function(gtest_add_tests)
if (ARGC LESS 1)
@@ -224,3 +343,68 @@ function(gtest_add_tests)
endif()
endfunction()
+
+#------------------------------------------------------------------------------
+function(gtest_discover_tests TARGET)
+ cmake_parse_arguments(
+ ""
+ "NO_PRETTY_TYPES;NO_PRETTY_VALUES"
+ "TEST_PREFIX;TEST_SUFFIX;WORKING_DIRECTORY;TEST_LIST"
+ "EXTRA_ARGS;PROPERTIES"
+ ${ARGN}
+ )
+
+ if(NOT _WORKING_DIRECTORY)
+ set(_WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}")
+ endif()
+ if(NOT _TEST_LIST)
+ set(_TEST_LIST ${TARGET}_TESTS)
+ endif()
+
+ # Define rule to generate test list for aforementioned test executable
+ set(ctest_include_file "${CMAKE_CURRENT_BINARY_DIR}/${TARGET}_include.cmake")
+ set(ctest_tests_file "${CMAKE_CURRENT_BINARY_DIR}/${TARGET}_tests.cmake")
+ get_property(crosscompiling_emulator
+ TARGET ${TARGET}
+ PROPERTY CROSSCOMPILING_EMULATOR
+ )
+ add_custom_command(
+ TARGET ${TARGET} POST_BUILD
+ BYPRODUCTS "${ctest_tests_file}"
+ COMMAND "${CMAKE_COMMAND}"
+ -D "TEST_TARGET=${TARGET}"
+ -D "TEST_EXECUTABLE=$<TARGET_FILE:${TARGET}>"
+ -D "TEST_EXECUTOR=${crosscompiling_emulator}"
+ -D "TEST_WORKING_DIR=${_WORKING_DIRECTORY}"
+ -D "TEST_EXTRA_ARGS=${_EXTRA_ARGS}"
+ -D "TEST_PROPERTIES=${_PROPERTIES}"
+ -D "TEST_PREFIX=${_TEST_PREFIX}"
+ -D "TEST_SUFFIX=${_TEST_SUFFIX}"
+ -D "NO_PRETTY_TYPES=${_NO_PRETTY_TYPES}"
+ -D "NO_PRETTY_VALUES=${_NO_PRETTY_VALUES}"
+ -D "TEST_LIST=${_TEST_LIST}"
+ -D "CTEST_FILE=${ctest_tests_file}"
+ -P "${_GOOGLETEST_DISCOVER_TESTS_SCRIPT}"
+ VERBATIM
+ )
+
+ file(WRITE "${ctest_include_file}"
+ "if(EXISTS \"${ctest_tests_file}\")\n"
+ " include(\"${ctest_tests_file}\")\n"
+ "else()\n"
+ " add_test(${TARGET}_NOT_BUILT ${TARGET}_NOT_BUILT)\n"
+ "endif()\n"
+ )
+
+ # Add discovered tests to directory TEST_INCLUDE_FILES
+ set_property(DIRECTORY
+ APPEND PROPERTY TEST_INCLUDE_FILES "${ctest_include_file}"
+ )
+
+endfunction()
+
+###############################################################################
+
+set(_GOOGLETEST_DISCOVER_TESTS_SCRIPT
+ ${CMAKE_CURRENT_LIST_DIR}/GoogleTestAddTests.cmake
+)
diff --git a/Modules/GoogleTestAddTests.cmake b/Modules/GoogleTestAddTests.cmake
new file mode 100644
index 000000000..7d0d9097b
--- /dev/null
+++ b/Modules/GoogleTestAddTests.cmake
@@ -0,0 +1,100 @@
+# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+# file Copyright.txt or https://cmake.org/licensing for details.
+
+set(prefix "${TEST_PREFIX}")
+set(suffix "${TEST_SUFFIX}")
+set(extra_args ${TEST_EXTRA_ARGS})
+set(properties ${TEST_PROPERTIES})
+set(script)
+set(suite)
+set(tests)
+
+function(add_command NAME)
+ set(_args "")
+ foreach(_arg ${ARGN})
+ if(_arg MATCHES "[^-./:a-zA-Z0-9_]")
+ set(_args "${_args} [==[${_arg}]==]")
+ else()
+ set(_args "${_args} ${_arg}")
+ endif()
+ endforeach()
+ set(script "${script}${NAME}(${_args})\n" PARENT_SCOPE)
+endfunction()
+
+# Run test executable to get list of available tests
+if(NOT EXISTS "${TEST_EXECUTABLE}")
+ message(FATAL_ERROR
+ "Specified test executable '${TEST_EXECUTABLE}' does not exist"
+ )
+endif()
+execute_process(
+ COMMAND ${TEST_EXECUTOR} "${TEST_EXECUTABLE}" --gtest_list_tests
+ OUTPUT_VARIABLE output
+ RESULT_VARIABLE result
+)
+if(NOT ${result} EQUAL 0)
+ message(FATAL_ERROR
+ "Error running test executable '${TEST_EXECUTABLE}':\n"
+ " Result: ${result}\n"
+ " Output: ${output}\n"
+ )
+endif()
+
+string(REPLACE "\n" ";" output "${output}")
+
+# Parse output
+foreach(line ${output})
+ # Skip header
+ if(NOT line MATCHES "gtest_main\\.cc")
+ # Do we have a module name or a test name?
+ if(NOT line MATCHES "^ ")
+ # Module; remove trailing '.' to get just the name...
+ string(REGEX REPLACE "\\.( *#.*)?" "" suite "${line}")
+ if(line MATCHES "#" AND NOT NO_PRETTY_TYPES)
+ string(REGEX REPLACE "/[0-9]\\.+ +#.*= +" "/" pretty_suite "${line}")
+ else()
+ set(pretty_suite "${suite}")
+ endif()
+ string(REGEX REPLACE "^DISABLED_" "" pretty_suite "${pretty_suite}")
+ else()
+ # Test name; strip spaces and comments to get just the name...
+ string(REGEX REPLACE " +" "" test "${line}")
+ if(test MATCHES "#" AND NOT NO_PRETTY_VALUES)
+ string(REGEX REPLACE "/[0-9]+#GetParam..=" "/" pretty_test "${test}")
+ else()
+ string(REGEX REPLACE "#.*" "" pretty_test "${test}")
+ endif()
+ string(REGEX REPLACE "^DISABLED_" "" pretty_test "${pretty_test}")
+ string(REGEX REPLACE "#.*" "" test "${test}")
+ # ...and add to script
+ add_command(add_test
+ "${prefix}${pretty_suite}.${pretty_test}${suffix}"
+ ${TEST_EXECUTOR}
+ "${TEST_EXECUTABLE}"
+ "--gtest_filter=${suite}.${test}"
+ "--gtest_also_run_disabled_tests"
+ ${extra_args}
+ )
+ if(suite MATCHES "^DISABLED" OR test MATCHES "^DISABLED")
+ add_command(set_tests_properties
+ "${prefix}${pretty_suite}.${pretty_test}${suffix}"
+ PROPERTIES DISABLED TRUE
+ )
+ endif()
+ add_command(set_tests_properties
+ "${prefix}${pretty_suite}.${pretty_test}${suffix}"
+ PROPERTIES
+ WORKING_DIRECTORY "${TEST_WORKING_DIR}"
+ ${properties}
+ )
+ list(APPEND tests "${prefix}${pretty_suite}.${pretty_test}${suffix}")
+ endif()
+ endif()
+endforeach()
+
+# Create a list of all discovered tests, which users may use to e.g. set
+# properties on the tests
+add_command(set ${TEST_LIST} ${tests})
+
+# Write CTest script
+file(WRITE "${CTEST_FILE}" "${script}")
diff --git a/Modules/InstallRequiredSystemLibraries.cmake b/Modules/InstallRequiredSystemLibraries.cmake
index 4e8713a08..1ba4877e6 100644
--- a/Modules/InstallRequiredSystemLibraries.cmake
+++ b/Modules/InstallRequiredSystemLibraries.cmake
@@ -56,6 +56,36 @@
# Specify the :command:`install(PROGRAMS)` command ``COMPONENT``
# option. If not specified, no such option will be used.
+set(_IRSL_HAVE_Intel FALSE)
+set(_IRSL_HAVE_MSVC FALSE)
+foreach(LANG IN ITEMS C CXX Fortran)
+ if(CMAKE_${LANG}_COMPILER_ID STREQUAL Intel)
+ if(NOT _IRSL_HAVE_Intel)
+ get_filename_component(_Intel_basedir "${CMAKE_${LANG}_COMPILER}" PATH)
+ if(CMAKE_SIZEOF_VOID_P EQUAL 8)
+ set(_Intel_archdir intel64)
+ else()
+ set(_Intel_archdir x86)
+ endif()
+ set(_Intel_compiler_ver ${CMAKE_${LANG}_COMPILER_VERSION})
+ if(WIN32)
+ get_filename_component(_Intel_redistdir "${_Intel_basedir}/../../redist/${_Intel_archdir}/compiler" ABSOLUTE)
+ elseif(APPLE)
+ get_filename_component(_Intel_redistdir "${_Intel_basedir}/../../compiler/lib" ABSOLUTE)
+ else()
+ if(EXISTS "${_Intel_basedir}/../lib/${_Intel_archdir}_lin")
+ get_filename_component(_Intel_redistdir "${_Intel_basedir}/../lib/${_Intel_archdir}" ABSOLUTE)
+ else()
+ get_filename_component(_Intel_redistdir "${_Intel_basedir}/../../compiler/lib/${_Intel_archdir}_lin" ABSOLUTE)
+ endif()
+ endif()
+ set(_IRSL_HAVE_Intel TRUE)
+ endif()
+ elseif(CMAKE_${LANG}_COMPILER_ID STREQUAL MSVC)
+ set(_IRSL_HAVE_MSVC TRUE)
+ endif()
+endforeach()
+
if(MSVC)
file(TO_CMAKE_PATH "$ENV{SYSTEMROOT}" SYSTEMROOT)
@@ -486,7 +516,7 @@ if(MSVC)
# MSVC 8 was the first version with OpenMP
# Furthermore, there is no debug version of this
- if(CMAKE_INSTALL_OPENMP_LIBRARIES)
+ if(CMAKE_INSTALL_OPENMP_LIBRARIES AND _IRSL_HAVE_MSVC)
set(_MSOMP_DLL_VERSION "")
set(_MSOMP_IDE_VERSION "")
if(MSVC_VERSION GREATER_EQUAL 2000)
@@ -545,6 +575,111 @@ if(MSVC)
endforeach()
endif()
+if(_IRSL_HAVE_Intel)
+ unset(__install_libs)
+ if(CMAKE_INSTALL_OPENMP_LIBRARIES)
+ if(WIN32)
+ list(APPEND __install_libs "${_Intel_redistdir}/libiomp5md.dll" "${_Intel_redistdir}/libiompstubs5md.dll")
+ elseif(APPLE)
+ list(APPEND __install_libs "${_Intel_redistdir}/libiomp5.dylib" "${_Intel_redistdir}/libiompstubs5.dylib")
+ else()
+ list(APPEND __install_libs "${_Intel_redistdir}/libiomp5.so" "${_Intel_redistdir}/libiompstubs5.so")
+ if(_Intel_compiler_ver VERSION_LESS 17)
+ list(APPEND __install_libs "${_Intel_redistdir}/libomp_db.so")
+ endif()
+ if(_Intel_compiler_ver VERSION_LESS 13)
+ list(APPEND __install_libs "${_Intel_redistdir}/libiompprof5.so")
+ endif()
+ endif()
+ endif()
+ if(WIN32)
+ set(__install_dirs "${_Intel_redistdir}/1033")
+ if(_Intel_compiler_ver VERSION_LESS 18)
+ list(APPEND __install_dirs "${_Intel_redistdir}/irml" "${_Intel_redistdir}/irml_c" "${_Intel_redistdir}/1041")
+ endif()
+ foreach(__Intel_lib IN ITEMS cilkrts20.dll libchkp.dll libgfxoffload.dll libioffload_host.dll libirngmd.dll
+ libmmd.dll libmmdd.dll libmpx.dll liboffload.dll svml_dispmd.dll)
+
+ list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}")
+ endforeach()
+ if(CMAKE_Fortran_COMPILER_ID STREQUAL Intel)
+ foreach(__Intel_lib IN ITEMS ifdlg100.dll libicaf.dll libifcoremd.dll libifcoremdd.dll libifcorert.dll libifcorertd.dll libifportmd.dll)
+
+ list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}")
+ endforeach()
+ endif()
+ elseif(APPLE)
+ foreach(__Intel_lib IN ITEMS libchkp.dylib libcilkrts.5.dylib libcilkrts.dylib libimf.dylib libintlc.dylib libirc.dylib libirng.dylib libsvml.dylib)
+ list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}")
+ endforeach()
+ if(_Intel_compiler_ver VERSION_LESS 17)
+ list(APPEND __install_libs "${_Intel_redistdir}/libistrconv.dylib")
+ endif()
+ if(CMAKE_Fortran_COMPILER_ID STREQUAL Intel)
+ foreach(__Intel_lib IN ITEMS libifcore.dylib libifcoremt.dylib libifport.dylib libifportmt.dylib)
+
+ list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}")
+ endforeach()
+ endif()
+ else()
+ set(__install_dirs "${_Intel_redistdir}/irml")
+ foreach(__Intel_lib IN ITEMS cilk_db.so libchkp.so libcilkrts.so libcilkrts.so.5 libimf.so libintlc.so libintlc.so.5 libirc.so libpdbx.so libpdbx.so.5 libsvml.so)
+
+ list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}")
+ endforeach()
+ if(_Intel_compiler_ver VERSION_GREATER_EQUAL 13)
+ foreach(__Intel_lib IN ITEMS libirng.so liboffload.so liboffload.so.5)
+
+ list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}")
+ endforeach()
+ endif()
+ if(_Intel_compiler_ver VERSION_GREATER_EQUAL 15)
+ foreach(__Intel_lib IN ITEMS libgfxoffload.so libistrconv.so)
+
+ list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}")
+ endforeach()
+ endif()
+ if(_Intel_compiler_ver VERSION_GREATER_EQUAL 16)
+ foreach(__Intel_lib IN ITEMS libioffload_host.so libioffload_host.so.5 libioffload_target.so libioffload_target.so.5 libmpx.so offload_main)
+
+ list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}")
+ endforeach()
+ endif()
+ if(_Intel_compiler_ver VERSION_LESS 15)
+ foreach(__Intel_lib IN ITEMS libcxaguard.so libcxaguard.so.5)
+
+ list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}")
+ endforeach()
+ endif()
+ if(CMAKE_Fortran_COMPILER_ID STREQUAL Intel)
+ foreach(__Intel_lib IN ITEMS libicaf.so libifcore.so libifcore.so.5 libifcoremt.so libifcoremt.so.5 libifport.so libifport.so.5)
+
+ list(APPEND __install_libs "${_Intel_redistdir}/${__Intel_lib}")
+ endforeach()
+ endif()
+ endif()
+
+ foreach(lib IN LISTS __install_libs)
+ if(EXISTS ${lib})
+ list(APPEND CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS ${lib})
+ else()
+ if(NOT CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS)
+ message(WARNING "system runtime library file does not exist: '${lib}'")
+ endif()
+ endif()
+ endforeach()
+
+ foreach(dir IN LISTS __install_dirs)
+ if(EXISTS ${dir})
+ list(APPEND CMAKE_INSTALL_SYSTEM_RUNTIME_DIRECTORIES ${dir})
+ else()
+ if(NOT CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS)
+ message(WARNING "system runtime library file does not exist: '${dir}'")
+ endif()
+ endif()
+ endforeach()
+endif()
+
if(WATCOM)
get_filename_component( CompilerPath ${CMAKE_C_COMPILER} PATH )
if(CMAKE_C_COMPILER_VERSION)
@@ -598,5 +733,10 @@ if(CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS)
DESTINATION ${CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION}
${_CMAKE_INSTALL_SYSTEM_RUNTIME_COMPONENT}
)
+
+ install(DIRECTORY ${CMAKE_INSTALL_SYSTEM_RUNTIME_DIRECTORIES}
+ DESTINATION ${CMAKE_INSTALL_SYSTEM_RUNTIME_DESTINATION}
+ ${_CMAKE_INSTALL_SYSTEM_RUNTIME_COMPONENT}
+ )
endif()
endif()
diff --git a/Modules/Platform/FreeBSD-Determine-CXX.cmake b/Modules/Platform/FreeBSD-Determine-CXX.cmake
new file mode 100644
index 000000000..b594daeb0
--- /dev/null
+++ b/Modules/Platform/FreeBSD-Determine-CXX.cmake
@@ -0,0 +1,3 @@
+if(NOT CMAKE_CXX_COMPILER_NAMES)
+ set(CMAKE_CXX_COMPILER_NAMES c++)
+endif()
diff --git a/Modules/Platform/GHS-MULTI-Initialize.cmake b/Modules/Platform/GHS-MULTI-Initialize.cmake
index fcda6f6c4..bf61d7b9d 100644
--- a/Modules/Platform/GHS-MULTI-Initialize.cmake
+++ b/Modules/Platform/GHS-MULTI-Initialize.cmake
@@ -10,7 +10,7 @@ if (NOT GHS_INT_DIRECTORY)
if (EXISTS ${GHS_EXPECTED_ROOT})
FILE(GLOB GHS_CANDIDATE_INT_DIRS RELATIVE
${GHS_EXPECTED_ROOT} ${GHS_EXPECTED_ROOT}/*)
- string(REGEX MATCHALL "int[0-9][0-9][0-9][0-9]" GHS_CANDIDATE_INT_DIRS
+ string(REGEX MATCHALL "int[0-9][0-9][0-9][0-9a-z]" GHS_CANDIDATE_INT_DIRS
${GHS_CANDIDATE_INT_DIRS})
if (GHS_CANDIDATE_INT_DIRS)
list(SORT GHS_CANDIDATE_INT_DIRS)
diff --git a/Modules/Platform/GNUtoMS_lib.bat.in b/Modules/Platform/GNUtoMS_lib.bat.in
index 2da920ab0..8613be359 100644
--- a/Modules/Platform/GNUtoMS_lib.bat.in
+++ b/Modules/Platform/GNUtoMS_lib.bat.in
@@ -1,3 +1,4 @@
@echo off
+set VSCMD_START_DIR=.
call "@CMAKE_GNUtoMS_BAT@"
lib /machine:"@CMAKE_GNUtoMS_ARCH@" %*
diff --git a/Modules/Platform/Generic-SDCC-C.cmake b/Modules/Platform/Generic-SDCC-C.cmake
index bbefe193e..4b3912af3 100644
--- a/Modules/Platform/Generic-SDCC-C.cmake
+++ b/Modules/Platform/Generic-SDCC-C.cmake
@@ -41,7 +41,7 @@ endif()
set(CMAKE_C_COMPILE_OBJECT "<CMAKE_C_COMPILER> <DEFINES> <INCLUDES> <FLAGS> -o <OBJECT> -c <SOURCE>")
# link object files to an executable
-set(CMAKE_C_LINK_EXECUTABLE "<CMAKE_C_COMPILER> <FLAGS> <OBJECTS> --out-fmt-ihx -o <TARGET> <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>")
+set(CMAKE_C_LINK_EXECUTABLE "<CMAKE_C_COMPILER> <FLAGS> <OBJECTS> -o <TARGET> <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <LINK_LIBRARIES>")
# needs sdcc 2.7.0 + sddclib from cvs
set(CMAKE_C_CREATE_STATIC_LIBRARY
diff --git a/Modules/Platform/Midipix.cmake b/Modules/Platform/Midipix.cmake
new file mode 100644
index 000000000..54a156b4d
--- /dev/null
+++ b/Modules/Platform/Midipix.cmake
@@ -0,0 +1 @@
+include(Platform/UnixPaths)
diff --git a/Modules/Platform/Windows-Clang-CXX.cmake b/Modules/Platform/Windows-Clang-CXX.cmake
index 2c3688a36..f1d40f265 100644
--- a/Modules/Platform/Windows-Clang-CXX.cmake
+++ b/Modules/Platform/Windows-Clang-CXX.cmake
@@ -1,2 +1,3 @@
include(Platform/Windows-Clang)
+set(_COMPILE_CXX_MSVC " -TP")
__windows_compiler_clang(CXX)
diff --git a/Modules/Platform/Windows-Clang.cmake b/Modules/Platform/Windows-Clang.cmake
index bcfda93cd..007ae530d 100644
--- a/Modules/Platform/Windows-Clang.cmake
+++ b/Modules/Platform/Windows-Clang.cmake
@@ -12,6 +12,7 @@ if("x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC"
OR "x${CMAKE_CXX_SIMULATE_ID}" STREQUAL "xMSVC")
include(Platform/Windows-MSVC)
macro(__windows_compiler_clang lang)
+ set(_COMPILE_${lang} "${_COMPILE_${lang}_MSVC}")
__windows_compiler_msvc(${lang})
endmacro()
else()
diff --git a/Modules/Platform/Windows-MSVC.cmake b/Modules/Platform/Windows-MSVC.cmake
index cfe6e1c21..4719563cc 100644
--- a/Modules/Platform/Windows-MSVC.cmake
+++ b/Modules/Platform/Windows-MSVC.cmake
@@ -122,7 +122,9 @@ set(CMAKE_BUILD_TYPE_INIT Debug)
# Compute an architecture family from the architecture id.
foreach(lang C CXX)
set(_MSVC_${lang}_ARCHITECTURE_FAMILY "${MSVC_${lang}_ARCHITECTURE_ID}")
- if(_MSVC_${lang}_ARCHITECTURE_FAMILY MATCHES "^ARM")
+ if(_MSVC_${lang}_ARCHITECTURE_FAMILY MATCHES "^ARM64")
+ set(_MSVC_${lang}_ARCHITECTURE_FAMILY "ARM64")
+ elseif(_MSVC_${lang}_ARCHITECTURE_FAMILY MATCHES "^ARM")
set(_MSVC_${lang}_ARCHITECTURE_FAMILY "ARM")
elseif(_MSVC_${lang}_ARCHITECTURE_FAMILY MATCHES "^SH")
set(_MSVC_${lang}_ARCHITECTURE_FAMILY "SHx")
@@ -175,7 +177,7 @@ elseif(WINDOWS_PHONE OR WINDOWS_STORE)
set(CMAKE_C_STANDARD_LIBRARIES_INIT "WindowsApp.lib")
elseif(WINDOWS_PHONE)
set(CMAKE_C_STANDARD_LIBRARIES_INIT "WindowsPhoneCore.lib RuntimeObject.lib PhoneAppModelHost.lib")
- elseif(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM")
+ elseif(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM64" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM64")
set(CMAKE_C_STANDARD_LIBRARIES_INIT "kernel32.lib user32.lib")
else()
set(CMAKE_C_STANDARD_LIBRARIES_INIT "kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib")
@@ -183,10 +185,10 @@ elseif(WINDOWS_PHONE OR WINDOWS_STORE)
else()
set(_PLATFORM_DEFINES "/DWIN32")
- if(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM")
+ if(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM" OR _MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM64" OR _MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM64")
set(CMAKE_C_STANDARD_LIBRARIES_INIT "kernel32.lib user32.lib")
elseif(MSVC_VERSION GREATER 1310)
- if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "(v[0-9]+_clang_.*|LLVM-vs[0-9]+.*)")
+ if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "v[0-9]+_clang_.*")
# Clang/C2 in MSVC14 Update 1 seems to not support -fsantinize (yet?)
# set(_RTC1 "-fsantinize=memory,safe-stack")
set(_FLAGS_CXX " -frtti -fexceptions")
@@ -215,6 +217,8 @@ set (CMAKE_LINK_DEF_FILE_FLAG "/DEF:")
if(MSVC_C_ARCHITECTURE_ID)
if(MSVC_C_ARCHITECTURE_ID MATCHES "^ARMV.I")
set(_MACHINE_ARCH_FLAG "/machine:THUMB")
+ elseif(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM64")
+ set(_MACHINE_ARCH_FLAG "/machine:ARM64")
elseif(_MSVC_C_ARCHITECTURE_FAMILY STREQUAL "ARM")
set(_MACHINE_ARCH_FLAG "/machine:ARM")
else()
@@ -223,6 +227,8 @@ if(MSVC_C_ARCHITECTURE_ID)
elseif(MSVC_CXX_ARCHITECTURE_ID)
if(MSVC_CXX_ARCHITECTURE_ID MATCHES "^ARMV.I")
set(_MACHINE_ARCH_FLAG "/machine:THUMB")
+ elseif(_MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM64")
+ set(_MACHINE_ARCH_FLAG "/machine:ARM64")
elseif(_MSVC_CXX_ARCHITECTURE_FAMILY STREQUAL "ARM")
set(_MACHINE_ARCH_FLAG "/machine:ARM")
else()
@@ -285,7 +291,7 @@ macro(__windows_compiler_msvc lang)
if("x${lang}" STREQUAL "xC" OR
"x${lang}" STREQUAL "xCXX")
- if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "(v[0-9]+_clang_.*|LLVM-vs[0-9]+.*)")
+ if(CMAKE_VS_PLATFORM_TOOLSET MATCHES "v[0-9]+_clang_.*")
# note: MSVC 14 2015 Update 1 sets -fno-ms-compatibility by default, but this does not allow one to compile many projects
# that include MS's own headers. CMake itself is affected project too.
string(APPEND CMAKE_${lang}_FLAGS_INIT " ${_PLATFORM_DEFINES}${_PLATFORM_DEFINES_${lang}} -fms-extensions -fms-compatibility -D_WINDOWS -Wall${_FLAGS_${lang}}")
diff --git a/Modules/Platform/Windows-NMcl.cmake b/Modules/Platform/Windows-NMcl.cmake
deleted file mode 100644
index 7add0b060..000000000
--- a/Modules/Platform/Windows-NMcl.cmake
+++ /dev/null
@@ -1,4 +0,0 @@
-# this is for the numega compiler which is really a front
-# end for visual studio, but adds memory checking code.
-
-include(Platform/Windows-cl)
diff --git a/Modules/Squish4RunTestCase.bat b/Modules/Squish4RunTestCase.bat
index ad1cc8c3b..c6582085a 100755
--- a/Modules/Squish4RunTestCase.bat
+++ b/Modules/Squish4RunTestCase.bat
@@ -1,24 +1,24 @@
-set SQUISHSERVER=%1
-set SQUISHRUNNER=%2
-set TESTSUITE=%3
-set TESTCASE=%4
-set AUT=%5
-set AUTDIR=%6
-set SETTINGSGROUP=%7
-
-%SQUISHSERVER% --stop
-
-echo "Adding AUT... %SQUISHSERVER% --config addAUT %AUT% %AUTDIR%"
-%SQUISHSERVER% --config addAUT "%AUT%" "%AUTDIR%"
-
-echo "Starting the squish server... %SQUISHSERVER%"
-start /B %SQUISHSERVER%
-
-echo "Running the test case...%SQUISHRUNNER% --testsuite %TESTSUITE% --testcase %TESTCASE%"
-%SQUISHRUNNER% --testsuite "%TESTSUITE%" --testcase "%TESTCASE%"
-set returnValue=%ERRORLEVEL%
-
-echo "Stopping the squish server... %SQUISHSERVER% --stop"
-%SQUISHSERVER% --stop
-
-exit /B %returnValue%
+set SQUISHSERVER=%1
+set SQUISHRUNNER=%2
+set TESTSUITE=%3
+set TESTCASE=%4
+set AUT=%5
+set AUTDIR=%6
+set SETTINGSGROUP=%7
+
+%SQUISHSERVER% --stop
+
+echo "Adding AUT... %SQUISHSERVER% --config addAUT %AUT% %AUTDIR%"
+%SQUISHSERVER% --config addAUT "%AUT%" "%AUTDIR%"
+
+echo "Starting the squish server... %SQUISHSERVER%"
+start /B %SQUISHSERVER%
+
+echo "Running the test case...%SQUISHRUNNER% --testsuite %TESTSUITE% --testcase %TESTCASE%"
+%SQUISHRUNNER% --testsuite "%TESTSUITE%" --testcase "%TESTCASE%"
+set returnValue=%ERRORLEVEL%
+
+echo "Stopping the squish server... %SQUISHSERVER% --stop"
+%SQUISHSERVER% --stop
+
+exit /B %returnValue%
diff --git a/Modules/UseSWIG.cmake b/Modules/UseSWIG.cmake
index fc815ddf8..c8b1cd7c4 100644
--- a/Modules/UseSWIG.cmake
+++ b/Modules/UseSWIG.cmake
@@ -82,10 +82,6 @@ macro(SWIG_MODULE_INITIALIZE name language)
set(SWIG_MODULE_${name}_REAL_NAME "_${name}")
elseif("x${SWIG_MODULE_${name}_LANGUAGE}" STREQUAL "xPERL")
set(SWIG_MODULE_${name}_EXTRA_FLAGS "-shadow")
- elseif("x${SWIG_MODULE_${name}_LANGUAGE}" STREQUAL "xCSHARP")
- # This makes sure that the name used in the generated DllImport
- # matches the library name created by CMake
- set(SWIG_MODULE_${name}_EXTRA_FLAGS "-dllimport;${name}")
endif()
endmacro()
@@ -194,6 +190,13 @@ macro(SWIG_ADD_SOURCE_TO_MODULE name outfiles infile)
if(swig_source_file_cplusplus)
set(swig_special_flags ${swig_special_flags} "-c++")
endif()
+ if("x${SWIG_MODULE_${name}_LANGUAGE}" STREQUAL "xCSHARP")
+ if(NOT ";${swig_source_file_flags};${CMAKE_SWIG_FLAGS};" MATCHES ";-dllimport;")
+ # This makes sure that the name used in the generated DllImport
+ # matches the library name created by CMake
+ set(SWIG_MODULE_${name}_EXTRA_FLAGS "-dllimport;${name}")
+ endif()
+ endif()
set(swig_extra_flags)
if(SWIG_MODULE_${name}_EXTRA_FLAGS)
set(swig_extra_flags ${swig_extra_flags} ${SWIG_MODULE_${name}_EXTRA_FLAGS})
diff --git a/README.rst b/README.rst
index d5acd4a7c..3cef06d89 100644
--- a/README.rst
+++ b/README.rst
@@ -36,7 +36,7 @@ Supported Platforms
* FreeBSD
* OpenBSD
* Solaris
-* HP-UX
+* AIX
Other UNIX-like operating systems may work too out of the box, if not
it should not be a major problem to port CMake to this platform.
@@ -51,7 +51,7 @@ Building CMake from Scratch
UNIX/Mac OSX/MinGW/MSYS/Cygwin
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-You need to have a compiler and a make installed.
+You need to have a C++ compiler (supporting C++11) and a ``make`` installed.
Run the ``bootstrap`` script you find in the source directory of CMake.
You can use the ``--help`` option to see the supported options.
You may use the ``--prefix=<install_prefix>`` option to specify a custom
diff --git a/Source/.gitattributes b/Source/.gitattributes
deleted file mode 100644
index 0f829a368..000000000
--- a/Source/.gitattributes
+++ /dev/null
@@ -1,2 +0,0 @@
-# Do not format third-party sources.
-/kwsys/** -format.clang-format
diff --git a/Source/CMakeLists.txt b/Source/CMakeLists.txt
index 40403ca25..a4dd91860 100644
--- a/Source/CMakeLists.txt
+++ b/Source/CMakeLists.txt
@@ -307,8 +307,9 @@ set(SRCS
cmPropertyDefinitionMap.h
cmPropertyMap.cxx
cmPropertyMap.h
- cmQtAutoGeneratorCommon.cxx
- cmQtAutoGeneratorCommon.h
+ cmQtAutoGen.cxx
+ cmQtAutoGen.h
+ cmQtAutoGenDigest.h
cmQtAutoGeneratorInitializer.cxx
cmQtAutoGeneratorInitializer.h
cmQtAutoGenerators.cxx
@@ -469,6 +470,8 @@ set(SRCS
cmIncludeDirectoryCommand.h
cmIncludeExternalMSProjectCommand.cxx
cmIncludeExternalMSProjectCommand.h
+ cmIncludeGuardCommand.cxx
+ cmIncludeGuardCommand.h
cmIncludeRegularExpressionCommand.cxx
cmIncludeRegularExpressionCommand.h
cmInstallCommand.cxx
@@ -584,7 +587,6 @@ set(SRCS
cmWriteFileCommand.cxx
cmWriteFileCommand.h
- cm_auto_ptr.hxx
cm_get_date.h
cm_get_date.c
cm_utf8.h
@@ -777,6 +779,8 @@ if(WIN32 AND NOT UNIX)
target_link_libraries(CMakeLib rpcrt4 crypt32)
endif()
+target_compile_definitions(CMakeLib PUBLIC ${CLANG_TIDY_DEFINITIONS})
+
#
# CTestLib
#
@@ -874,6 +878,7 @@ set(CPACK_SRCS
CPack/cmCPackTarCompressGenerator.cxx
CPack/cmCPackZIPGenerator.cxx
CPack/cmCPack7zGenerator.cxx
+ CPack/cmCPackDebGenerator.cxx
)
# CPack IFW generator
set(CPACK_SRCS ${CPACK_SRCS}
@@ -896,11 +901,39 @@ if(CYGWIN)
)
endif()
+option(CPACK_ENABLE_FREEBSD_PKG "Add FreeBSD pkg(8) generator to CPack." OFF)
+
if(UNIX)
set(CPACK_SRCS ${CPACK_SRCS}
- CPack/cmCPackDebGenerator.cxx
CPack/cmCPackRPMGenerator.cxx
)
+
+ # Optionally, try to use pkg(8)
+ if(CPACK_ENABLE_FREEBSD_PKG)
+ # On UNIX, you may find FreeBSD's pkg(8) and attendant
+ # library -- it can be used on FreeBSD, Dragonfly, NetBSD,
+ # OpenBSD and also Linux and OSX. Look for the header and
+ # the library; it's a warning on FreeBSD if they're not
+ # found, and informational on other platforms.
+ find_path(FREEBSD_PKG_INCLUDE_DIRS "pkg.h" PATHS /usr/local)
+ if(FREEBSD_PKG_INCLUDE_DIRS)
+ find_library(FREEBSD_PKG_LIBRARIES
+ pkg
+ DOC "FreeBSD pkg(8) library")
+ if(FREEBSD_PKG_LIBRARIES)
+ set(CPACK_SRCS ${CPACK_SRCS}
+ CPack/cmCPackFreeBSDGenerator.cxx
+ )
+ endif()
+ endif()
+
+ if (NOT FREEBSD_PKG_INCLUDE_DIRS OR NOT FREEBSD_PKG_LIBRARIES)
+ message(FATAL_ERROR "CPack needs libpkg(3) to produce FreeBSD packages natively.")
+ endif()
+ else()
+ set(FREEBSD_PKG_INCLUDE_DIRS NOTFOUND)
+ set(FREEBSD_PKG_LIBRARIES NOTFOUND)
+ endif()
endif()
if(WIN32)
@@ -958,6 +991,11 @@ if(APPLE)
"See CMakeFiles/CMakeError.log for details of the failure.")
endif()
endif()
+if(CPACK_ENABLE_FREEBSD_PKG AND FREEBSD_PKG_INCLUDE_DIRS AND FREEBSD_PKG_LIBRARIES)
+ target_link_libraries(CPackLib ${FREEBSD_PKG_LIBRARIES})
+ include_directories(${FREEBSD_PKG_INCLUDE_DIRS})
+ add_definitions(-DHAVE_FREEBSD_PKG)
+endif()
if(APPLE)
add_executable(cmakexbuild cmakexbuild.cxx)
@@ -974,18 +1012,16 @@ add_executable(cmake cmakemain.cxx cmcmd.cxx cmcmd.h ${MANIFEST_FILE})
list(APPEND _tools cmake)
target_link_libraries(cmake CMakeLib)
-if(CMake_ENABLE_SERVER_MODE)
- add_library(CMakeServerLib
- cmFileMonitor.cxx cmFileMonitor.h
- cmServer.cxx cmServer.h
- cmServerConnection.cxx cmServerConnection.h
- cmServerProtocol.cxx cmServerProtocol.h
- )
- target_link_libraries(CMakeServerLib CMakeLib)
- set_property(SOURCE cmcmd.cxx APPEND PROPERTY COMPILE_DEFINITIONS HAVE_SERVER_MODE=1)
-
- target_link_libraries(cmake CMakeServerLib)
-endif()
+add_library(CMakeServerLib
+ cmConnection.h cmConnection.cxx
+ cmFileMonitor.cxx cmFileMonitor.h
+ cmPipeConnection.cxx cmPipeConnection.h
+ cmServer.cxx cmServer.h
+ cmServerConnection.cxx cmServerConnection.h
+ cmServerProtocol.cxx cmServerProtocol.h
+ )
+target_link_libraries(CMakeServerLib CMakeLib)
+target_link_libraries(cmake CMakeServerLib)
# Build CTest executable
add_executable(ctest ctest.cxx ${MANIFEST_FILE})
diff --git a/Source/CMakeVersion.cmake b/Source/CMakeVersion.cmake
index 5bd328ee3..8a93c36ca 100644
--- a/Source/CMakeVersion.cmake
+++ b/Source/CMakeVersion.cmake
@@ -1,5 +1,5 @@
# CMake version number components.
set(CMake_VERSION_MAJOR 3)
-set(CMake_VERSION_MINOR 9)
-set(CMake_VERSION_PATCH 6)
+set(CMake_VERSION_MINOR 10)
+set(CMake_VERSION_PATCH 0)
#set(CMake_VERSION_RC 0)
diff --git a/Source/CPack/IFW/cmCPackIFWCommon.cxx b/Source/CPack/IFW/cmCPackIFWCommon.cxx
index e8f05bd50..1e7264156 100644
--- a/Source/CPack/IFW/cmCPackIFWCommon.cxx
+++ b/Source/CPack/IFW/cmCPackIFWCommon.cxx
@@ -15,14 +15,14 @@
#include <vector>
cmCPackIFWCommon::cmCPackIFWCommon()
- : Generator(CM_NULLPTR)
+ : Generator(nullptr)
{
}
const char* cmCPackIFWCommon::GetOption(const std::string& op) const
{
return this->Generator ? this->Generator->cmCPackGenerator::GetOption(op)
- : CM_NULLPTR;
+ : nullptr;
}
bool cmCPackIFWCommon::IsOn(const std::string& op) const
diff --git a/Source/CPack/IFW/cmCPackIFWGenerator.cxx b/Source/CPack/IFW/cmCPackIFWGenerator.cxx
index 226ea0a29..825a88804 100644
--- a/Source/CPack/IFW/cmCPackIFWGenerator.cxx
+++ b/Source/CPack/IFW/cmCPackIFWGenerator.cxx
@@ -49,10 +49,22 @@ int cmCPackIFWGenerator::PackageFiles()
ifwCmd += " -p " + this->toplevel + "/packages";
if (!this->PkgsDirsVector.empty()) {
- for (std::vector<std::string>::iterator it =
- this->PkgsDirsVector.begin();
- it != this->PkgsDirsVector.end(); ++it) {
- ifwCmd += " -p " + *it;
+ for (std::string const& it : this->PkgsDirsVector) {
+ ifwCmd += " -p " + it;
+ }
+ }
+
+ if (!this->RepoDirsVector.empty()) {
+ if (!this->IsVersionLess("3.1")) {
+ for (std::string const& rd : this->RepoDirsVector) {
+ ifwCmd += " --repository " + rd;
+ }
+ } else {
+ cmCPackIFWLogger(WARNING, "The \"CPACK_IFW_REPOSITORIES_DIRECTORIES\" "
+ << "variable is set, but content will be skiped, "
+ << "because this feature available only since "
+ << "QtIFW 3.1. Please update your QtIFW instance."
+ << std::endl);
}
}
@@ -73,7 +85,7 @@ int cmCPackIFWGenerator::PackageFiles()
int retVal = 1;
cmCPackIFWLogger(OUTPUT, "- Generate repository" << std::endl);
bool res = cmSystemTools::RunSingleCommand(ifwCmd.c_str(), &output,
- &output, &retVal, CM_NULLPTR,
+ &output, &retVal, nullptr,
this->GeneratorVerbose, 0);
if (!res || retVal) {
cmGeneratedFileStream ofs(ifwTmpFile.c_str());
@@ -121,10 +133,22 @@ int cmCPackIFWGenerator::PackageFiles()
ifwCmd += " -p " + this->toplevel + "/packages";
if (!this->PkgsDirsVector.empty()) {
- for (std::vector<std::string>::iterator it =
- this->PkgsDirsVector.begin();
- it != this->PkgsDirsVector.end(); ++it) {
- ifwCmd += " -p " + *it;
+ for (std::string const& it : this->PkgsDirsVector) {
+ ifwCmd += " -p " + it;
+ }
+ }
+
+ if (!this->RepoDirsVector.empty()) {
+ if (!this->IsVersionLess("3.1")) {
+ for (std::string const& rd : this->RepoDirsVector) {
+ ifwCmd += " --repository " + rd;
+ }
+ } else {
+ cmCPackIFWLogger(WARNING, "The \"CPACK_IFW_REPOSITORIES_DIRECTORIES\" "
+ << "variable is set, but content will be skipped, "
+ << "because this feature available only since "
+ << "QtIFW 3.1. Please update your QtIFW instance."
+ << std::endl);
}
}
@@ -164,13 +188,14 @@ int cmCPackIFWGenerator::PackageFiles()
ifwCmd += " " + this->packageFileNames[0];
} else {
ifwCmd += " installer";
+ ifwCmd += this->OutputExtension;
}
cmCPackIFWLogger(VERBOSE, "Execute: " << ifwCmd << std::endl);
std::string output;
int retVal = 1;
cmCPackIFWLogger(OUTPUT, "- Generate package" << std::endl);
bool res = cmSystemTools::RunSingleCommand(ifwCmd.c_str(), &output,
- &output, &retVal, CM_NULLPTR,
+ &output, &retVal, nullptr,
this->GeneratorVerbose, 0);
if (!res || retVal) {
cmGeneratedFileStream ofs(ifwTmpFile.c_str());
@@ -205,7 +230,7 @@ const char* cmCPackIFWGenerator::GetPackagingInstallPrefix()
const char* cmCPackIFWGenerator::GetOutputExtension()
{
- return this->ExecutableSuffix.c_str();
+ return this->OutputExtension.c_str();
}
int cmCPackIFWGenerator::InitializeInternal()
@@ -225,7 +250,7 @@ int cmCPackIFWGenerator::InitializeInternal()
const char* BinCreatorStr = this->GetOption(BinCreatorOpt);
if (!BinCreatorStr || cmSystemTools::IsNOTFOUND(BinCreatorStr)) {
- this->BinCreator = "";
+ this->BinCreator.clear();
} else {
this->BinCreator = BinCreatorStr;
}
@@ -241,7 +266,7 @@ int cmCPackIFWGenerator::InitializeInternal()
const char* RepoGenStr = this->GetOption(RepoGenOpt);
if (!RepoGenStr || cmSystemTools::IsNOTFOUND(RepoGenStr)) {
- this->RepoGen = "";
+ this->RepoGen.clear();
} else {
this->RepoGen = RepoGenStr;
}
@@ -265,6 +290,13 @@ int cmCPackIFWGenerator::InitializeInternal()
cmSystemTools::ExpandListArgument(dirs, this->PkgsDirsVector);
}
+ // Additional repositories dirs
+ this->RepoDirsVector.clear();
+ if (const char* dirs =
+ this->GetOption("CPACK_IFW_REPOSITORIES_DIRECTORIES")) {
+ cmSystemTools::ExpandListArgument(dirs, this->RepoDirsVector);
+ }
+
// Installer
this->Installer.Generator = this;
this->Installer.ConfigureFromOptions();
@@ -281,9 +313,8 @@ int cmCPackIFWGenerator::InitializeInternal()
if (const char* RepoAllStr = this->GetOption("CPACK_IFW_REPOSITORIES_ALL")) {
std::vector<std::string> RepoAllVector;
cmSystemTools::ExpandListArgument(RepoAllStr, RepoAllVector);
- for (std::vector<std::string>::iterator rit = RepoAllVector.begin();
- rit != RepoAllVector.end(); ++rit) {
- this->GetRepository(*rit);
+ for (std::string const& r : RepoAllVector) {
+ this->GetRepository(r);
}
}
@@ -305,16 +336,29 @@ int cmCPackIFWGenerator::InitializeInternal()
}
// Executable suffix
- if (const char* optExeSuffix = this->GetOption("CMAKE_EXECUTABLE_SUFFIX")) {
- this->ExecutableSuffix = optExeSuffix;
- if (this->ExecutableSuffix.empty()) {
- std::string sysName(this->GetOption("CMAKE_SYSTEM_NAME"));
- if (sysName == "Linux") {
- this->ExecutableSuffix = ".run";
- }
- }
+ std::string exeSuffix(this->GetOption("CMAKE_EXECUTABLE_SUFFIX"));
+ std::string sysName(this->GetOption("CMAKE_SYSTEM_NAME"));
+ if (sysName == "Linux") {
+ this->ExecutableSuffix = ".run";
+ } else if (sysName == "Windows") {
+ this->ExecutableSuffix = ".exe";
+ } else if (sysName == "Darwin") {
+ this->ExecutableSuffix = ".app";
} else {
- this->ExecutableSuffix = this->cmCPackGenerator::GetOutputExtension();
+ this->ExecutableSuffix = exeSuffix;
+ }
+
+ // Output extension
+ if (const char* optOutExt =
+ this->GetOption("CPACK_IFW_PACKAGE_FILE_EXTENSION")) {
+ this->OutputExtension = optOutExt;
+ } else if (sysName == "Darwin") {
+ this->OutputExtension = ".dmg";
+ } else {
+ this->OutputExtension = this->ExecutableSuffix;
+ }
+ if (this->OutputExtension.empty()) {
+ this->OutputExtension = this->cmCPackGenerator::GetOutputExtension();
}
return this->Superclass::InitializeInternal();
@@ -520,7 +564,7 @@ cmCPackIFWPackage* cmCPackIFWGenerator::GetGroupPackage(
{
std::map<cmCPackComponentGroup*, cmCPackIFWPackage*>::const_iterator pit =
this->GroupPackages.find(group);
- return pit != this->GroupPackages.end() ? pit->second : CM_NULLPTR;
+ return pit != this->GroupPackages.end() ? pit->second : nullptr;
}
cmCPackIFWPackage* cmCPackIFWGenerator::GetComponentPackage(
@@ -528,7 +572,7 @@ cmCPackIFWPackage* cmCPackIFWGenerator::GetComponentPackage(
{
std::map<cmCPackComponent*, cmCPackIFWPackage*>::const_iterator pit =
this->ComponentPackages.find(component);
- return pit != this->ComponentPackages.end() ? pit->second : CM_NULLPTR;
+ return pit != this->ComponentPackages.end() ? pit->second : nullptr;
}
cmCPackIFWRepository* cmCPackIFWGenerator::GetRepository(
@@ -550,7 +594,7 @@ cmCPackIFWRepository* cmCPackIFWGenerator::GetRepository(
}
} else {
this->Repositories.erase(repositoryName);
- repository = CM_NULLPTR;
+ repository = nullptr;
cmCPackIFWLogger(WARNING, "Invalid repository \""
<< repositoryName << "\""
<< " configuration. Repository will be skipped."
diff --git a/Source/CPack/IFW/cmCPackIFWGenerator.h b/Source/CPack/IFW/cmCPackIFWGenerator.h
index 8348ceeec..919dd4678 100644
--- a/Source/CPack/IFW/cmCPackIFWGenerator.h
+++ b/Source/CPack/IFW/cmCPackIFWGenerator.h
@@ -47,7 +47,7 @@ public:
/**
* Destruct IFW generator
*/
- ~cmCPackIFWGenerator() CM_OVERRIDE;
+ ~cmCPackIFWGenerator() override;
protected:
// cmCPackGenerator reimplementation
@@ -56,18 +56,18 @@ protected:
* @brief Initialize generator
* @return 0 on failure
*/
- int InitializeInternal() CM_OVERRIDE;
- int PackageFiles() CM_OVERRIDE;
- const char* GetPackagingInstallPrefix() CM_OVERRIDE;
+ int InitializeInternal() override;
+ int PackageFiles() override;
+ const char* GetPackagingInstallPrefix() override;
/**
- * @brief Extension of binary installer
- * @return Executable suffix or value from default implementation
+ * @brief Target binary extension
+ * @return Executable suffix or disk image format
*/
- const char* GetOutputExtension() CM_OVERRIDE;
+ const char* GetOutputExtension() override;
std::string GetComponentInstallDirNameSuffix(
- const std::string& componentName) CM_OVERRIDE;
+ const std::string& componentName) override;
/**
* @brief Get Component
@@ -79,7 +79,7 @@ protected:
* @return Pointer to component
*/
cmCPackComponent* GetComponent(const std::string& projectName,
- const std::string& componentName) CM_OVERRIDE;
+ const std::string& componentName) override;
/**
* @brief Get group of component
@@ -91,12 +91,12 @@ protected:
* @return Pointer to component group
*/
cmCPackComponentGroup* GetComponentGroup(
- const std::string& projectName, const std::string& groupName) CM_OVERRIDE;
+ const std::string& projectName, const std::string& groupName) override;
- enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() const
- CM_OVERRIDE;
- bool SupportsAbsoluteDestination() const CM_OVERRIDE;
- bool SupportsComponentInstallation() const CM_OVERRIDE;
+ enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir()
+ const override;
+ bool SupportsAbsoluteDestination() const override;
+ bool SupportsComponentInstallation() const override;
protected:
// Methods
@@ -143,10 +143,12 @@ private:
std::string BinCreator;
std::string FrameworkVersion;
std::string ExecutableSuffix;
+ std::string OutputExtension;
bool OnlineOnly;
bool ResolveDuplicateNames;
std::vector<std::string> PkgsDirsVector;
+ std::vector<std::string> RepoDirsVector;
};
#endif
diff --git a/Source/CPack/IFW/cmCPackIFWInstaller.cxx b/Source/CPack/IFW/cmCPackIFWInstaller.cxx
index 288e924e5..422f5d5e7 100644
--- a/Source/CPack/IFW/cmCPackIFWInstaller.cxx
+++ b/Source/CPack/IFW/cmCPackIFWInstaller.cxx
@@ -262,7 +262,7 @@ public:
std::string path, basePath;
protected:
- void StartElement(const std::string& name, const char** /*atts*/) CM_OVERRIDE
+ void StartElement(const std::string& name, const char** /*atts*/) override
{
this->file = name == "file";
if (file) {
@@ -270,7 +270,7 @@ protected:
}
}
- void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
+ void CharacterDataHandler(const char* data, int length) override
{
if (this->file) {
std::string content(data, data + length);
@@ -284,7 +284,7 @@ protected:
}
}
- void EndElement(const std::string& /*name*/) CM_OVERRIDE {}
+ void EndElement(const std::string& /*name*/) override {}
};
void cmCPackIFWInstaller::GenerateInstallerFile()
@@ -406,9 +406,8 @@ void cmCPackIFWInstaller::GenerateInstallerFile()
// Remote repositories
if (!this->RemoteRepositories.empty()) {
xout.StartElement("RemoteRepositories");
- for (RepositoriesVector::iterator rit = this->RemoteRepositories.begin();
- rit != this->RemoteRepositories.end(); ++rit) {
- (*rit)->WriteRepositoryConfig(xout);
+ for (cmCPackIFWRepository* r : this->RemoteRepositories) {
+ r->WriteRepositoryConfig(xout);
}
xout.EndElement();
}
@@ -492,9 +491,8 @@ void cmCPackIFWInstaller::GeneratePackageFiles()
}
// Generate packages meta information
- for (PackagesMap::iterator pit = this->Packages.begin();
- pit != this->Packages.end(); ++pit) {
- cmCPackIFWPackage* package = pit->second;
+ for (auto& p : this->Packages) {
+ cmCPackIFWPackage* package = p.second;
package->GeneratePackageFile();
}
}
diff --git a/Source/CPack/IFW/cmCPackIFWPackage.cxx b/Source/CPack/IFW/cmCPackIFWPackage.cxx
index c5311c31c..d3ce15c86 100644
--- a/Source/CPack/IFW/cmCPackIFWPackage.cxx
+++ b/Source/CPack/IFW/cmCPackIFWPackage.cxx
@@ -92,7 +92,7 @@ std::string cmCPackIFWPackage::DependenceStruct::NameWithCompare() const
//------------------------------------------------------ cmCPackIFWPackage ---
cmCPackIFWPackage::cmCPackIFWPackage()
- : Installer(CM_NULLPTR)
+ : Installer(nullptr)
{
}
@@ -111,19 +111,19 @@ void cmCPackIFWPackage::DefaultConfiguration()
{
this->DisplayName.clear();
this->Description.clear();
- this->Version = "";
- this->ReleaseDate = "";
- this->Script = "";
+ this->Version.clear();
+ this->ReleaseDate.clear();
+ this->Script.clear();
this->Licenses.clear();
this->UserInterfaces.clear();
this->Translations.clear();
- this->SortingPriority = "";
- this->UpdateText = "";
- this->Default = "";
- this->Essential = "";
- this->Virtual = "";
- this->ForcedInstallation = "";
- this->RequiresAdminRights = "";
+ this->SortingPriority.clear();
+ this->UpdateText.clear();
+ this->Default.clear();
+ this->Essential.clear();
+ this->Virtual.clear();
+ this->ForcedInstallation.clear();
+ this->RequiresAdminRights.clear();
}
// Defaul configuration (all in one package)
@@ -203,10 +203,8 @@ int cmCPackIFWPackage::ConfigureFromComponent(cmCPackComponent* component)
// CMake dependencies
if (!component->Dependencies.empty()) {
- std::vector<cmCPackComponent*>::iterator dit;
- for (dit = component->Dependencies.begin();
- dit != component->Dependencies.end(); ++dit) {
- this->Dependencies.insert(this->Generator->ComponentPackages[*dit]);
+ for (cmCPackComponent* dep : component->Dependencies) {
+ this->Dependencies.insert(this->Generator->ComponentPackages[dep]);
}
}
@@ -413,9 +411,8 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
if (const char* value = this->GetOption(option)) {
cmSystemTools::ExpandListArgument(value, deps);
}
- for (std::vector<std::string>::iterator dit = deps.begin();
- dit != deps.end(); ++dit) {
- DependenceStruct dep(*dit);
+ for (std::string const& d : deps) {
+ DependenceStruct dep(d);
if (this->Generator->Packages.count(dep.Name)) {
cmCPackIFWPackage& depPkg = this->Generator->Packages[dep.Name];
dep.Name = depPkg.Name;
@@ -435,9 +432,8 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
} else if (const char* value = this->GetOption(option)) {
std::vector<std::string> depsOn;
cmSystemTools::ExpandListArgument(value, depsOn);
- for (std::vector<std::string>::iterator dit = depsOn.begin();
- dit != depsOn.end(); ++dit) {
- DependenceStruct dep(*dit);
+ for (std::string const& d : depsOn) {
+ DependenceStruct dep(d);
if (this->Generator->Packages.count(dep.Name)) {
cmCPackIFWPackage& depPkg = this->Generator->Packages[dep.Name];
dep.Name = depPkg.Name;
@@ -486,6 +482,15 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
this->ForcedInstallation = "false";
}
+ // Replaces
+ option = prefix + "REPLACES";
+ if (this->IsSetToEmpty(option)) {
+ this->Replaces.clear();
+ } else if (const char* value = this->GetOption(option)) {
+ this->Replaces.clear();
+ cmSystemTools::ExpandListArgument(value, this->Replaces);
+ }
+
// Requires admin rights
option = prefix + "REQUIRES_ADMIN_RIGHTS";
if (this->IsSetToEmpty(option)) {
@@ -496,6 +501,16 @@ int cmCPackIFWPackage::ConfigureFromPrefix(const std::string& prefix)
this->RequiresAdminRights = "false";
}
+ // Checkable
+ option = prefix + "CHECKABLE";
+ if (this->IsSetToEmpty(option)) {
+ this->Checkable.clear();
+ } else if (this->IsOn(option)) {
+ this->Checkable = "true";
+ } else if (this->IsSetToOff(option)) {
+ this->Checkable = "false";
+ }
+
return 1;
}
@@ -521,26 +536,22 @@ void cmCPackIFWPackage::GeneratePackageFile()
xout.StartElement("Package");
// DisplayName (with translations)
- for (std::map<std::string, std::string>::iterator it =
- this->DisplayName.begin();
- it != this->DisplayName.end(); ++it) {
+ for (auto const& dn : this->DisplayName) {
xout.StartElement("DisplayName");
- if (!it->first.empty()) {
- xout.Attribute("xml:lang", it->first);
+ if (!dn.first.empty()) {
+ xout.Attribute("xml:lang", dn.first);
}
- xout.Content(it->second);
+ xout.Content(dn.second);
xout.EndElement();
}
// Description (with translations)
- for (std::map<std::string, std::string>::iterator it =
- this->Description.begin();
- it != this->Description.end(); ++it) {
+ for (auto const& d : this->Description) {
xout.StartElement("Description");
- if (!it->first.empty()) {
- xout.Attribute("xml:lang", it->first);
+ if (!d.first.empty()) {
+ xout.Attribute("xml:lang", d.first);
}
- xout.Content(it->second);
+ xout.Content(d.second);
xout.EndElement();
}
@@ -568,46 +579,43 @@ void cmCPackIFWPackage::GeneratePackageFile()
// User Interfaces (copy to meta dir)
std::vector<std::string> userInterfaces = UserInterfaces;
- for (size_t i = 0; i < userInterfaces.size(); i++) {
- std::string name = cmSystemTools::GetFilenameName(userInterfaces[i]);
+ for (std::string& userInterface : userInterfaces) {
+ std::string name = cmSystemTools::GetFilenameName(userInterface);
std::string path = this->Directory + "/meta/" + name;
- cmsys::SystemTools::CopyFileIfDifferent(userInterfaces[i], path);
- userInterfaces[i] = name;
+ cmsys::SystemTools::CopyFileIfDifferent(userInterface, path);
+ userInterface = name;
}
if (!userInterfaces.empty()) {
xout.StartElement("UserInterfaces");
- for (size_t i = 0; i < userInterfaces.size(); i++) {
- xout.Element("UserInterface", userInterfaces[i]);
+ for (std::string const& userInterface : userInterfaces) {
+ xout.Element("UserInterface", userInterface);
}
xout.EndElement();
}
// Translations (copy to meta dir)
std::vector<std::string> translations = Translations;
- for (size_t i = 0; i < translations.size(); i++) {
- std::string name = cmSystemTools::GetFilenameName(translations[i]);
+ for (std::string& translation : translations) {
+ std::string name = cmSystemTools::GetFilenameName(translation);
std::string path = this->Directory + "/meta/" + name;
- cmsys::SystemTools::CopyFileIfDifferent(translations[i], path);
- translations[i] = name;
+ cmsys::SystemTools::CopyFileIfDifferent(translation, path);
+ translation = name;
}
if (!translations.empty()) {
xout.StartElement("Translations");
- for (size_t i = 0; i < translations.size(); i++) {
- xout.Element("Translation", translations[i]);
+ for (std::string const& translation : translations) {
+ xout.Element("Translation", translation);
}
xout.EndElement();
}
// Dependencies
std::set<DependenceStruct> compDepSet;
- for (std::set<DependenceStruct*>::iterator ait =
- this->AlienDependencies.begin();
- ait != this->AlienDependencies.end(); ++ait) {
- compDepSet.insert(*(*ait));
+ for (DependenceStruct* ad : this->AlienDependencies) {
+ compDepSet.insert(*ad);
}
- for (std::set<cmCPackIFWPackage*>::iterator it = this->Dependencies.begin();
- it != this->Dependencies.end(); ++it) {
- compDepSet.insert(DependenceStruct((*it)->Name));
+ for (cmCPackIFWPackage* d : this->Dependencies) {
+ compDepSet.insert(DependenceStruct(d->Name));
}
// Write dependencies
if (!compDepSet.empty()) {
@@ -624,10 +632,8 @@ void cmCPackIFWPackage::GeneratePackageFile()
// Automatic dependency on
std::set<DependenceStruct> compAutoDepSet;
- for (std::set<DependenceStruct*>::iterator ait =
- this->AlienAutoDependOn.begin();
- ait != this->AlienAutoDependOn.end(); ++ait) {
- compAutoDepSet.insert(*(*ait));
+ for (DependenceStruct* aad : this->AlienAutoDependOn) {
+ compAutoDepSet.insert(*aad);
}
// Write automatic dependency on
if (!compAutoDepSet.empty()) {
@@ -665,6 +671,19 @@ void cmCPackIFWPackage::GeneratePackageFile()
xout.Element("ForcedInstallation", this->ForcedInstallation);
}
+ // Replaces
+ if (!this->Replaces.empty()) {
+ std::ostringstream replaces;
+ std::vector<std::string>::iterator it = this->Replaces.begin();
+ replaces << *it;
+ ++it;
+ while (it != this->Replaces.end()) {
+ replaces << "," << *it;
+ ++it;
+ }
+ xout.Element("Replaces", replaces.str());
+ }
+
if (!this->RequiresAdminRights.empty()) {
xout.Element("RequiresAdminRights", this->RequiresAdminRights);
}
@@ -685,6 +704,11 @@ void cmCPackIFWPackage::GeneratePackageFile()
xout.Element("SortingPriority", this->SortingPriority);
}
+ // Checkable
+ if (!this->Checkable.empty()) {
+ xout.Element("Checkable", this->Checkable);
+ }
+
xout.EndElement();
xout.EndDocument();
}
diff --git a/Source/CPack/IFW/cmCPackIFWPackage.h b/Source/CPack/IFW/cmCPackIFWPackage.h
index cec59b03c..ae411462a 100644
--- a/Source/CPack/IFW/cmCPackIFWPackage.h
+++ b/Source/CPack/IFW/cmCPackIFWPackage.h
@@ -114,9 +114,15 @@ public:
/// Determines that the package must always be installed
std::string ForcedInstallation;
+ /// List of components to replace
+ std::vector<std::string> Replaces;
+
/// Package needs to be installed with elevated permissions
std::string RequiresAdminRights;
+ /// Set to false if you want to hide the checkbox for an item
+ std::string Checkable;
+
public:
// Internal implementation
diff --git a/Source/CPack/IFW/cmCPackIFWRepository.cxx b/Source/CPack/IFW/cmCPackIFWRepository.cxx
index b115db057..a01fc4ed3 100644
--- a/Source/CPack/IFW/cmCPackIFWRepository.cxx
+++ b/Source/CPack/IFW/cmCPackIFWRepository.cxx
@@ -62,49 +62,49 @@ bool cmCPackIFWRepository::ConfigureFromOptions()
if (const char* url = this->GetOption(prefix + "URL")) {
this->Url = url;
} else {
- this->Url = "";
+ this->Url.clear();
}
// Old url
if (const char* oldUrl = this->GetOption(prefix + "OLD_URL")) {
this->OldUrl = oldUrl;
} else {
- this->OldUrl = "";
+ this->OldUrl.clear();
}
// New url
if (const char* newUrl = this->GetOption(prefix + "NEW_URL")) {
this->NewUrl = newUrl;
} else {
- this->NewUrl = "";
+ this->NewUrl.clear();
}
// Enabled
if (this->IsOn(prefix + "DISABLED")) {
this->Enabled = "0";
} else {
- this->Enabled = "";
+ this->Enabled.clear();
}
// Username
if (const char* username = this->GetOption(prefix + "USERNAME")) {
this->Username = username;
} else {
- this->Username = "";
+ this->Username.clear();
}
// Password
if (const char* password = this->GetOption(prefix + "PASSWORD")) {
this->Password = password;
} else {
- this->Password = "";
+ this->Password.clear();
}
// DisplayName
if (const char* displayName = this->GetOption(prefix + "DISPLAY_NAME")) {
this->DisplayName = displayName;
} else {
- this->DisplayName = "";
+ this->DisplayName.clear();
}
return this->IsValid();
@@ -128,7 +128,7 @@ public:
bool patched;
protected:
- void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
+ void StartElement(const std::string& name, const char** atts) override
{
this->xout.StartElement(name);
this->StartFragment(atts);
@@ -143,7 +143,7 @@ protected:
}
}
- void EndElement(const std::string& name) CM_OVERRIDE
+ void EndElement(const std::string& name) override
{
if (name == "Updates" && !this->patched) {
this->repository->WriteRepositoryUpdates(this->xout);
@@ -159,10 +159,10 @@ protected:
}
}
- void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
+ void CharacterDataHandler(const char* data, int length) override
{
std::string content(data, data + length);
- if (content == "" || content == " " || content == " " ||
+ if (content.empty() || content == " " || content == " " ||
content == "\n") {
return;
}
@@ -279,9 +279,8 @@ void cmCPackIFWRepository::WriteRepositoryUpdates(cmXMLWriter& xout)
{
if (!this->RepositoryUpdate.empty()) {
xout.StartElement("RepositoryUpdate");
- for (RepositoriesVector::iterator rit = this->RepositoryUpdate.begin();
- rit != this->RepositoryUpdate.end(); ++rit) {
- (*rit)->WriteRepositoryUpdate(xout);
+ for (cmCPackIFWRepository* r : this->RepositoryUpdate) {
+ r->WriteRepositoryUpdate(xout);
}
xout.EndElement();
}
diff --git a/Source/CPack/OSXScriptLauncher.cxx b/Source/CPack/OSXScriptLauncher.cxx
index b48bf1214..d3de02b47 100644
--- a/Source/CPack/OSXScriptLauncher.cxx
+++ b/Source/CPack/OSXScriptLauncher.cxx
@@ -34,7 +34,7 @@ int main(int argc, char* argv[])
}
fileName = CFSTR("RuntimeScript");
if (!(scriptFileURL =
- CFBundleCopyResourceURL(appBundle, fileName, NULL, NULL))) {
+ CFBundleCopyResourceURL(appBundle, fileName, nullptr, nullptr))) {
DebugError("CFBundleCopyResourceURL failed");
return 1;
}
@@ -71,7 +71,7 @@ int main(int argc, char* argv[])
for (cc = 1; cc < argc; ++cc) {
args.push_back(argv[cc]);
}
- args.push_back(0);
+ args.push_back(nullptr);
cmsysProcess* cp = cmsysProcess_New();
cmsysProcess_SetCommand(cp, &*args.begin());
@@ -83,7 +83,7 @@ int main(int argc, char* argv[])
std::vector<char> tempOutput;
char* data;
int length;
- while (cmsysProcess_WaitForData(cp, &data, &length, 0)) {
+ while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
// Translate NULL characters in the output into valid text.
for (int i = 0; i < length; ++i) {
if (data[i] == '\0') {
@@ -93,7 +93,7 @@ int main(int argc, char* argv[])
std::cout.write(data, length);
}
- cmsysProcess_WaitForExit(cp, 0);
+ cmsysProcess_WaitForExit(cp, nullptr);
bool result = true;
if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exited) {
diff --git a/Source/CPack/WiX/cmCPackWIXGenerator.cxx b/Source/CPack/WiX/cmCPackWIXGenerator.cxx
index 274dfd0ce..ba07d0863 100644
--- a/Source/CPack/WiX/cmCPackWIXGenerator.cxx
+++ b/Source/CPack/WiX/cmCPackWIXGenerator.cxx
@@ -89,9 +89,8 @@ bool cmCPackWIXGenerator::RunCandleCommand(std::string const& sourceFile,
command << " -arch " << GetArchitecture();
command << " -out " << QuotePath(objectFile);
- for (extension_set_t::const_iterator i = CandleExtensions.begin();
- i != CandleExtensions.end(); ++i) {
- command << " -ext " << QuotePath(*i);
+ for (std::string const& ext : CandleExtensions) {
+ command << " -ext " << QuotePath(ext);
}
AddCustomFlags("CPACK_WIX_CANDLE_EXTRA_FLAGS", command);
@@ -113,9 +112,8 @@ bool cmCPackWIXGenerator::RunLightCommand(std::string const& objectFiles)
command << " -nologo";
command << " -out " << QuotePath(packageFileNames.at(0));
- for (extension_set_t::const_iterator i = this->LightExtensions.begin();
- i != this->LightExtensions.end(); ++i) {
- command << " -ext " << QuotePath(*i);
+ for (std::string const& ext : this->LightExtensions) {
+ command << " -ext " << QuotePath(ext);
}
const char* const cultures = GetOption("CPACK_WIX_CULTURES");
@@ -219,8 +217,8 @@ bool cmCPackWIXGenerator::InitializeWiXConfiguration()
std::vector<std::string> patchFilePaths;
cmSystemTools::ExpandListArgument(patchFilePath, patchFilePaths);
- for (size_t i = 0; i < patchFilePaths.size(); ++i) {
- if (!this->Patch->LoadFragments(patchFilePaths[i])) {
+ for (std::string const& p : patchFilePaths) {
+ if (!this->Patch->LoadFragments(p)) {
return false;
}
}
@@ -254,9 +252,7 @@ bool cmCPackWIXGenerator::PackageFilesImpl()
std::set<std::string> usedBaseNames;
std::ostringstream objectFiles;
- for (size_t i = 0; i < this->WixSources.size(); ++i) {
- std::string const& sourceFilename = this->WixSources[i];
-
+ for (std::string const& sourceFilename : this->WixSources) {
std::string baseName =
cmSystemTools::GetFilenameWithoutLastExtension(sourceFilename);
@@ -306,8 +302,8 @@ void cmCPackWIXGenerator::AppendUserSuppliedExtraObjects(std::ostream& stream)
cmSystemTools::ExpandListArgument(cpackWixExtraObjects,
expandedExtraObjects);
- for (size_t i = 0; i < expandedExtraObjects.size(); ++i) {
- stream << " " << QuotePath(expandedExtraObjects[i]);
+ for (std::string const& obj : expandedExtraObjects) {
+ stream << " " << QuotePath(obj);
}
}
@@ -345,9 +341,7 @@ void cmCPackWIXGenerator::CreateWiXPropertiesIncludeFile()
std::string prefix = "CPACK_WIX_PROPERTY_";
std::vector<std::string> options = GetOptions();
- for (size_t i = 0; i < options.size(); ++i) {
- std::string const& name = options[i];
-
+ for (std::string const& name : options) {
if (name.length() > prefix.length() &&
name.substr(0, prefix.length()) == prefix) {
std::string id = name.substr(prefix.length());
@@ -503,16 +497,14 @@ bool cmCPackWIXGenerator::CreateWiXSourceFiles()
globalShortcuts.AddShortcutTypes(emittedShortcutTypes);
} else {
- for (std::map<std::string, cmCPackComponent>::const_iterator i =
- this->Components.begin();
- i != this->Components.end(); ++i) {
- cmCPackComponent const& component = i->second;
+ for (auto const& i : this->Components) {
+ cmCPackComponent const& component = i.second;
std::string componentPath = toplevel;
componentPath += "/";
componentPath += component.Name;
- std::string componentFeatureId = "CM_C_" + component.Name;
+ std::string const componentFeatureId = "CM_C_" + component.Name;
cmWIXShortcuts featureShortcuts;
AddComponentsToFeature(componentPath, componentFeatureId,
@@ -623,19 +615,15 @@ bool cmCPackWIXGenerator::GenerateMainSourceFileFromTemplate()
bool cmCPackWIXGenerator::CreateFeatureHierarchy(
cmWIXFeaturesSourceWriter& featureDefinitions)
{
- for (std::map<std::string, cmCPackComponentGroup>::const_iterator i =
- ComponentGroups.begin();
- i != ComponentGroups.end(); ++i) {
- cmCPackComponentGroup const& group = i->second;
+ for (auto const& i : ComponentGroups) {
+ cmCPackComponentGroup const& group = i.second;
if (group.ParentGroup == 0) {
featureDefinitions.EmitFeatureForComponentGroup(group, *this->Patch);
}
}
- for (std::map<std::string, cmCPackComponent>::const_iterator i =
- this->Components.begin();
- i != this->Components.end(); ++i) {
- cmCPackComponent const& component = i->second;
+ for (auto const& i : this->Components) {
+ cmCPackComponent const& component = i.second;
if (!component.Group) {
featureDefinitions.EmitFeatureForComponent(component, *this->Patch);
@@ -1135,9 +1123,8 @@ void cmCPackWIXGenerator::AddCustomFlags(std::string const& variableName,
std::vector<std::string> list;
cmSystemTools::ExpandListArgument(variableContent, list);
- for (std::vector<std::string>::const_iterator i = list.begin();
- i != list.end(); ++i) {
- stream << " " << QuotePath(*i);
+ for (std::string const& i : list) {
+ stream << " " << QuotePath(i);
}
}
diff --git a/Source/CPack/WiX/cmWIXAccessControlList.cxx b/Source/CPack/WiX/cmWIXAccessControlList.cxx
index 744a93298..1603bf868 100644
--- a/Source/CPack/WiX/cmWIXAccessControlList.cxx
+++ b/Source/CPack/WiX/cmWIXAccessControlList.cxx
@@ -20,8 +20,8 @@ bool cmWIXAccessControlList::Apply()
std::vector<std::string> entries;
this->InstalledFile.GetPropertyAsList("CPACK_WIX_ACL", entries);
- for (size_t i = 0; i < entries.size(); ++i) {
- this->CreatePermissionElement(entries[i]);
+ for (std::string const& entry : entries) {
+ this->CreatePermissionElement(entry);
}
return true;
@@ -56,9 +56,9 @@ void cmWIXAccessControlList::CreatePermissionElement(std::string const& entry)
if (!domain.empty()) {
this->SourceWriter.AddAttribute("Domain", domain);
}
- for (size_t i = 0; i < permissions.size(); ++i) {
+ for (std::string const& permission : permissions) {
this->EmitBooleanAttribute(entry,
- cmSystemTools::TrimWhitespace(permissions[i]));
+ cmSystemTools::TrimWhitespace(permission));
}
this->SourceWriter.EndElement("Permission");
}
diff --git a/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx b/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx
index 0be43776e..a7a064881 100644
--- a/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx
+++ b/Source/CPack/WiX/cmWIXFeaturesSourceWriter.cxx
@@ -46,16 +46,12 @@ void cmWIXFeaturesSourceWriter::EmitFeatureForComponentGroup(
patch.ApplyFragment("CM_G_" + group.Name, *this);
- for (std::vector<cmCPackComponentGroup*>::const_iterator i =
- group.Subgroups.begin();
- i != group.Subgroups.end(); ++i) {
- EmitFeatureForComponentGroup(**i, patch);
+ for (cmCPackComponentGroup* subgroup : group.Subgroups) {
+ EmitFeatureForComponentGroup(*subgroup, patch);
}
- for (std::vector<cmCPackComponent*>::const_iterator i =
- group.Components.begin();
- i != group.Components.end(); ++i) {
- EmitFeatureForComponent(**i, patch);
+ for (cmCPackComponent* component : group.Components) {
+ EmitFeatureForComponent(*component, patch);
}
EndElement("Feature");
diff --git a/Source/CPack/WiX/cmWIXPatch.cxx b/Source/CPack/WiX/cmWIXPatch.cxx
index 287a644bb..dec95fb6e 100644
--- a/Source/CPack/WiX/cmWIXPatch.cxx
+++ b/Source/CPack/WiX/cmWIXPatch.cxx
@@ -29,10 +29,8 @@ void cmWIXPatch::ApplyFragment(std::string const& id,
return;
const cmWIXPatchElement& fragment = i->second;
- for (cmWIXPatchElement::attributes_t::const_iterator attr_i =
- fragment.attributes.begin();
- attr_i != fragment.attributes.end(); ++attr_i) {
- writer.AddAttribute(attr_i->first, attr_i->second);
+ for (auto const& attr : fragment.attributes) {
+ writer.AddAttribute(attr.first, attr.second);
}
this->ApplyElementChildren(fragment, writer);
@@ -42,11 +40,7 @@ void cmWIXPatch::ApplyFragment(std::string const& id,
void cmWIXPatch::ApplyElementChildren(const cmWIXPatchElement& element,
cmWIXSourceWriter& writer)
{
- for (cmWIXPatchElement::child_list_t::const_iterator j =
- element.children.begin();
- j != element.children.end(); ++j) {
- cmWIXPatchNode* node = *j;
-
+ for (cmWIXPatchNode* node : element.children) {
switch (node->type()) {
case cmWIXPatchNode::ELEMENT:
ApplyElement(dynamic_cast<const cmWIXPatchElement&>(*node), writer);
@@ -63,10 +57,8 @@ void cmWIXPatch::ApplyElement(const cmWIXPatchElement& element,
{
writer.BeginElement(element.name);
- for (cmWIXPatchElement::attributes_t::const_iterator i =
- element.attributes.begin();
- i != element.attributes.end(); ++i) {
- writer.AddAttribute(i->first, i->second);
+ for (auto const& attr : element.attributes) {
+ writer.AddAttribute(attr.first, attr.second);
}
this->ApplyElementChildren(element, writer);
@@ -77,14 +69,13 @@ void cmWIXPatch::ApplyElement(const cmWIXPatchElement& element,
bool cmWIXPatch::CheckForUnappliedFragments()
{
std::string fragmentList;
- for (cmWIXPatchParser::fragment_map_t::const_iterator i = Fragments.begin();
- i != Fragments.end(); ++i) {
+ for (auto const& fragment : Fragments) {
if (!fragmentList.empty()) {
fragmentList += ", ";
}
fragmentList += "'";
- fragmentList += i->first;
+ fragmentList += fragment.first;
fragmentList += "'";
}
diff --git a/Source/CPack/WiX/cmWIXPatchParser.cxx b/Source/CPack/WiX/cmWIXPatchParser.cxx
index 0dcc74ae0..e6aeed325 100644
--- a/Source/CPack/WiX/cmWIXPatchParser.cxx
+++ b/Source/CPack/WiX/cmWIXPatchParser.cxx
@@ -22,8 +22,8 @@ cmWIXPatchNode::~cmWIXPatchNode()
cmWIXPatchElement::~cmWIXPatchElement()
{
- for (child_list_t::iterator i = children.begin(); i != children.end(); ++i) {
- delete *i;
+ for (cmWIXPatchNode* child : children) {
+ delete child;
}
}
@@ -72,7 +72,7 @@ void cmWIXPatchParser::StartElement(const std::string& name, const char** atts)
void cmWIXPatchParser::StartFragment(const char** attributes)
{
- cmWIXPatchElement* new_element = CM_NULLPTR;
+ cmWIXPatchElement* new_element = nullptr;
/* find the id of for fragment */
for (size_t i = 0; attributes[i]; i += 2) {
const std::string key = attributes[i];
diff --git a/Source/CPack/WiX/cmWIXRichTextFormatWriter.h b/Source/CPack/WiX/cmWIXRichTextFormatWriter.h
index 30df87814..21be8ee66 100644
--- a/Source/CPack/WiX/cmWIXRichTextFormatWriter.h
+++ b/Source/CPack/WiX/cmWIXRichTextFormatWriter.h
@@ -3,7 +3,7 @@
#ifndef cmWIXRichTextFormatWriter_h
#define cmWIXRichTextFormatWriter_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmsys/FStream.hxx"
#include <string>
diff --git a/Source/CPack/WiX/cmWIXShortcut.cxx b/Source/CPack/WiX/cmWIXShortcut.cxx
index e5dea94c4..cd1988a1c 100644
--- a/Source/CPack/WiX/cmWIXShortcut.cxx
+++ b/Source/CPack/WiX/cmWIXShortcut.cxx
@@ -47,10 +47,9 @@ bool cmWIXShortcuts::EmitShortcuts(
return false;
}
- for (shortcut_id_map_t::const_iterator j = id_map.begin(); j != id_map.end();
- ++j) {
- std::string const& id = j->first;
- shortcut_list_t const& shortcutList = j->second;
+ for (auto const& j : id_map) {
+ std::string const& id = j.first;
+ shortcut_list_t const& shortcutList = j.second;
for (size_t shortcutListIndex = 0; shortcutListIndex < shortcutList.size();
++shortcutListIndex) {
@@ -68,9 +67,8 @@ bool cmWIXShortcuts::EmitShortcuts(
void cmWIXShortcuts::AddShortcutTypes(std::set<Type>& types)
{
- for (shortcut_type_map_t::const_iterator i = this->Shortcuts.begin();
- i != this->Shortcuts.end(); ++i) {
- types.insert(i->first);
+ for (auto const& shortcut : this->Shortcuts) {
+ types.insert(shortcut.first);
}
}
@@ -96,9 +94,9 @@ void cmWIXShortcuts::CreateFromProperty(std::string const& propertyName,
std::vector<std::string> list;
installedFile.GetPropertyAsList(propertyName, list);
- for (size_t i = 0; i < list.size(); ++i) {
+ for (std::string const& label : list) {
cmWIXShortcut shortcut;
- shortcut.label = list[i];
+ shortcut.label = label;
shortcut.workingDirectoryId = directoryId;
insert(type, id, shortcut);
}
diff --git a/Source/CPack/WiX/cmWIXSourceWriter.cxx b/Source/CPack/WiX/cmWIXSourceWriter.cxx
index a86e28d1c..dc730e00c 100644
--- a/Source/CPack/WiX/cmWIXSourceWriter.cxx
+++ b/Source/CPack/WiX/cmWIXSourceWriter.cxx
@@ -158,9 +158,7 @@ std::string cmWIXSourceWriter::EscapeAttributeValue(std::string const& value)
std::string result;
result.reserve(value.size());
- char c = 0;
- for (size_t i = 0; i < value.size(); ++i) {
- c = value[i];
+ for (char c : value) {
switch (c) {
case '<':
result += "&lt;";
diff --git a/Source/CPack/cmCPack7zGenerator.h b/Source/CPack/cmCPack7zGenerator.h
index 42a47810c..8af4c4a4d 100644
--- a/Source/CPack/cmCPack7zGenerator.h
+++ b/Source/CPack/cmCPack7zGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPack7zGenerator_h
#define cmCPack7zGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCPackArchiveGenerator.h"
#include "cmCPackGenerator.h"
@@ -20,10 +20,10 @@ public:
* Construct generator
*/
cmCPack7zGenerator();
- ~cmCPack7zGenerator() CM_OVERRIDE;
+ ~cmCPack7zGenerator() override;
protected:
- const char* GetOutputExtension() CM_OVERRIDE { return ".7z"; }
+ const char* GetOutputExtension() override { return ".7z"; }
};
#endif
diff --git a/Source/CPack/cmCPackArchiveGenerator.cxx b/Source/CPack/cmCPackArchiveGenerator.cxx
index 575c94924..641be3861 100644
--- a/Source/CPack/cmCPackArchiveGenerator.cxx
+++ b/Source/CPack/cmCPackArchiveGenerator.cxx
@@ -9,7 +9,6 @@
#include "cmSystemTools.h"
#include "cmWorkingDirectory.h"
-#include <map>
#include <ostream>
#include <utility>
#include <vector>
@@ -74,12 +73,10 @@ int cmCPackArchiveGenerator::addOneComponentToArchive(
filePrefix += installPrefix + 1;
filePrefix += "/";
}
- std::vector<std::string>::const_iterator fileIt;
- for (fileIt = component->Files.begin(); fileIt != component->Files.end();
- ++fileIt) {
- std::string rp = filePrefix + *fileIt;
+ for (std::string const& file : component->Files) {
+ std::string rp = filePrefix + file;
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Adding file: " << rp << std::endl);
- archive.Add(rp, 0, CM_NULLPTR, false);
+ archive.Add(rp, 0, nullptr, false);
if (!archive) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "ERROR while packaging files: "
<< archive.GetError() << std::endl);
@@ -117,53 +114,47 @@ int cmCPackArchiveGenerator::PackageComponents(bool ignoreGroup)
// The default behavior is to have one package by component group
// unless CPACK_COMPONENTS_IGNORE_GROUP is specified.
if (!ignoreGroup) {
- std::map<std::string, cmCPackComponentGroup>::iterator compGIt;
- for (compGIt = this->ComponentGroups.begin();
- compGIt != this->ComponentGroups.end(); ++compGIt) {
- cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Packaging component group: "
- << compGIt->first << std::endl);
+ for (auto const& compG : this->ComponentGroups) {
+ cmCPackLogger(cmCPackLog::LOG_VERBOSE,
+ "Packaging component group: " << compG.first << std::endl);
// Begin the archive for this group
std::string packageFileName = std::string(toplevel) + "/" +
- this->GetArchiveComponentFileName(compGIt->first, true);
+ this->GetArchiveComponentFileName(compG.first, true);
// open a block in order to automatically close archive
// at the end of the block
{
DECLARE_AND_OPEN_ARCHIVE(packageFileName, archive);
// now iterate over the component of this group
- std::vector<cmCPackComponent*>::iterator compIt;
- for (compIt = (compGIt->second).Components.begin();
- compIt != (compGIt->second).Components.end(); ++compIt) {
+ for (cmCPackComponent* comp : (compG.second).Components) {
// Add the files of this component to the archive
- addOneComponentToArchive(archive, *compIt);
+ addOneComponentToArchive(archive, comp);
}
}
// add the generated package to package file names list
packageFileNames.push_back(packageFileName);
}
// Handle Orphan components (components not belonging to any groups)
- std::map<std::string, cmCPackComponent>::iterator compIt;
- for (compIt = this->Components.begin(); compIt != this->Components.end();
- ++compIt) {
+ for (auto& comp : this->Components) {
// Does the component belong to a group?
- if (compIt->second.Group == CM_NULLPTR) {
+ if (comp.second.Group == nullptr) {
cmCPackLogger(
cmCPackLog::LOG_VERBOSE, "Component <"
- << compIt->second.Name
+ << comp.second.Name
<< "> does not belong to any group, package it separately."
<< std::endl);
std::string localToplevel(
this->GetOption("CPACK_TEMPORARY_DIRECTORY"));
std::string packageFileName = std::string(toplevel);
- localToplevel += "/" + compIt->first;
+ localToplevel += "/" + comp.first;
packageFileName +=
- "/" + this->GetArchiveComponentFileName(compIt->first, false);
+ "/" + this->GetArchiveComponentFileName(comp.first, false);
{
DECLARE_AND_OPEN_ARCHIVE(packageFileName, archive);
// Add the files of this component to the archive
- addOneComponentToArchive(archive, &(compIt->second));
+ addOneComponentToArchive(archive, &(comp.second));
}
// add the generated package to package file names list
packageFileNames.push_back(packageFileName);
@@ -173,20 +164,18 @@ int cmCPackArchiveGenerator::PackageComponents(bool ignoreGroup)
// CPACK_COMPONENTS_IGNORE_GROUPS is set
// We build 1 package per component
else {
- std::map<std::string, cmCPackComponent>::iterator compIt;
- for (compIt = this->Components.begin(); compIt != this->Components.end();
- ++compIt) {
+ for (auto& comp : this->Components) {
std::string localToplevel(this->GetOption("CPACK_TEMPORARY_DIRECTORY"));
std::string packageFileName = std::string(toplevel);
- localToplevel += "/" + compIt->first;
+ localToplevel += "/" + comp.first;
packageFileName +=
- "/" + this->GetArchiveComponentFileName(compIt->first, false);
+ "/" + this->GetArchiveComponentFileName(comp.first, false);
{
DECLARE_AND_OPEN_ARCHIVE(packageFileName, archive);
// Add the files of this component to the archive
- addOneComponentToArchive(archive, &(compIt->second));
+ addOneComponentToArchive(archive, &(comp.second));
}
// add the generated package to package file names list
packageFileNames.push_back(packageFileName);
@@ -217,11 +206,9 @@ int cmCPackArchiveGenerator::PackageComponentsAllInOne()
DECLARE_AND_OPEN_ARCHIVE(packageFileNames[0], archive);
// The ALL COMPONENTS in ONE package case
- std::map<std::string, cmCPackComponent>::iterator compIt;
- for (compIt = this->Components.begin(); compIt != this->Components.end();
- ++compIt) {
+ for (auto& comp : this->Components) {
// Add the files of this component to the archive
- addOneComponentToArchive(archive, &(compIt->second));
+ addOneComponentToArchive(archive, &(comp.second));
}
// archive goes out of scope so it will finalized and closed.
@@ -249,16 +236,15 @@ int cmCPackArchiveGenerator::PackageFiles()
// CASE 3 : NON COMPONENT package.
DECLARE_AND_OPEN_ARCHIVE(packageFileNames[0], archive);
- std::vector<std::string>::const_iterator fileIt;
cmWorkingDirectory workdir(toplevel);
- for (fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
+ for (std::string const& file : files) {
// Get the relative path to the file
std::string rp =
- cmSystemTools::RelativePath(toplevel.c_str(), fileIt->c_str());
- archive.Add(rp, 0, CM_NULLPTR, false);
+ cmSystemTools::RelativePath(toplevel.c_str(), file.c_str());
+ archive.Add(rp, 0, nullptr, false);
if (!archive) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem while adding file< "
- << *fileIt << "> to archive <" << packageFileNames[0]
+ << file << "> to archive <" << packageFileNames[0]
<< "> .ERROR =" << archive.GetError() << std::endl);
return 0;
}
diff --git a/Source/CPack/cmCPackArchiveGenerator.h b/Source/CPack/cmCPackArchiveGenerator.h
index e7116c466..998385432 100644
--- a/Source/CPack/cmCPackArchiveGenerator.h
+++ b/Source/CPack/cmCPackArchiveGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackArchiveGenerator_h
#define cmCPackArchiveGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmArchiveWrite.h"
#include "cmCPackGenerator.h"
@@ -28,11 +28,11 @@ public:
* Construct generator
*/
cmCPackArchiveGenerator(cmArchiveWrite::Compress, std::string const& format);
- ~cmCPackArchiveGenerator() CM_OVERRIDE;
+ ~cmCPackArchiveGenerator() override;
// Used to add a header to the archive
virtual int GenerateHeader(std::ostream* os);
// component support
- bool SupportsComponentInstallation() const CM_OVERRIDE;
+ bool SupportsComponentInstallation() const override;
private:
// get archive component filename
@@ -40,7 +40,7 @@ private:
bool isGroupName);
protected:
- int InitializeInternal() CM_OVERRIDE;
+ int InitializeInternal() override;
/**
* Add the files belonging to the specified component
* to the provided (already opened) archive.
@@ -56,7 +56,7 @@ protected:
* method will call either PackageComponents or
* PackageComponentsAllInOne.
*/
- int PackageFiles() CM_OVERRIDE;
+ int PackageFiles() override;
/**
* The method used to package files when component
* install is used. This will create one
@@ -68,7 +68,7 @@ protected:
* components will be put in a single installer.
*/
int PackageComponentsAllInOne();
- const char* GetOutputExtension() CM_OVERRIDE = 0;
+ const char* GetOutputExtension() override = 0;
cmArchiveWrite::Compress Compress;
std::string ArchiveFormat;
};
diff --git a/Source/CPack/cmCPackBundleGenerator.cxx b/Source/CPack/cmCPackBundleGenerator.cxx
index d5389014a..f47ca7a74 100644
--- a/Source/CPack/cmCPackBundleGenerator.cxx
+++ b/Source/CPack/cmCPackBundleGenerator.cxx
@@ -19,7 +19,7 @@ cmCPackBundleGenerator::~cmCPackBundleGenerator()
int cmCPackBundleGenerator::InitializeInternal()
{
const char* name = this->GetOption("CPACK_BUNDLE_NAME");
- if (0 == name) {
+ if (nullptr == name) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
"CPACK_BUNDLE_NAME must be set to use the Bundle generator."
<< std::endl);
@@ -213,8 +213,7 @@ int cmCPackBundleGenerator::SignBundle(const std::string& src_dir)
cmSystemTools::ExpandListArgument(sign_files, relFiles);
// sign the files supplied by the user, ie. frameworks.
- for (std::vector<std::string>::iterator it = relFiles.begin();
- it != relFiles.end(); ++it) {
+ for (auto const& file : relFiles) {
std::ostringstream temp_sign_file_cmd;
temp_sign_file_cmd << this->GetOption("CPACK_COMMAND_CODESIGN");
temp_sign_file_cmd << " " << sign_parameter << " -s \""
@@ -223,11 +222,11 @@ int cmCPackBundleGenerator::SignBundle(const std::string& src_dir)
temp_sign_file_cmd << this->GetOption("CPACK_APPLE_BUNDLE_ID");
temp_sign_file_cmd << " \"";
temp_sign_file_cmd << bundle_path;
- temp_sign_file_cmd << *it << "\"";
+ temp_sign_file_cmd << file << "\"";
if (!this->RunCommand(temp_sign_file_cmd, &output)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
- "Error signing file:" << bundle_path << *it << std::endl
+ "Error signing file:" << bundle_path << file << std::endl
<< output << std::endl);
return 0;
diff --git a/Source/CPack/cmCPackBundleGenerator.h b/Source/CPack/cmCPackBundleGenerator.h
index 861fe4b09..27bac3a5a 100644
--- a/Source/CPack/cmCPackBundleGenerator.h
+++ b/Source/CPack/cmCPackBundleGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackBundleGenerator_h
#define cmCPackBundleGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
@@ -21,15 +21,15 @@ public:
cmCPackTypeMacro(cmCPackBundleGenerator, cmCPackDragNDropGenerator);
cmCPackBundleGenerator();
- virtual ~cmCPackBundleGenerator();
+ ~cmCPackBundleGenerator() override;
protected:
- int InitializeInternal() CM_OVERRIDE;
- const char* GetPackagingInstallPrefix() CM_OVERRIDE;
+ int InitializeInternal() override;
+ const char* GetPackagingInstallPrefix() override;
int ConstructBundle();
int SignBundle(const std::string& src_dir);
- int PackageFiles() CM_OVERRIDE;
- bool SupportsComponentInstallation() const CM_OVERRIDE;
+ int PackageFiles() override;
+ bool SupportsComponentInstallation() const override;
std::string InstallPrefix;
};
diff --git a/Source/CPack/cmCPackComponentGroup.cxx b/Source/CPack/cmCPackComponentGroup.cxx
index e39398ad5..f888a5f5d 100644
--- a/Source/CPack/cmCPackComponentGroup.cxx
+++ b/Source/CPack/cmCPackComponentGroup.cxx
@@ -5,7 +5,6 @@
#include "cmSystemTools.h"
#include <string>
-#include <vector>
unsigned long cmCPackComponent::GetInstalledSize(
const std::string& installDir) const
@@ -14,11 +13,10 @@ unsigned long cmCPackComponent::GetInstalledSize(
return this->TotalSize;
}
- std::vector<std::string>::const_iterator fileIt;
- for (fileIt = this->Files.begin(); fileIt != this->Files.end(); ++fileIt) {
+ for (std::string const& file : this->Files) {
std::string path = installDir;
path += '/';
- path += *fileIt;
+ path += file;
this->TotalSize += cmSystemTools::FileLength(path);
}
diff --git a/Source/CPack/cmCPackComponentGroup.h b/Source/CPack/cmCPackComponentGroup.h
index 26d69ba68..f2907db20 100644
--- a/Source/CPack/cmCPackComponentGroup.h
+++ b/Source/CPack/cmCPackComponentGroup.h
@@ -3,7 +3,7 @@
#ifndef cmCPackComponentGroup_h
#define cmCPackComponentGroup_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -36,7 +36,7 @@ class cmCPackComponent
{
public:
cmCPackComponent()
- : Group(CM_NULLPTR)
+ : Group(nullptr)
, IsRequired(true)
, IsHidden(false)
, IsDisabledByDefault(false)
@@ -114,7 +114,7 @@ class cmCPackComponentGroup
{
public:
cmCPackComponentGroup()
- : ParentGroup(CM_NULLPTR)
+ : ParentGroup(nullptr)
{
}
diff --git a/Source/CPack/cmCPackCygwinBinaryGenerator.h b/Source/CPack/cmCPackCygwinBinaryGenerator.h
index 58e80bda7..f87a1343b 100644
--- a/Source/CPack/cmCPackCygwinBinaryGenerator.h
+++ b/Source/CPack/cmCPackCygwinBinaryGenerator.h
@@ -17,7 +17,7 @@ public:
* Construct generator
*/
cmCPackCygwinBinaryGenerator();
- virtual ~cmCPackCygwinBinaryGenerator();
+ ~cmCPackCygwinBinaryGenerator() override;
protected:
virtual int InitializeInternal();
diff --git a/Source/CPack/cmCPackCygwinSourceGenerator.h b/Source/CPack/cmCPackCygwinSourceGenerator.h
index 896de1d3e..a909b1595 100644
--- a/Source/CPack/cmCPackCygwinSourceGenerator.h
+++ b/Source/CPack/cmCPackCygwinSourceGenerator.h
@@ -17,7 +17,7 @@ public:
* Construct generator
*/
cmCPackCygwinSourceGenerator();
- virtual ~cmCPackCygwinSourceGenerator();
+ ~cmCPackCygwinSourceGenerator() override;
protected:
const char* GetPackagingInstallPrefix();
diff --git a/Source/CPack/cmCPackDebGenerator.cxx b/Source/CPack/cmCPackDebGenerator.cxx
index af54fce33..7fc3c26de 100644
--- a/Source/CPack/cmCPackDebGenerator.cxx
+++ b/Source/CPack/cmCPackDebGenerator.cxx
@@ -6,28 +6,17 @@
#include "cmCPackComponentGroup.h"
#include "cmCPackGenerator.h"
#include "cmCPackLog.h"
+#include "cmCryptoHash.h"
#include "cmGeneratedFileStream.h"
#include "cmSystemTools.h"
#include "cm_sys_stat.h"
#include "cmsys/Glob.hxx"
-#include <limits.h>
-#include <map>
#include <ostream>
#include <set>
-#include <stdio.h>
#include <string.h>
#include <utility>
-// NOTE:
-// A debian package .deb is simply an 'ar' archive. The only subtle difference
-// is that debian uses the BSD ar style archive whereas most Linux distro have
-// a GNU ar.
-// See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=161593 for more info
-// Therefore we provide our own implementation of a BSD-ar:
-static int ar_append(const char* archive,
- const std::vector<std::string>& files);
-
cmCPackDebGenerator::cmCPackDebGenerator()
{
}
@@ -115,37 +104,31 @@ int cmCPackDebGenerator::PackageComponents(bool ignoreGroup)
// The default behavior is to have one package by component group
// unless CPACK_COMPONENTS_IGNORE_GROUP is specified.
if (!ignoreGroup) {
- std::map<std::string, cmCPackComponentGroup>::iterator compGIt;
- for (compGIt = this->ComponentGroups.begin();
- compGIt != this->ComponentGroups.end(); ++compGIt) {
- cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Packaging component group: "
- << compGIt->first << std::endl);
+ for (auto const& compG : this->ComponentGroups) {
+ cmCPackLogger(cmCPackLog::LOG_VERBOSE,
+ "Packaging component group: " << compG.first << std::endl);
// Begin the archive for this group
- retval &= PackageOnePack(initialTopLevel, compGIt->first);
+ retval &= PackageOnePack(initialTopLevel, compG.first);
}
// Handle Orphan components (components not belonging to any groups)
- std::map<std::string, cmCPackComponent>::iterator compIt;
- for (compIt = this->Components.begin(); compIt != this->Components.end();
- ++compIt) {
+ for (auto const& comp : this->Components) {
// Does the component belong to a group?
- if (compIt->second.Group == CM_NULLPTR) {
+ if (comp.second.Group == nullptr) {
cmCPackLogger(
cmCPackLog::LOG_VERBOSE, "Component <"
- << compIt->second.Name
+ << comp.second.Name
<< "> does not belong to any group, package it separately."
<< std::endl);
// Begin the archive for this orphan component
- retval &= PackageOnePack(initialTopLevel, compIt->first);
+ retval &= PackageOnePack(initialTopLevel, comp.first);
}
}
}
// CPACK_COMPONENTS_IGNORE_GROUPS is set
// We build 1 package per component
else {
- std::map<std::string, cmCPackComponent>::iterator compIt;
- for (compIt = this->Components.begin(); compIt != this->Components.end();
- ++compIt) {
- retval &= PackageOnePack(initialTopLevel, compIt->first);
+ for (auto const& comp : this->Components) {
+ retval &= PackageOnePack(initialTopLevel, comp.first);
}
}
return retval;
@@ -346,10 +329,8 @@ int cmCPackDebGenerator::createDeb()
{
std::string dirName = this->GetOption("CPACK_TEMPORARY_DIRECTORY");
dirName += '/';
- for (std::vector<std::string>::const_iterator fileIt =
- packageFiles.begin();
- fileIt != packageFiles.end(); ++fileIt) {
- totalSize += cmSystemTools::FileLength(*fileIt);
+ for (std::string const& file : packageFiles) {
+ totalSize += cmSystemTools::FileLength(file);
}
}
out << "Installed-Size: " << (totalSize + 1023) / 1024 << "\n";
@@ -410,7 +391,7 @@ int cmCPackDebGenerator::createDeb()
compression_suffix = ".gz";
tar_compression_type = cmArchiveWrite::CompressGZip;
} else if (!strcmp(debian_compression_type, "none")) {
- compression_suffix = "";
+ compression_suffix.clear();
tar_compression_type = cmArchiveWrite::CompressNone;
} else {
cmCPackLogger(cmCPackLog::LOG_ERROR,
@@ -456,10 +437,7 @@ int cmCPackDebGenerator::createDeb()
// we have to reconstruct the parent folders as well
- for (std::vector<std::string>::const_iterator fileIt =
- packageFiles.begin();
- fileIt != packageFiles.end(); ++fileIt) {
- std::string currentPath = *fileIt;
+ for (std::string currentPath : packageFiles) {
while (currentPath != strGenWDIR) {
// the last one IS strGenWDIR, but we do not want this one:
// XXX/application/usr/bin/myprogram with GEN_WDIR=XXX/application
@@ -469,22 +447,40 @@ int cmCPackDebGenerator::createDeb()
}
}
- for (std::set<std::string>::const_iterator fileIt = orderedFiles.begin();
- fileIt != orderedFiles.end(); ++fileIt) {
- cmCPackLogger(cmCPackLog::LOG_DEBUG, "FILEIT: \"" << *fileIt << "\""
+ for (std::string const& file : orderedFiles) {
+ cmCPackLogger(cmCPackLog::LOG_DEBUG, "FILEIT: \"" << file << "\""
<< std::endl);
- std::string::size_type slashPos = fileIt->find('/', topLevelLength + 1);
+ std::string::size_type slashPos = file.find('/', topLevelLength + 1);
std::string relativeDir =
- fileIt->substr(topLevelLength, slashPos - topLevelLength);
+ file.substr(topLevelLength, slashPos - topLevelLength);
cmCPackLogger(cmCPackLog::LOG_DEBUG, "RELATIVEDIR: \""
<< relativeDir << "\"" << std::endl);
+#ifdef WIN32
+ std::string mode_t_adt_filename = file + ":cmake_mode_t";
+ cmsys::ifstream permissionStream(mode_t_adt_filename.c_str());
+
+ mode_t permissions = 0;
+
+ if (permissionStream) {
+ permissionStream >> std::oct >> permissions;
+ }
+
+ if (permissions != 0) {
+ data_tar.SetPermissions(permissions);
+ } else if (cmSystemTools::FileIsDirectory(file)) {
+ data_tar.SetPermissions(0755);
+ } else {
+ data_tar.ClearPermissions();
+ }
+#endif
+
// do not recurse because the loop will do it
- if (!data_tar.Add(*fileIt, topLevelLength, ".", false)) {
+ if (!data_tar.Add(file, topLevelLength, ".", false)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem adding file to tar:"
<< std::endl
<< "#top level directory: " << strGenWDIR << std::endl
- << "#file: " << *fileIt << std::endl
+ << "#file: " << file << std::endl
<< "#error:" << data_tar.GetError() << std::endl);
return 0;
}
@@ -499,25 +495,21 @@ int cmCPackDebGenerator::createDeb()
std::string topLevelWithTrailingSlash =
this->GetOption("CPACK_TEMPORARY_DIRECTORY");
topLevelWithTrailingSlash += '/';
- for (std::vector<std::string>::const_iterator fileIt =
- packageFiles.begin();
- fileIt != packageFiles.end(); ++fileIt) {
+ for (std::string const& file : packageFiles) {
// hash only regular files
- if (cmSystemTools::FileIsDirectory(*fileIt) ||
- cmSystemTools::FileIsSymlink(*fileIt)) {
+ if (cmSystemTools::FileIsDirectory(file) ||
+ cmSystemTools::FileIsSymlink(file)) {
continue;
}
- char md5sum[33];
- if (!cmSystemTools::ComputeFileMD5(*fileIt, md5sum)) {
+ std::string output =
+ cmSystemTools::ComputeFileHash(file, cmCryptoHash::AlgoMD5);
+ if (output.empty()) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Problem computing the md5 of "
- << *fileIt << std::endl);
+ << file << std::endl);
}
- md5sum[32] = 0;
-
- std::string output(md5sum);
- output += " " + *fileIt + "\n";
+ output += " " + file + "\n";
// debian md5sums entries are like this:
// 014f3604694729f3bf19263bac599765 usr/bin/ccmake
// thus strip the full path (with the trailing slash)
@@ -553,8 +545,8 @@ int cmCPackDebGenerator::createDeb()
and
https://lintian.debian.org/tags/control-file-has-bad-permissions.html
*/
- const mode_t permission644 = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
- const mode_t permissionExecute = S_IXUSR | S_IXGRP | S_IXOTH;
+ const mode_t permission644 = 0644;
+ const mode_t permissionExecute = 0111;
const mode_t permission755 = permission644 | permissionExecute;
// for md5sum and control (that we have generated here), we use 644
@@ -634,9 +626,8 @@ int cmCPackDebGenerator::createDeb()
std::vector<std::string> controlExtraList;
cmSystemTools::ExpandListArgument(controlExtra, controlExtraList);
- for (std::vector<std::string>::iterator i = controlExtraList.begin();
- i != controlExtraList.end(); ++i) {
- std::string filenamename = cmsys::SystemTools::GetFilenameName(*i);
+ for (std::string const& i : controlExtraList) {
+ std::string filenamename = cmsys::SystemTools::GetFilenameName(i);
std::string localcopy = strGenWDIR + "/" + filenamename;
if (permissionStrictPolicy) {
@@ -646,7 +637,7 @@ int cmCPackDebGenerator::createDeb()
}
// if we can copy the file, it means it does exist, let's add it:
- if (cmsys::SystemTools::CopyFileIfDifferent(*i, localcopy)) {
+ if (cmsys::SystemTools::CopyFileIfDifferent(i, localcopy)) {
control_tar.Add(localcopy, strGenWDIR.length(), ".");
}
}
@@ -654,23 +645,25 @@ int cmCPackDebGenerator::createDeb()
}
// ar -r your-package-name.deb debian-binary control.tar.* data.tar.*
- // since debian packages require BSD ar (most Linux distros and even
- // FreeBSD and NetBSD ship GNU ar) we use a copy of OpenBSD ar here.
- std::vector<std::string> arFiles;
- std::string topLevelString = strGenWDIR + "/";
- arFiles.push_back(topLevelString + "debian-binary");
- arFiles.push_back(topLevelString + "control.tar.gz");
- arFiles.push_back(topLevelString + "data.tar" + compression_suffix);
- std::string outputFileName = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
- outputFileName += "/";
- outputFileName += this->GetOption("GEN_CPACK_OUTPUT_FILE_NAME");
- int res = ar_append(outputFileName.c_str(), arFiles);
- if (res != 0) {
- std::string tmpFile =
- this->GetOption("GEN_CPACK_TEMPORARY_PACKAGE_FILE_NAME");
- tmpFile += "/Deb.log";
- cmGeneratedFileStream ofs(tmpFile.c_str());
- ofs << "# Problem creating archive using: " << res << std::endl;
+ // A debian package .deb is simply an 'ar' archive. The only subtle
+ // difference is that debian uses the BSD ar style archive whereas most
+ // Linux distro have a GNU ar.
+ // See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=161593 for more info
+ std::string const outputDir = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
+ std::string const outputName = this->GetOption("GEN_CPACK_OUTPUT_FILE_NAME");
+ std::string const outputPath = outputDir + "/" + outputName;
+ std::string const tlDir = strGenWDIR + "/";
+ cmGeneratedFileStream debStream;
+ debStream.Open(outputPath.c_str(), false, true);
+ cmArchiveWrite deb(debStream, cmArchiveWrite::CompressNone, "arbsd");
+ if (!deb.Add(tlDir + "debian-binary", tlDir.length()) ||
+ !deb.Add(tlDir + "control.tar.gz", tlDir.length()) ||
+ !deb.Add(tlDir + "data.tar" + compression_suffix, tlDir.length())) {
+ cmCPackLogger(cmCPackLog::LOG_ERROR, "Error creating debian package:"
+ << std::endl
+ << "#top level directory: " << outputDir << std::endl
+ << "#file: " << outputName << std::endl
+ << "#error:" << deb.GetError() << std::endl);
return 0;
}
return 1;
@@ -695,252 +688,8 @@ std::string cmCPackDebGenerator::GetComponentInstallDirNameSuffix(
// the current COMPONENT belongs to.
std::string groupVar =
"CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP";
- if (CM_NULLPTR != GetOption(groupVar)) {
+ if (nullptr != GetOption(groupVar)) {
return std::string(GetOption(groupVar));
}
return componentName;
}
-
-// The following code is taken from OpenBSD ar:
-// http://www.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ar/
-// It has been slightly modified:
-// -return error codes instead exit() in functions
-// -use the stdio file I/O functions instead the file descriptor based ones
-// -merged into one cxx file
-// -no additional options supported
-// The coding style hasn't been modified.
-
-/*-
- * Copyright (c) 1990, 1993, 1994
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Hugh Smith at The University of Guelph.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``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 REGENTS OR CONTRIBUTORS 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.
- */
-
-#define ARMAG "!<arch>\n" /* ar "magic number" */
-#define SARMAG 8 /* strlen(ARMAG); */
-
-#define AR_EFMT1 "#1/" /* extended format #1 */
-#define ARFMAG "`\n"
-
-/* Header format strings. */
-#define HDR1 "%s%-13d%-12ld%-6u%-6u%-8o%-10lld%2s"
-#define HDR2 "%-16.16s%-12ld%-6u%-6u%-8o%-10lld%2s"
-
-struct ar_hdr
-{
- char ar_name[16]; /* name */
- char ar_date[12]; /* modification time */
- char ar_uid[6]; /* user id */
- char ar_gid[6]; /* group id */
- char ar_mode[8]; /* octal file permissions */
- char ar_size[10]; /* size in bytes */
- char ar_fmag[2]; /* consistency check */
-};
-
-/* Set up file copy. */
-#define SETCF(from, fromname, to, toname, pad) \
- { \
- cf.rFile = from; \
- cf.rname = fromname; \
- cf.wFile = to; \
- cf.wname = toname; \
- cf.flags = pad; \
- }
-
-/* File copy structure. */
-typedef struct
-{
- FILE* rFile; /* read file descriptor */
- const char* rname; /* read name */
- FILE* wFile; /* write file descriptor */
- const char* wname; /* write name */
-#define NOPAD 0x00 /* don't pad */
-#define WPAD 0x02 /* pad on writes */
- unsigned int flags; /* pad flags */
-} CF;
-
-/* misc.c */
-
-static const char* ar_rname(const char* path)
-{
- const char* ind = strrchr(path, '/');
- return (ind) ? ind + 1 : path;
-}
-
-/* archive.c */
-
-typedef struct ar_hdr HDR;
-static char ar_hb[sizeof(HDR) + 1]; /* real header */
-
-static size_t ar_already_written;
-
-/* copy_ar --
- * Copy size bytes from one file to another - taking care to handle the
- * extra byte (for odd size files) when reading archives and writing an
- * extra byte if necessary when adding files to archive. The length of
- * the object is the long name plus the object itself; the variable
- * already_written gets set if a long name was written.
- *
- * The padding is really unnecessary, and is almost certainly a remnant
- * of early archive formats where the header included binary data which
- * a PDP-11 required to start on an even byte boundary. (Or, perhaps,
- * because 16-bit word addressed copies were faster?) Anyhow, it should
- * have been ripped out long ago.
- */
-static int copy_ar(CF* cfp, off_t size)
-{
- static char pad = '\n';
- off_t sz = size;
- size_t nr, nw;
- char buf[8 * 1024];
-
- if (sz == 0) {
- return 0;
- }
-
- FILE* from = cfp->rFile;
- FILE* to = cfp->wFile;
- while (sz &&
- (nr = fread(buf, 1, sz < static_cast<off_t>(sizeof(buf))
- ? static_cast<size_t>(sz)
- : sizeof(buf),
- from)) > 0) {
- sz -= nr;
- for (size_t off = 0; off < nr; nr -= off, off += nw) {
- if ((nw = fwrite(buf + off, 1, nr, to)) < nr) {
- return -1;
- }
- }
- }
- if (sz) {
- return -2;
- }
-
- if (cfp->flags & WPAD && (size + ar_already_written) & 1 &&
- fwrite(&pad, 1, 1, to) != 1) {
- return -4;
- }
-
- return 0;
-}
-
-/* put_arobj -- Write an archive member to a file. */
-static int put_arobj(CF* cfp, struct stat* sb)
-{
- int result = 0;
- struct ar_hdr* hdr;
-
- /* If passed an sb structure, reading a file from disk. Get stat(2)
- * information, build a name and construct a header. (Files are named
- * by their last component in the archive.) */
- const char* name = ar_rname(cfp->rname);
- (void)stat(cfp->rname, sb);
-
- /* If not truncating names and the name is too long or contains
- * a space, use extended format 1. */
- size_t lname = strlen(name);
- uid_t uid = sb->st_uid;
- gid_t gid = sb->st_gid;
- if (uid > USHRT_MAX) {
- uid = USHRT_MAX;
- }
- if (gid > USHRT_MAX) {
- gid = USHRT_MAX;
- }
- if (lname > sizeof(hdr->ar_name) || strchr(name, ' ')) {
- (void)sprintf(ar_hb, HDR1, AR_EFMT1, (int)lname, (long int)sb->st_mtime,
- (unsigned)uid, (unsigned)gid, (unsigned)sb->st_mode,
- (long long)sb->st_size + lname, ARFMAG);
- } else {
- lname = 0;
- (void)sprintf(ar_hb, HDR2, name, (long int)sb->st_mtime, (unsigned)uid,
- (unsigned)gid, (unsigned)sb->st_mode, (long long)sb->st_size,
- ARFMAG);
- }
- off_t size = sb->st_size;
-
- if (fwrite(ar_hb, 1, sizeof(HDR), cfp->wFile) != sizeof(HDR)) {
- return -1;
- }
-
- if (lname) {
- if (fwrite(name, 1, lname, cfp->wFile) != lname) {
- return -2;
- }
- ar_already_written = lname;
- }
- result = copy_ar(cfp, size);
- ar_already_written = 0;
- return result;
-}
-
-/* append.c */
-
-/* append --
- * Append files to the archive - modifies original archive or creates
- * a new archive if named archive does not exist.
- */
-static int ar_append(const char* archive,
- const std::vector<std::string>& files)
-{
- int eval = 0;
- FILE* aFile = cmSystemTools::Fopen(archive, "wb+");
- if (aFile != CM_NULLPTR) {
- fwrite(ARMAG, SARMAG, 1, aFile);
- if (fseek(aFile, 0, SEEK_END) != -1) {
- CF cf;
- struct stat sb;
- /* Read from disk, write to an archive; pad on write. */
- SETCF(CM_NULLPTR, CM_NULLPTR, aFile, archive, WPAD);
- for (std::vector<std::string>::const_iterator fileIt = files.begin();
- fileIt != files.end(); ++fileIt) {
- const char* filename = fileIt->c_str();
- FILE* file = cmSystemTools::Fopen(filename, "rb");
- if (file == CM_NULLPTR) {
- eval = -1;
- continue;
- }
- cf.rFile = file;
- cf.rname = filename;
- int result = put_arobj(&cf, &sb);
- (void)fclose(file);
- if (result != 0) {
- eval = -2;
- break;
- }
- }
- } else {
- eval = -3;
- }
- fclose(aFile);
- } else {
- eval = -4;
- }
- return eval;
-}
diff --git a/Source/CPack/cmCPackDebGenerator.h b/Source/CPack/cmCPackDebGenerator.h
index e7cde1145..b4f0c7972 100644
--- a/Source/CPack/cmCPackDebGenerator.h
+++ b/Source/CPack/cmCPackDebGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackDebGenerator_h
#define cmCPackDebGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCPackGenerator.h"
@@ -23,7 +23,7 @@ public:
* Construct generator
*/
cmCPackDebGenerator();
- ~cmCPackDebGenerator() CM_OVERRIDE;
+ ~cmCPackDebGenerator() override;
static bool CanGenerate()
{
@@ -40,7 +40,7 @@ public:
}
protected:
- int InitializeInternal() CM_OVERRIDE;
+ int InitializeInternal() override;
/**
* This method factors out the work done in component packaging case.
*/
@@ -57,11 +57,11 @@ protected:
* components will be put in a single installer.
*/
int PackageComponentsAllInOne(const std::string& compInstDirName);
- int PackageFiles() CM_OVERRIDE;
- const char* GetOutputExtension() CM_OVERRIDE { return ".deb"; }
- bool SupportsComponentInstallation() const CM_OVERRIDE;
+ int PackageFiles() override;
+ const char* GetOutputExtension() override { return ".deb"; }
+ bool SupportsComponentInstallation() const override;
std::string GetComponentInstallDirNameSuffix(
- const std::string& componentName) CM_OVERRIDE;
+ const std::string& componentName) override;
private:
int createDeb();
diff --git a/Source/CPack/cmCPackDragNDropGenerator.cxx b/Source/CPack/cmCPackDragNDropGenerator.cxx
index d26d5bc1a..1e1543f9d 100644
--- a/Source/CPack/cmCPackDragNDropGenerator.cxx
+++ b/Source/CPack/cmCPackDragNDropGenerator.cxx
@@ -136,17 +136,17 @@ int cmCPackDragNDropGenerator::InitializeInternal()
"CPACK_DMG_SLA_LANGUAGES set but empty" << std::endl);
return 0;
}
- for (size_t i = 0; i < languages.size(); ++i) {
- std::string license = slaDirectory + "/" + languages[i] + ".license.txt";
+ for (auto const& language : languages) {
+ std::string license = slaDirectory + "/" + language + ".license.txt";
if (!singleLicense && !cmSystemTools::FileExists(license)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Missing license file "
- << languages[i] << ".license.txt" << std::endl);
+ << language << ".license.txt" << std::endl);
return 0;
}
- std::string menu = slaDirectory + "/" + languages[i] + ".menu.txt";
+ std::string menu = slaDirectory + "/" + language + ".menu.txt";
if (!cmSystemTools::FileExists(menu)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Missing menu file "
- << languages[i] << ".menu.txt" << std::endl);
+ << language << ".menu.txt" << std::endl);
return 0;
}
}
@@ -185,19 +185,19 @@ int cmCPackDragNDropGenerator::PackageFiles()
// loop to create dmg files
packageFileNames.clear();
- for (size_t i = 0; i < package_files.size(); i++) {
+ for (auto const& package_file : package_files) {
std::string full_package_name = std::string(toplevel) + std::string("/");
- if (package_files[i] == "ALL_IN_ONE") {
+ if (package_file == "ALL_IN_ONE") {
full_package_name += this->GetOption("CPACK_PACKAGE_FILE_NAME");
} else {
- full_package_name += package_files[i];
+ full_package_name += package_file;
}
full_package_name += std::string(GetOutputExtension());
packageFileNames.push_back(full_package_name);
std::string src_dir = toplevel;
src_dir += "/";
- src_dir += package_files[i];
+ src_dir += package_file;
if (0 == this->CreateDMG(src_dir, full_package_name)) {
return 0;
@@ -226,14 +226,14 @@ bool cmCPackDragNDropGenerator::CreateEmptyFile(std::ostringstream& target,
cmsys::ofstream fout(target.str().c_str(), std::ios::out | std::ios::binary);
if (!fout) {
return false;
- } else {
- // Seek to desired size - 1 byte
- fout.seekp(size - 1, std::ios::beg);
- char byte = 0;
- // Write one byte to ensure file grows
- fout.write(&byte, 1);
}
+ // Seek to desired size - 1 byte
+ fout.seekp(size - 1, std::ios::beg);
+ char byte = 0;
+ // Write one byte to ensure file grows
+ fout.write(&byte, 1);
+
return true;
}
@@ -242,9 +242,9 @@ bool cmCPackDragNDropGenerator::RunCommand(std::ostringstream& command,
{
int exit_code = 1;
- bool result =
- cmSystemTools::RunSingleCommand(command.str().c_str(), output, output,
- &exit_code, 0, this->GeneratorVerbose, 0);
+ bool result = cmSystemTools::RunSingleCommand(command.str().c_str(), output,
+ output, &exit_code, nullptr,
+ this->GeneratorVerbose, 0);
if (!result || exit_code) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Error executing: " << command.str()
@@ -417,6 +417,7 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
temp_image_command << " -ov";
temp_image_command << " -srcfolder \"" << staging.str() << "\"";
temp_image_command << " -volname \"" << cpack_dmg_volume_name << "\"";
+ temp_image_command << " -fs HFS+";
temp_image_command << " -format " << temp_image_format;
temp_image_command << " \"" << temp_image << "\"";
@@ -448,6 +449,8 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
cmsys::RegularExpression mountpoint_regex(".*(/Volumes/[^\n]+)\n.*");
mountpoint_regex.find(attach_output.c_str());
std::string const temp_mount = mountpoint_regex.match(1);
+ std::string const temp_mount_name =
+ temp_mount.substr(sizeof("/Volumes/") - 1);
// Remove dummy padding file so we have enough space on RW image ...
std::ostringstream dummy_padding;
@@ -481,7 +484,7 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
std::ostringstream setup_script_command;
setup_script_command << "osascript"
<< " \"" << cpack_dmg_ds_store_setup_script << "\""
- << " \"" << cpack_dmg_volume_name << "\"";
+ << " \"" << temp_mount_name << "\"";
std::string error;
if (!this->RunCommand(setup_script_command, &error)) {
cmCPackLogger(cmCPackLog::LOG_ERROR,
@@ -551,16 +554,17 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
header_data.push_back(languages.size());
for (size_t i = 0; i < languages.size(); ++i) {
CFStringRef language_cfstring = CFStringCreateWithCString(
- NULL, languages[i].c_str(), kCFStringEncodingUTF8);
+ nullptr, languages[i].c_str(), kCFStringEncodingUTF8);
CFStringRef iso_language =
CFLocaleCreateCanonicalLanguageIdentifierFromString(
- NULL, language_cfstring);
+ nullptr, language_cfstring);
if (!iso_language) {
cmCPackLogger(cmCPackLog::LOG_ERROR, languages[i]
<< " is not a recognized language" << std::endl);
}
- char* iso_language_cstr = (char*)malloc(65);
- CFStringGetCString(iso_language, iso_language_cstr, 64,
+ char iso_language_cstr[65];
+ CFStringGetCString(iso_language, iso_language_cstr,
+ sizeof(iso_language_cstr) - 1,
kCFStringEncodingMacRoman);
LangCode lang = 0;
RegionCode region = 0;
@@ -573,11 +577,9 @@ int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir,
cmCPackLogger(cmCPackLog::LOG_ERROR,
"No language/region code available for "
<< iso_language_cstr << std::endl);
- free(iso_language_cstr);
return 0;
}
#ifdef HAVE_CoreServices
- free(iso_language_cstr);
header_data.push_back(region);
header_data.push_back(i);
header_data.push_back(0);
@@ -767,7 +769,8 @@ std::string cmCPackDragNDropGenerator::GetComponentInstallDirNameSuffix(
bool cmCPackDragNDropGenerator::WriteLicense(
cmGeneratedFileStream& outputStream, int licenseNumber,
- std::string licenseLanguage, std::string licenseFile, std::string* error)
+ std::string licenseLanguage, const std::string& licenseFile,
+ std::string* error)
{
if (!licenseFile.empty() && !singleLicense) {
licenseNumber = 5002;
@@ -793,8 +796,8 @@ bool cmCPackDragNDropGenerator::WriteLicense(
if (!this->BreakLongLine(line, lines, error)) {
return false;
}
- for (size_t i = 0; i < lines.size(); ++i) {
- outputStream << " \"" << lines[i] << "\"\n";
+ for (auto const& l : lines) {
+ outputStream << " \"" << l << "\"\n";
}
}
outputStream << " \"\\n\"\n";
@@ -863,10 +866,11 @@ bool cmCPackDragNDropGenerator::BreakLongLine(const std::string& line,
size_t line_length = max_line_length;
if (i + line_length > line.size()) {
line_length = line.size() - i;
- } else
+ } else {
while (line_length > 0 && line[i + line_length - 1] != ' ') {
line_length = line_length - 1;
}
+ }
if (line_length == 0) {
*error = "Please make sure there are no words "
diff --git a/Source/CPack/cmCPackDragNDropGenerator.h b/Source/CPack/cmCPackDragNDropGenerator.h
index ae2cc173f..d8c5c8337 100644
--- a/Source/CPack/cmCPackDragNDropGenerator.h
+++ b/Source/CPack/cmCPackDragNDropGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackDragNDropGenerator_h
#define cmCPackDragNDropGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <sstream>
#include <stddef.h>
@@ -23,32 +23,30 @@ public:
cmCPackTypeMacro(cmCPackDragNDropGenerator, cmCPackGenerator);
cmCPackDragNDropGenerator();
- virtual ~cmCPackDragNDropGenerator();
+ ~cmCPackDragNDropGenerator() override;
protected:
- int InitializeInternal() CM_OVERRIDE;
- const char* GetOutputExtension() CM_OVERRIDE;
- int PackageFiles() CM_OVERRIDE;
- bool SupportsComponentInstallation() const CM_OVERRIDE;
+ int InitializeInternal() override;
+ const char* GetOutputExtension() override;
+ int PackageFiles() override;
+ bool SupportsComponentInstallation() const override;
bool CopyFile(std::ostringstream& source, std::ostringstream& target);
bool CreateEmptyFile(std::ostringstream& target, size_t size);
bool RunCommand(std::ostringstream& command, std::string* output = 0);
std::string GetComponentInstallDirNameSuffix(
- const std::string& componentName) CM_OVERRIDE;
+ const std::string& componentName) override;
int CreateDMG(const std::string& src_dir, const std::string& output_file);
- std::string InstallPrefix;
-
private:
std::string slaDirectory;
bool singleLicense;
bool WriteLicense(cmGeneratedFileStream& outputStream, int licenseNumber,
- std::string licenseLanguage, std::string licenseFile,
- std::string* error);
+ std::string licenseLanguage,
+ const std::string& licenseFile, std::string* error);
bool BreakLongLine(const std::string& line, std::vector<std::string>& lines,
std::string* error);
void EscapeQuotesAndBackslashes(std::string& line);
diff --git a/Source/CPack/cmCPackFreeBSDGenerator.cxx b/Source/CPack/cmCPackFreeBSDGenerator.cxx
new file mode 100644
index 000000000..91ae1a23f
--- /dev/null
+++ b/Source/CPack/cmCPackFreeBSDGenerator.cxx
@@ -0,0 +1,359 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmCPackFreeBSDGenerator.h"
+
+#include "cmArchiveWrite.h"
+#include "cmCPackArchiveGenerator.h"
+#include "cmCPackLog.h"
+#include "cmGeneratedFileStream.h"
+#include "cmSystemTools.h"
+
+// Needed for ::open() and ::stat()
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <pkg.h>
+
+#include <algorithm>
+
+cmCPackFreeBSDGenerator::cmCPackFreeBSDGenerator()
+ : cmCPackArchiveGenerator(cmArchiveWrite::CompressXZ, "paxr")
+{
+}
+
+int cmCPackFreeBSDGenerator::InitializeInternal()
+{
+ this->SetOptionIfNotSet("CPACK_PACKAGING_INSTALL_PREFIX", "/usr/local");
+ this->SetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", "0");
+ return this->Superclass::InitializeInternal();
+}
+
+cmCPackFreeBSDGenerator::~cmCPackFreeBSDGenerator()
+{
+}
+
+// This is a wrapper, for use only in stream-based output,
+// that will output a string in UCL escaped fashion (in particular,
+// quotes and backslashes are escaped). The list of characters
+// to escape is taken from https://github.com/vstakhov/libucl
+// (which is the reference implementation pkg(8) refers to).
+class EscapeQuotes
+{
+public:
+ const std::string& value;
+
+ EscapeQuotes(const std::string& s)
+ : value(s)
+ {
+ }
+};
+
+// Output a string as "string" with escaping applied.
+cmGeneratedFileStream& operator<<(cmGeneratedFileStream& s,
+ const EscapeQuotes& v)
+{
+ s << '"';
+ for (std::string::size_type i = 0; i < v.value.length(); ++i) {
+ char c = v.value[i];
+ switch (c) {
+ case '\n':
+ s << "\\n";
+ break;
+ case '\r':
+ s << "\\r";
+ break;
+ case '\b':
+ s << "\\b";
+ break;
+ case '\t':
+ s << "\\t";
+ break;
+ case '\f':
+ s << "\\f";
+ break;
+ case '\\':
+ s << "\\\\";
+ break;
+ case '"':
+ s << "\\\"";
+ break;
+ default:
+ s << c;
+ break;
+ }
+ }
+ s << '"';
+ return s;
+}
+
+// The following classes are all helpers for writing out the UCL
+// manifest file (it also looks like JSON). ManifestKey just has
+// a (string-valued) key; subclasses add a specific kind of
+// value-type to the key, and implement write_value() to output
+// the corresponding UCL.
+class ManifestKey
+{
+public:
+ std::string key;
+
+ ManifestKey(const std::string& k)
+ : key(k)
+ {
+ }
+
+ virtual ~ManifestKey() {}
+
+ // Output the value associated with this key to the stream @p s.
+ // Format is to be decided by subclasses.
+ virtual void write_value(cmGeneratedFileStream& s) const = 0;
+};
+
+// Basic string-value (e.g. "name": "cmake")
+class ManifestKeyValue : public ManifestKey
+{
+public:
+ std::string value;
+
+ ManifestKeyValue(const std::string& k, const std::string& v)
+ : ManifestKey(k)
+ , value(v)
+ {
+ }
+
+ void write_value(cmGeneratedFileStream& s) const override
+ {
+ s << EscapeQuotes(value);
+ }
+};
+
+// List-of-strings values (e.g. "licenses": ["GPLv2", "LGPLv2"])
+class ManifestKeyListValue : public ManifestKey
+{
+public:
+ typedef std::vector<std::string> VList;
+ VList value;
+
+ ManifestKeyListValue(const std::string& k)
+ : ManifestKey(k)
+ {
+ }
+
+ ManifestKeyListValue& operator<<(const std::string& v)
+ {
+ value.push_back(v);
+ return *this;
+ }
+
+ ManifestKeyListValue& operator<<(const std::vector<std::string>& v)
+ {
+ for (VList::const_iterator it = v.begin(); it != v.end(); ++it) {
+ (*this) << (*it);
+ }
+ return *this;
+ }
+
+ void write_value(cmGeneratedFileStream& s) const override
+ {
+ bool with_comma = false;
+
+ s << '[';
+ for (VList::const_iterator it = value.begin(); it != value.end(); ++it) {
+ s << (with_comma ? ',' : ' ');
+ s << EscapeQuotes(*it);
+ with_comma = true;
+ }
+ s << " ]";
+ }
+};
+
+// Deps: actually a dictionary, but we'll treat it as a
+// list so we only name the deps, and produce dictionary-
+// like output via write_value()
+class ManifestKeyDepsValue : public ManifestKeyListValue
+{
+public:
+ ManifestKeyDepsValue(const std::string& k)
+ : ManifestKeyListValue(k)
+ {
+ }
+
+ void write_value(cmGeneratedFileStream& s) const override
+ {
+ s << "{\n";
+ for (VList::const_iterator it = value.begin(); it != value.end(); ++it) {
+ s << " \"" << *it << "\": {\"origin\": \"" << *it << "\"},\n";
+ }
+ s << '}';
+ }
+};
+
+// Write one of the key-value classes (above) to the stream @p s
+cmGeneratedFileStream& operator<<(cmGeneratedFileStream& s,
+ const ManifestKey& v)
+{
+ s << '"' << v.key << "\": ";
+ v.write_value(s);
+ s << ",\n";
+ return s;
+}
+
+// Look up variable; if no value is set, returns an empty string;
+// 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);
+ if (!pv) {
+ return std::string();
+ } else {
+ return pv;
+ }
+}
+
+// Produce UCL in the given @p manifest file for the common
+// manifest fields (common to the compact and regular formats),
+// by reading the CPACK_FREEBSD_* variables.
+void cmCPackFreeBSDGenerator::write_manifest_fields(
+ cmGeneratedFileStream& manifest)
+{
+ manifest << ManifestKeyValue("name",
+ var_lookup("CPACK_FREEBSD_PACKAGE_NAME"));
+ manifest << ManifestKeyValue("origin",
+ var_lookup("CPACK_FREEBSD_PACKAGE_ORIGIN"));
+ manifest << ManifestKeyValue("version",
+ var_lookup("CPACK_FREEBSD_PACKAGE_VERSION"));
+ manifest << ManifestKeyValue("maintainer",
+ var_lookup("CPACK_FREEBSD_PACKAGE_MAINTAINER"));
+ manifest << ManifestKeyValue("comment",
+ var_lookup("CPACK_FREEBSD_PACKAGE_COMMENT"));
+ manifest << ManifestKeyValue(
+ "desc", var_lookup("CPACK_FREEBSD_PACKAGE_DESCRIPTION"));
+ manifest << ManifestKeyValue("www", var_lookup("CPACK_FREEBSD_PACKAGE_WWW"));
+ std::vector<std::string> licenses;
+ cmSystemTools::ExpandListArgument(
+ var_lookup("CPACK_FREEBSD_PACKAGE_LICENSE"), licenses);
+ std::string licenselogic("single");
+ if (licenses.size() < 1) {
+ cmSystemTools::SetFatalErrorOccured();
+ } else if (licenses.size() > 1) {
+ licenselogic = var_lookup("CPACK_FREEBSD_PACKAGE_LICENSE_LOGIC");
+ }
+ manifest << ManifestKeyValue("licenselogic", licenselogic);
+ manifest << (ManifestKeyListValue("licenses") << licenses);
+ std::vector<std::string> categories;
+ cmSystemTools::ExpandListArgument(
+ var_lookup("CPACK_FREEBSD_PACKAGE_CATEGORIES"), categories);
+ manifest << (ManifestKeyListValue("categories") << categories);
+ manifest << ManifestKeyValue("prefix", var_lookup("CMAKE_INSTALL_PREFIX"));
+ std::vector<std::string> deps;
+ cmSystemTools::ExpandListArgument(var_lookup("CPACK_FREEBSD_PACKAGE_DEPS"),
+ deps);
+ if (deps.size() > 0) {
+ manifest << (ManifestKeyDepsValue("deps") << deps);
+ }
+}
+
+// Package only actual files; others are ignored (in particular,
+// intermediate subdirectories are ignored).
+static bool ignore_file(const std::string& filename)
+{
+ struct stat statbuf;
+
+ if (!((stat(filename.c_str(), &statbuf) >= 0) &&
+ ((statbuf.st_mode & S_IFMT) == S_IFREG))) {
+ return true;
+ }
+ // May be other reasons to return false
+ return false;
+}
+
+// Write the given list of @p files to the manifest stream @p s,
+// as the UCL field "files" (which is dictionary-valued, to
+// associate filenames with hashes). All the files are transformed
+// to paths relative to @p toplevel, with a leading / (since the paths
+// in FreeBSD package files are supposed to be absolute).
+void write_manifest_files(cmGeneratedFileStream& s,
+ const std::string& toplevel,
+ const std::vector<std::string>& files)
+{
+ const char* c_toplevel = toplevel.c_str();
+ std::vector<std::string>::const_iterator it;
+
+ s << "\"files\": {\n";
+ for (it = files.begin(); it != files.end(); ++it) {
+ s << " \"/" << cmSystemTools::RelativePath(c_toplevel, it->c_str())
+ << "\": \""
+ << "<sha256>"
+ << "\",\n";
+ }
+ s << " },\n";
+}
+
+static bool has_suffix(const std::string& str, const std::string& suffix)
+{
+ return str.size() >= suffix.size() &&
+ str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
+}
+
+int cmCPackFreeBSDGenerator::PackageFiles()
+{
+ if (!this->ReadListFile("CPackFreeBSD.cmake")) {
+ cmCPackLogger(cmCPackLog::LOG_ERROR,
+ "Error while execution CPackFreeBSD.cmake" << std::endl);
+ return 0;
+ }
+
+ std::vector<std::string>::const_iterator fileIt;
+ std::string dir = cmSystemTools::GetCurrentWorkingDirectory();
+ cmSystemTools::ChangeDirectory(toplevel);
+
+ files.erase(std::remove_if(files.begin(), files.end(), ignore_file),
+ files.end());
+
+ std::string manifestname = toplevel + "/+MANIFEST";
+ {
+ cmGeneratedFileStream manifest(manifestname.c_str());
+ manifest << "{\n";
+ write_manifest_fields(manifest);
+ write_manifest_files(manifest, toplevel, files);
+ manifest << "}\n";
+ }
+
+ cmCPackLogger(cmCPackLog::LOG_DEBUG, "Toplevel: " << toplevel << std::endl);
+
+ if (WantsComponentInstallation()) {
+ // CASE 1 : COMPONENT ALL-IN-ONE package
+ // If ALL COMPONENTS in ONE package has been requested
+ // then the package file is unique and should be open here.
+ if (componentPackageMethod == ONE_PACKAGE) {
+ return PackageComponentsAllInOne();
+ }
+ // CASE 2 : COMPONENT CLASSICAL package(s) (i.e. not all-in-one)
+ // There will be 1 package for each component group
+ // however one may require to ignore component group and
+ // in this case you'll get 1 package for each component.
+ return PackageComponents(componentPackageMethod ==
+ ONE_PACKAGE_PER_COMPONENT);
+ }
+
+ std::string output_dir =
+ cmSystemTools::CollapseCombinedPath(toplevel, "../");
+ pkg_create_from_manifest(output_dir.c_str(), ::TXZ, toplevel.c_str(),
+ manifestname.c_str(), NULL);
+
+ std::string broken_suffix = std::string("-") +
+ var_lookup("CPACK_TOPLEVEL_TAG") + std::string(GetOutputExtension());
+ for (std::vector<std::string>::iterator it = packageFileNames.begin();
+ it != packageFileNames.end(); ++it) {
+ cmCPackLogger(cmCPackLog::LOG_DEBUG, "Packagefile " << *it << std::endl);
+ if (has_suffix(*it, broken_suffix)) {
+ it->replace(it->size() - broken_suffix.size(), std::string::npos,
+ GetOutputExtension());
+ break;
+ }
+ }
+
+ cmSystemTools::ChangeDirectory(dir);
+ return 1;
+}
diff --git a/Source/CPack/cmCPackFreeBSDGenerator.h b/Source/CPack/cmCPackFreeBSDGenerator.h
new file mode 100644
index 000000000..99d2e2421
--- /dev/null
+++ b/Source/CPack/cmCPackFreeBSDGenerator.h
@@ -0,0 +1,37 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmCPackFreeBSDGenerator_h
+#define cmCPackFreeBSDGenerator_h
+
+#include <cmConfigure.h>
+
+#include "cmCPackArchiveGenerator.h"
+#include "cmCPackGenerator.h"
+
+class cmGeneratedFileStream;
+
+/** \class cmCPackFreeBSDGenerator
+ * \brief A generator for FreeBSD package files (TXZ with a manifest)
+ *
+ */
+class cmCPackFreeBSDGenerator : public cmCPackArchiveGenerator
+{
+public:
+ cmCPackTypeMacro(cmCPackFreeBSDGenerator, cmCPackArchiveGenerator);
+ /**
+ * Construct generator
+ */
+ cmCPackFreeBSDGenerator();
+ ~cmCPackFreeBSDGenerator() override;
+
+ int InitializeInternal() override;
+ int PackageFiles() override;
+
+protected:
+ const char* GetOutputExtension() override { return ".txz"; }
+
+ std::string var_lookup(const char* var_name);
+ void write_manifest_fields(cmGeneratedFileStream&);
+};
+
+#endif
diff --git a/Source/CPack/cmCPackGenerator.cxx b/Source/CPack/cmCPackGenerator.cxx
index d8e2753cf..ecb5adb47 100644
--- a/Source/CPack/cmCPackGenerator.cxx
+++ b/Source/CPack/cmCPackGenerator.cxx
@@ -6,6 +6,7 @@
#include "cmsys/Glob.hxx"
#include "cmsys/RegularExpression.hxx"
#include <algorithm>
+#include <memory> // IWYU pragma: keep
#include <utility>
#include "cmCPackComponentGroup.h"
@@ -17,7 +18,6 @@
#include "cmStateSnapshot.h"
#include "cmWorkingDirectory.h"
#include "cmXMLSafe.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
#if defined(__HAIKU__)
@@ -28,14 +28,14 @@
cmCPackGenerator::cmCPackGenerator()
{
this->GeneratorVerbose = cmSystemTools::OUTPUT_NONE;
- this->MakefileMap = CM_NULLPTR;
- this->Logger = CM_NULLPTR;
+ this->MakefileMap = nullptr;
+ this->Logger = nullptr;
this->componentPackageMethod = ONE_PACKAGE_PER_GROUP;
}
cmCPackGenerator::~cmCPackGenerator()
{
- this->MakefileMap = CM_NULLPTR;
+ this->MakefileMap = nullptr;
}
void cmCPackGeneratorProgress(const char* msg, float prog, void* ptr)
@@ -156,7 +156,7 @@ int cmCPackGenerator::PrepareNames()
}
const char* algoSignature = this->GetOption("CPACK_PACKAGE_CHECKSUM");
if (algoSignature) {
- if (cmCryptoHash::New(algoSignature).get() == CM_NULLPTR) {
+ if (!cmCryptoHash::New(algoSignature)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot recognize algorithm: "
<< algoSignature << std::endl);
return 0;
@@ -248,25 +248,23 @@ int cmCPackGenerator::InstallProjectViaInstallCommands(
cmSystemTools::PutEnv(tempInstallDirectoryEnv);
std::vector<std::string> installCommandsVector;
cmSystemTools::ExpandListArgument(installCommands, installCommandsVector);
- std::vector<std::string>::iterator it;
- for (it = installCommandsVector.begin(); it != installCommandsVector.end();
- ++it) {
- cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << *it << std::endl);
+ for (std::string const& ic : installCommandsVector) {
+ cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << ic << std::endl);
std::string output;
int retVal = 1;
bool resB =
- cmSystemTools::RunSingleCommand(it->c_str(), &output, &output, &retVal,
- CM_NULLPTR, this->GeneratorVerbose, 0);
+ cmSystemTools::RunSingleCommand(ic.c_str(), &output, &output, &retVal,
+ nullptr, this->GeneratorVerbose, 0);
if (!resB || retVal) {
std::string tmpFile = this->GetOption("CPACK_TOPLEVEL_DIRECTORY");
tmpFile += "/InstallOutput.log";
cmGeneratedFileStream ofs(tmpFile.c_str());
- ofs << "# Run command: " << *it << std::endl
+ ofs << "# Run command: " << ic << std::endl
<< "# Output:" << std::endl
<< output << std::endl;
cmCPackLogger(
cmCPackLog::LOG_ERROR, "Problem running install command: "
- << *it << std::endl
+ << ic << std::endl
<< "Please check " << tmpFile << " for errors" << std::endl);
return 0;
}
@@ -286,12 +284,10 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories(
std::vector<std::string> ignoreFilesRegexString;
cmSystemTools::ExpandListArgument(cpackIgnoreFiles,
ignoreFilesRegexString);
- std::vector<std::string>::iterator it;
- for (it = ignoreFilesRegexString.begin();
- it != ignoreFilesRegexString.end(); ++it) {
+ for (std::string const& ifr : ignoreFilesRegexString) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
- "Create ignore files regex for: " << *it << std::endl);
- ignoreFilesRegex.push_back(it->c_str());
+ "Create ignore files regex for: " << ifr << std::endl);
+ ignoreFilesRegex.push_back(ifr.c_str());
}
}
const char* installDirectories =
@@ -313,7 +309,7 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories(
const std::string& tempDir = tempInstallDirectory;
for (it = installDirectoriesVector.begin();
it != installDirectoriesVector.end(); ++it) {
- std::vector<std::pair<std::string, std::string> > symlinkedFiles;
+ std::vector<std::pair<std::string, std::string>> symlinkedFiles;
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Find files" << std::endl);
cmsys::Glob gl;
std::string top = *it;
@@ -334,15 +330,14 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories(
files = gl.GetFiles();
std::vector<std::string>::iterator gfit;
std::vector<cmsys::RegularExpression>::iterator regIt;
- for (gfit = files.begin(); gfit != files.end(); ++gfit) {
+ for (std::string const& gf : files) {
bool skip = false;
- std::string inFile = *gfit;
- if (cmSystemTools::FileIsDirectory(*gfit)) {
+ std::string inFile = gf;
+ if (cmSystemTools::FileIsDirectory(gf)) {
inFile += '/';
}
- for (regIt = ignoreFilesRegex.begin(); regIt != ignoreFilesRegex.end();
- ++regIt) {
- if (regIt->find(inFile.c_str())) {
+ for (cmsys::RegularExpression& reg : ignoreFilesRegex) {
+ if (reg.find(inFile.c_str())) {
cmCPackLogger(cmCPackLog::LOG_VERBOSE,
"Ignore file: " << inFile << std::endl);
skip = true;
@@ -353,7 +348,7 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories(
}
std::string filePath = tempDir;
filePath += "/" + subdir + "/" +
- cmSystemTools::RelativePath(top.c_str(), gfit->c_str());
+ cmSystemTools::RelativePath(top.c_str(), gf.c_str());
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Copy file: "
<< inFile << " -> " << filePath << std::endl);
/* If the file is a symlink we will have to re-create it */
@@ -377,33 +372,30 @@ int cmCPackGenerator::InstallProjectViaInstalledDirectories(
}
/* rebuild symlinks in the installed tree */
if (!symlinkedFiles.empty()) {
- std::vector<std::pair<std::string, std::string> >::iterator
- symlinkedIt;
std::string curDir = cmSystemTools::GetCurrentWorkingDirectory();
std::string goToDir = tempDir;
goToDir += "/" + subdir;
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Change dir to: " << goToDir
<< std::endl);
cmWorkingDirectory workdir(goToDir);
- for (symlinkedIt = symlinkedFiles.begin();
- symlinkedIt != symlinkedFiles.end(); ++symlinkedIt) {
+ for (auto const& symlinked : symlinkedFiles) {
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Will create a symlink: "
- << symlinkedIt->second << "--> "
- << symlinkedIt->first << std::endl);
+ << symlinked.second << "--> " << symlinked.first
+ << std::endl);
// make sure directory exists for symlink
std::string destDir =
- cmSystemTools::GetFilenamePath(symlinkedIt->second);
+ cmSystemTools::GetFilenamePath(symlinked.second);
if (!destDir.empty() && !cmSystemTools::MakeDirectory(destDir)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot create dir: "
<< destDir << "\nTrying to create symlink: "
- << symlinkedIt->second << "--> "
- << symlinkedIt->first << std::endl);
+ << symlinked.second << "--> " << symlinked.first
+ << std::endl);
}
- if (!cmSystemTools::CreateSymlink(symlinkedIt->first,
- symlinkedIt->second)) {
+ if (!cmSystemTools::CreateSymlink(symlinked.first,
+ symlinked.second)) {
cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot create symlink: "
- << symlinkedIt->second << "--> "
- << symlinkedIt->first << std::endl);
+ << symlinked.second << "--> " << symlinked.first
+ << std::endl);
return 0;
}
}
@@ -424,10 +416,7 @@ int cmCPackGenerator::InstallProjectViaInstallScript(
<< std::endl);
std::vector<std::string> cmakeScriptsVector;
cmSystemTools::ExpandListArgument(cmakeScripts, cmakeScriptsVector);
- std::vector<std::string>::iterator it;
- for (it = cmakeScriptsVector.begin(); it != cmakeScriptsVector.end();
- ++it) {
- std::string installScript = *it;
+ for (std::string const& installScript : cmakeScriptsVector) {
cmCPackLogger(cmCPackLog::LOG_OUTPUT,
"- Install script: " << installScript << std::endl);
@@ -533,10 +522,8 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
if (installTypes && *installTypes) {
std::vector<std::string> installTypesVector;
cmSystemTools::ExpandListArgument(installTypes, installTypesVector);
- std::vector<std::string>::iterator installTypeIt;
- for (installTypeIt = installTypesVector.begin();
- installTypeIt != installTypesVector.end(); ++installTypeIt) {
- this->GetInstallationType(installProjectName, *installTypeIt);
+ for (std::string const& installType : installTypesVector) {
+ this->GetInstallationType(installProjectName, installType);
}
}
@@ -546,10 +533,8 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
const char* components = this->GetOption(componentsVar);
if (components && *components) {
cmSystemTools::ExpandListArgument(components, componentsVector);
- std::vector<std::string>::iterator compIt;
- for (compIt = componentsVector.begin();
- compIt != componentsVector.end(); ++compIt) {
- GetComponent(installProjectName, *compIt);
+ for (std::string const& comp : componentsVector) {
+ GetComponent(installProjectName, comp);
}
componentInstall = true;
}
@@ -610,11 +595,9 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
"- Install project: " << installProjectName << std::endl);
// Run the installation for each component
- std::vector<std::string>::iterator componentIt;
- for (componentIt = componentsVector.begin();
- componentIt != componentsVector.end(); ++componentIt) {
+ for (std::string const& component : componentsVector) {
std::string tempInstallDirectory = baseTempInstallDirectory;
- installComponent = *componentIt;
+ installComponent = component;
if (componentInstall) {
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Install component: "
<< installComponent << std::endl);
@@ -627,8 +610,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
cm.AddCMakePaths();
cm.SetProgressCallback(cmCPackGeneratorProgress, this);
cmGlobalGenerator gg(&cm);
- CM_AUTO_PTR<cmMakefile> mf(
- new cmMakefile(&gg, cm.GetCurrentSnapshot()));
+ cmMakefile mf(&gg, cm.GetCurrentSnapshot());
if (!installSubDirectory.empty() && installSubDirectory != "/" &&
installSubDirectory != ".") {
tempInstallDirectory += installSubDirectory;
@@ -674,11 +656,11 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
if (this->GetOption("CPACK_INSTALL_PREFIX")) {
dir += this->GetOption("CPACK_INSTALL_PREFIX");
}
- mf->AddDefinition("CMAKE_INSTALL_PREFIX", dir.c_str());
+ mf.AddDefinition("CMAKE_INSTALL_PREFIX", dir.c_str());
cmCPackLogger(
cmCPackLog::LOG_DEBUG,
- "- Using DESTDIR + CPACK_INSTALL_PREFIX... (mf->AddDefinition)"
+ "- Using DESTDIR + CPACK_INSTALL_PREFIX... (mf.AddDefinition)"
<< std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"- Setting CMAKE_INSTALL_PREFIX to '" << dir << "'"
@@ -715,8 +697,8 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
return 0;
}
} else {
- mf->AddDefinition("CMAKE_INSTALL_PREFIX",
- tempInstallDirectory.c_str());
+ mf.AddDefinition("CMAKE_INSTALL_PREFIX",
+ tempInstallDirectory.c_str());
if (!cmsys::SystemTools::MakeDirectory(
tempInstallDirectory.c_str())) {
@@ -727,7 +709,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
}
cmCPackLogger(cmCPackLog::LOG_DEBUG,
- "- Using non-DESTDIR install... (mf->AddDefinition)"
+ "- Using non-DESTDIR install... (mf.AddDefinition)"
<< std::endl);
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"- Setting CMAKE_INSTALL_PREFIX to '"
@@ -735,19 +717,19 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
}
if (!buildConfig.empty()) {
- mf->AddDefinition("BUILD_TYPE", buildConfig.c_str());
+ mf.AddDefinition("BUILD_TYPE", buildConfig.c_str());
}
std::string installComponentLowerCase =
cmSystemTools::LowerCase(installComponent);
if (installComponentLowerCase != "all") {
- mf->AddDefinition("CMAKE_INSTALL_COMPONENT",
- installComponent.c_str());
+ mf.AddDefinition("CMAKE_INSTALL_COMPONENT",
+ installComponent.c_str());
}
// strip on TRUE, ON, 1, one or several file names, but not on
// FALSE, OFF, 0 and an empty string
if (!cmSystemTools::IsOff(this->GetOption("CPACK_STRIP_FILES"))) {
- mf->AddDefinition("CMAKE_INSTALL_DO_STRIP", "1");
+ mf.AddDefinition("CMAKE_INSTALL_DO_STRIP", "1");
}
// Remember the list of files before installation
// of the current component (if we are in component install)
@@ -767,7 +749,7 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
// If CPack was asked to warn on ABSOLUTE INSTALL DESTINATION
// then forward request to cmake_install.cmake script
if (this->IsOn("CPACK_WARN_ON_ABSOLUTE_INSTALL_DESTINATION")) {
- mf->AddDefinition("CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION", "1");
+ mf.AddDefinition("CMAKE_WARN_ON_ABSOLUTE_INSTALL_DESTINATION", "1");
}
// If current CPack generator does support
// ABSOLUTE INSTALL DESTINATION or CPack has been asked for
@@ -775,18 +757,17 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
// as soon as it occurs (before installing file)
if (!SupportsAbsoluteDestination() ||
this->IsOn("CPACK_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION")) {
- mf->AddDefinition("CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION",
- "1");
+ mf.AddDefinition("CMAKE_ERROR_ON_ABSOLUTE_INSTALL_DESTINATION", "1");
}
// do installation
- int res = mf->ReadListFile(installFile.c_str());
+ int res = mf.ReadListFile(installFile.c_str());
// forward definition of CMAKE_ABSOLUTE_DESTINATION_FILES
// to CPack (may be used by generators like CPack RPM or DEB)
// in order to transparently handle ABSOLUTE PATH
- if (mf->GetDefinition("CMAKE_ABSOLUTE_DESTINATION_FILES")) {
- mf->AddDefinition(
+ if (mf.GetDefinition("CMAKE_ABSOLUTE_DESTINATION_FILES")) {
+ mf.AddDefinition(
"CPACK_ABSOLUTE_DESTINATION_FILES",
- mf->GetDefinition("CMAKE_ABSOLUTE_DESTINATION_FILES"));
+ mf.GetDefinition("CMAKE_ABSOLUTE_DESTINATION_FILES"));
}
// Now rebuild the list of files after installation
@@ -820,13 +801,12 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
}
}
- if (CM_NULLPTR !=
- mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")) {
+ if (nullptr != mf.GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES")) {
if (!absoluteDestFiles.empty()) {
absoluteDestFiles += ";";
}
absoluteDestFiles +=
- mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES");
+ mf.GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES");
cmCPackLogger(cmCPackLog::LOG_DEBUG,
"Got some ABSOLUTE DESTINATION FILES: "
<< absoluteDestFiles << std::endl);
@@ -835,18 +815,18 @@ int cmCPackGenerator::InstallProjectViaInstallCMakeProjects(
std::string absoluteDestFileComponent =
std::string("CPACK_ABSOLUTE_DESTINATION_FILES") + "_" +
GetComponentInstallDirNameSuffix(installComponent);
- if (CM_NULLPTR != this->GetOption(absoluteDestFileComponent)) {
+ if (nullptr != this->GetOption(absoluteDestFileComponent)) {
std::string absoluteDestFilesListComponent =
this->GetOption(absoluteDestFileComponent);
absoluteDestFilesListComponent += ";";
absoluteDestFilesListComponent +=
- mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES");
+ mf.GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES");
this->SetOption(absoluteDestFileComponent,
absoluteDestFilesListComponent.c_str());
} else {
this->SetOption(
absoluteDestFileComponent,
- mf->GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES"));
+ mf.GetDefinition("CPACK_ABSOLUTE_DESTINATION_FILES"));
}
}
}
@@ -982,7 +962,7 @@ int cmCPackGenerator::DoPackage()
/* Prepare checksum algorithm*/
const char* algo = this->GetOption("CPACK_PACKAGE_CHECKSUM");
- CM_AUTO_PTR<cmCryptoHash> crypto = cmCryptoHash::New(algo ? algo : "");
+ std::unique_ptr<cmCryptoHash> crypto = cmCryptoHash::New(algo ? algo : "");
/*
* Copy the generated packages to final destination
@@ -992,12 +972,11 @@ int cmCPackGenerator::DoPackage()
*/
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Copying final package(s) ["
<< packageFileNames.size() << "]:" << std::endl);
- std::vector<std::string>::iterator it;
/* now copy package one by one */
- for (it = packageFileNames.begin(); it != packageFileNames.end(); ++it) {
+ for (std::string const& pkgFileName : packageFileNames) {
std::string tmpPF(this->GetOption("CPACK_OUTPUT_FILE_PREFIX"));
- std::string filename(cmSystemTools::GetFilenameName(*it));
- tempPackageFileName = it->c_str();
+ std::string filename(cmSystemTools::GetFilenameName(pkgFileName));
+ tempPackageFileName = pkgFileName.c_str();
tmpPF += "/" + filename;
const char* packageFileName = tmpPF.c_str();
cmCPackLogger(cmCPackLog::LOG_DEBUG, "Copy final package(s): "
@@ -1016,10 +995,9 @@ int cmCPackGenerator::DoPackage()
<< packageFileName << " generated." << std::endl);
/* Generate checksum file */
- if (crypto.get() != CM_NULLPTR) {
+ if (crypto) {
std::string hashFile(this->GetOption("CPACK_OUTPUT_FILE_PREFIX"));
- hashFile +=
- "/" + filename.substr(0, filename.rfind(this->GetOutputExtension()));
+ hashFile += "/" + filename;
hashFile += "." + cmSystemTools::LowerCase(algo);
cmsys::ofstream outF(hashFile.c_str());
if (!outF) {
@@ -1225,7 +1203,7 @@ int cmCPackGenerator::PrepareGroupingKind()
std::string groupingType;
// Second way to specify grouping
- if (CM_NULLPTR != this->GetOption("CPACK_COMPONENTS_GROUPING")) {
+ if (nullptr != this->GetOption("CPACK_COMPONENTS_GROUPING")) {
groupingType = this->GetOption("CPACK_COMPONENTS_GROUPING");
}
@@ -1407,7 +1385,7 @@ cmCPackComponent* cmCPackGenerator::GetComponent(
component->Group = GetComponentGroup(projectName, groupName);
component->Group->Components.push_back(component);
} else {
- component->Group = CM_NULLPTR;
+ component->Group = nullptr;
}
const char* description = this->GetOption(macroPrefix + "_DESCRIPTION");
@@ -1421,10 +1399,9 @@ cmCPackComponent* cmCPackGenerator::GetComponent(
std::vector<std::string> installTypesVector;
cmSystemTools::ExpandListArgument(installTypes, installTypesVector);
std::vector<std::string>::iterator installTypesIt;
- for (installTypesIt = installTypesVector.begin();
- installTypesIt != installTypesVector.end(); ++installTypesIt) {
+ for (std::string const& installType : installTypesVector) {
component->InstallationTypes.push_back(
- this->GetInstallationType(projectName, *installTypesIt));
+ this->GetInstallationType(projectName, installType));
}
}
@@ -1434,9 +1411,8 @@ cmCPackComponent* cmCPackGenerator::GetComponent(
std::vector<std::string> dependsVector;
cmSystemTools::ExpandListArgument(depends, dependsVector);
std::vector<std::string>::iterator dependIt;
- for (dependIt = dependsVector.begin(); dependIt != dependsVector.end();
- ++dependIt) {
- cmCPackComponent* child = GetComponent(projectName, *dependIt);
+ for (std::string const& depend : dependsVector) {
+ cmCPackComponent* child = GetComponent(projectName, depend);
component->Dependencies.push_back(child);
child->ReverseDependencies.push_back(component);
}
@@ -1475,7 +1451,7 @@ cmCPackComponentGroup* cmCPackGenerator::GetComponentGroup(
group->ParentGroup = GetComponentGroup(projectName, parentGroupName);
group->ParentGroup->Subgroups.push_back(group);
} else {
- group->ParentGroup = CM_NULLPTR;
+ group->ParentGroup = nullptr;
}
}
return group;
diff --git a/Source/CPack/cmCPackGenerator.h b/Source/CPack/cmCPackGenerator.h
index 45777fa05..4e3a6e038 100644
--- a/Source/CPack/cmCPackGenerator.h
+++ b/Source/CPack/cmCPackGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackGenerator_h
#define cmCPackGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <map>
#include <sstream>
@@ -105,7 +105,7 @@ protected:
cmInstalledFile const* GetInstalledFile(std::string const& name) const;
virtual const char* GetOutputExtension() { return ".cpack"; }
- virtual const char* GetOutputPostfix() { return CM_NULLPTR; }
+ virtual const char* GetOutputPostfix() { return nullptr; }
/**
* Prepare requested grouping kind from CPACK_xxx vars
@@ -299,7 +299,7 @@ private:
#define cmCPackTypeMacro(klass, superclass) \
typedef superclass Superclass; \
- const char* GetNameOfClass() CM_OVERRIDE { return #klass; } \
+ const char* GetNameOfClass() override { return #klass; } \
static cmCPackGenerator* CreateGenerator() { return new klass; } \
class cmCPackTypeMacro_UseTrailingSemicolon
diff --git a/Source/CPack/cmCPackGeneratorFactory.cxx b/Source/CPack/cmCPackGeneratorFactory.cxx
index 31f48c7e3..4b81bbc5f 100644
--- a/Source/CPack/cmCPackGeneratorFactory.cxx
+++ b/Source/CPack/cmCPackGeneratorFactory.cxx
@@ -2,13 +2,16 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackGeneratorFactory.h"
-#include "cmConfigure.h"
#include <ostream>
#include <utility>
#include "IFW/cmCPackIFWGenerator.h"
#include "cmAlgorithms.h"
#include "cmCPack7zGenerator.h"
+#ifdef HAVE_FREEBSD_PKG
+#include "cmCPackFreeBSDGenerator.h"
+#endif
+#include "cmCPackDebGenerator.h"
#include "cmCPackGenerator.h"
#include "cmCPackLog.h"
#include "cmCPackNSISGenerator.h"
@@ -34,7 +37,6 @@
#if !defined(_WIN32) && !defined(__QNXNTO__) && !defined(__BEOS__) && \
!defined(__HAIKU__)
-#include "cmCPackDebGenerator.h"
#include "cmCPackRPMGenerator.h"
#endif
@@ -99,6 +101,10 @@ cmCPackGeneratorFactory::cmCPackGeneratorFactory()
this->RegisterGenerator("TZ", "Tar Compress compression",
cmCPackTarCompressGenerator::CreateGenerator);
}
+ if (cmCPackDebGenerator::CanGenerate()) {
+ this->RegisterGenerator("DEB", "Debian packages",
+ cmCPackDebGenerator::CreateGenerator);
+ }
#ifdef __APPLE__
if (cmCPackDragNDropGenerator::CanGenerate()) {
this->RegisterGenerator("DragNDrop", "Mac OSX Drag And Drop",
@@ -123,15 +129,17 @@ cmCPackGeneratorFactory::cmCPackGeneratorFactory()
#endif
#if !defined(_WIN32) && !defined(__QNXNTO__) && !defined(__BEOS__) && \
!defined(__HAIKU__)
- if (cmCPackDebGenerator::CanGenerate()) {
- this->RegisterGenerator("DEB", "Debian packages",
- cmCPackDebGenerator::CreateGenerator);
- }
if (cmCPackRPMGenerator::CanGenerate()) {
this->RegisterGenerator("RPM", "RPM packages",
cmCPackRPMGenerator::CreateGenerator);
}
#endif
+#ifdef HAVE_FREEBSD_PKG
+ if (cmCPackFreeBSDGenerator::CanGenerate()) {
+ this->RegisterGenerator("FREEBSD", "FreeBSD pkg(8) packages",
+ cmCPackFreeBSDGenerator::CreateGenerator);
+ }
+#endif
}
cmCPackGeneratorFactory::~cmCPackGeneratorFactory()
@@ -144,7 +152,7 @@ cmCPackGenerator* cmCPackGeneratorFactory::NewGenerator(
{
cmCPackGenerator* gen = this->NewGeneratorInternal(name);
if (!gen) {
- return CM_NULLPTR;
+ return nullptr;
}
this->Generators.push_back(gen);
gen->SetLogger(this->Logger);
@@ -157,7 +165,7 @@ cmCPackGenerator* cmCPackGeneratorFactory::NewGeneratorInternal(
cmCPackGeneratorFactory::t_GeneratorCreatorsMap::iterator it =
this->GeneratorCreators.find(name);
if (it == this->GeneratorCreators.end()) {
- return CM_NULLPTR;
+ return nullptr;
}
return (it->second)();
}
diff --git a/Source/CPack/cmCPackLog.cxx b/Source/CPack/cmCPackLog.cxx
index 5c7123959..a3ca4b590 100644
--- a/Source/CPack/cmCPackLog.cxx
+++ b/Source/CPack/cmCPackLog.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCPackLog.h"
-#include "cmConfigure.h"
#include <iostream>
#include "cmGeneratedFileStream.h"
@@ -19,13 +18,13 @@ cmCPackLog::cmCPackLog()
this->DefaultOutput = &std::cout;
this->DefaultError = &std::cerr;
- this->LogOutput = CM_NULLPTR;
+ this->LogOutput = nullptr;
this->LogOutputCleanup = false;
}
cmCPackLog::~cmCPackLog()
{
- this->SetLogOutputStream(CM_NULLPTR);
+ this->SetLogOutputStream(nullptr);
}
void cmCPackLog::SetLogOutputStream(std::ostream* os)
@@ -39,13 +38,13 @@ void cmCPackLog::SetLogOutputStream(std::ostream* os)
bool cmCPackLog::SetLogOutputFile(const char* fname)
{
- cmGeneratedFileStream* cg = CM_NULLPTR;
+ cmGeneratedFileStream* cg = nullptr;
if (fname) {
cg = new cmGeneratedFileStream(fname);
}
if (cg && !*cg) {
delete cg;
- cg = CM_NULLPTR;
+ cg = nullptr;
}
this->SetLogOutputStream(cg);
if (!cg) {
diff --git a/Source/CPack/cmCPackNSISGenerator.cxx b/Source/CPack/cmCPackNSISGenerator.cxx
index 9697a3832..ddf104c93 100644
--- a/Source/CPack/cmCPackNSISGenerator.cxx
+++ b/Source/CPack/cmCPackNSISGenerator.cxx
@@ -59,11 +59,10 @@ int cmCPackNSISGenerator::PackageFiles()
std::string nsisInstallOptions = nsisFileName + "/NSIS.InstallOptions.ini";
nsisFileName += "/project.nsi";
std::ostringstream str;
- std::vector<std::string>::const_iterator it;
- for (it = files.begin(); it != files.end(); ++it) {
+ for (std::string const& file : files) {
std::string outputDir = "$INSTDIR";
std::string fileN =
- cmSystemTools::RelativePath(toplevel.c_str(), it->c_str());
+ cmSystemTools::RelativePath(toplevel.c_str(), file.c_str());
if (!this->Components.empty()) {
const std::string::size_type pos = fileN.find('/');
@@ -87,12 +86,11 @@ int cmCPackNSISGenerator::PackageFiles()
this->SetOptionIfNotSet("CPACK_NSIS_DELETE_FILES", str.str().c_str());
std::vector<std::string> dirs;
this->GetListOfSubdirectories(toplevel.c_str(), dirs);
- std::vector<std::string>::const_iterator sit;
std::ostringstream dstr;
- for (sit = dirs.begin(); sit != dirs.end(); ++sit) {
+ for (std::string const& dir : dirs) {
std::string componentName;
std::string fileN =
- cmSystemTools::RelativePath(toplevel.c_str(), sit->c_str());
+ cmSystemTools::RelativePath(toplevel.c_str(), dir.c_str());
if (fileN.empty()) {
continue;
}
@@ -205,65 +203,57 @@ int cmCPackNSISGenerator::PackageFiles()
// in a vector based on the indices, and print them in that order.
std::vector<cmCPackInstallationType*> installTypes(
this->InstallationTypes.size());
- std::map<std::string, cmCPackInstallationType>::iterator installTypeIt;
- for (installTypeIt = this->InstallationTypes.begin();
- installTypeIt != this->InstallationTypes.end(); ++installTypeIt) {
- installTypes[installTypeIt->second.Index - 1] = &installTypeIt->second;
- }
- std::vector<cmCPackInstallationType*>::iterator installTypeIt2;
- for (installTypeIt2 = installTypes.begin();
- installTypeIt2 != installTypes.end(); ++installTypeIt2) {
+ for (auto& installType : this->InstallationTypes) {
+ installTypes[installType.second.Index - 1] = &installType.second;
+ }
+ for (cmCPackInstallationType* installType : installTypes) {
installTypesCode += "InstType \"";
- installTypesCode += (*installTypeIt2)->DisplayName;
+ installTypesCode += installType->DisplayName;
installTypesCode += "\"\n";
}
// Create installation groups first
- std::map<std::string, cmCPackComponentGroup>::iterator groupIt;
- for (groupIt = this->ComponentGroups.begin();
- groupIt != this->ComponentGroups.end(); ++groupIt) {
- if (groupIt->second.ParentGroup == CM_NULLPTR) {
+ for (auto& group : this->ComponentGroups) {
+ if (group.second.ParentGroup == nullptr) {
componentCode +=
- this->CreateComponentGroupDescription(&groupIt->second, macrosOut);
+ this->CreateComponentGroupDescription(&group.second, macrosOut);
}
// Add the group description, if any.
- if (!groupIt->second.Description.empty()) {
+ if (!group.second.Description.empty()) {
groupDescriptions += " !insertmacro MUI_DESCRIPTION_TEXT ${" +
- groupIt->first + "} \"" +
- this->TranslateNewlines(groupIt->second.Description) + "\"\n";
+ group.first + "} \"" +
+ this->TranslateNewlines(group.second.Description) + "\"\n";
}
}
// Create the remaining components, which aren't associated with groups.
- std::map<std::string, cmCPackComponent>::iterator compIt;
- for (compIt = this->Components.begin(); compIt != this->Components.end();
- ++compIt) {
- if (compIt->second.Files.empty()) {
+ for (auto& comp : this->Components) {
+ if (comp.second.Files.empty()) {
// NSIS cannot cope with components that have no files.
continue;
}
anyDownloadedComponents =
- anyDownloadedComponents || compIt->second.IsDownloaded;
+ anyDownloadedComponents || comp.second.IsDownloaded;
- if (!compIt->second.Group) {
+ if (!comp.second.Group) {
componentCode +=
- this->CreateComponentDescription(&compIt->second, macrosOut);
+ this->CreateComponentDescription(&comp.second, macrosOut);
}
// Add this component to the various section lists.
sectionList += " !insertmacro \"${MacroName}\" \"";
- sectionList += compIt->first;
+ sectionList += comp.first;
sectionList += "\"\n";
- selectedVarsList += "Var " + compIt->first + "_selected\n";
- selectedVarsList += "Var " + compIt->first + "_was_installed\n";
+ selectedVarsList += "Var " + comp.first + "_selected\n";
+ selectedVarsList += "Var " + comp.first + "_was_installed\n";
// Add the component description, if any.
- if (!compIt->second.Description.empty()) {
+ if (!comp.second.Description.empty()) {
componentDescriptions += " !insertmacro MUI_DESCRIPTION_TEXT ${" +
- compIt->first + "} \"" +
- this->TranslateNewlines(compIt->second.Description) + "\"\n";
+ comp.first + "} \"" +
+ this->TranslateNewlines(comp.second.Description) + "\"\n";
}
}
@@ -313,7 +303,7 @@ int cmCPackNSISGenerator::PackageFiles()
int retVal = 1;
bool res =
cmSystemTools::RunSingleCommand(nsisCmd.c_str(), &output, &output, &retVal,
- CM_NULLPTR, this->GeneratorVerbose, 0);
+ nullptr, this->GeneratorVerbose, 0);
if (!res || retVal) {
cmGeneratedFileStream ofs(tmpFile.c_str());
ofs << "# Run command: " << nsisCmd << std::endl
@@ -337,7 +327,7 @@ int cmCPackNSISGenerator::InitializeInternal()
"NSIS Generator cannot work with CPACK_INCLUDE_TOPLEVEL_DIRECTORY set. "
"This option will be reset to 0 (for this generator only)."
<< std::endl);
- this->SetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", CM_NULLPTR);
+ this->SetOption("CPACK_INCLUDE_TOPLEVEL_DIRECTORY", nullptr);
}
cmCPackLogger(cmCPackLog::LOG_DEBUG, "cmCPackNSISGenerator::Initialize()"
@@ -412,7 +402,7 @@ int cmCPackNSISGenerator::InitializeInternal()
int retVal = 1;
bool resS =
cmSystemTools::RunSingleCommand(nsisCmd.c_str(), &output, &output, &retVal,
- CM_NULLPTR, this->GeneratorVerbose, 0);
+ nullptr, this->GeneratorVerbose, 0);
cmsys::RegularExpression versionRex("v([0-9]+.[0-9]+)");
cmsys::RegularExpression versionRexCVS("v(.*)\\.cvs");
if (!resS || retVal ||
@@ -463,11 +453,9 @@ int cmCPackNSISGenerator::InitializeInternal()
cmSystemTools::ExpandListArgument(cpackPackageDeskTopLinks,
cpackPackageDesktopLinksVector);
- for (std::vector<std::string>::iterator i =
- cpackPackageDesktopLinksVector.begin();
- i != cpackPackageDesktopLinksVector.end(); ++i) {
+ for (std::string const& cpdl : cpackPackageDesktopLinksVector) {
cmCPackLogger(cmCPackLog::LOG_DEBUG,
- "CPACK_CREATE_DESKTOP_LINKS: " << *i << std::endl);
+ "CPACK_CREATE_DESKTOP_LINKS: " << cpdl << std::endl);
}
} else {
cmCPackLogger(cmCPackLog::LOG_DEBUG, "CPACK_CREATE_DESKTOP_LINKS: "
@@ -647,11 +635,9 @@ std::string cmCPackNSISGenerator::CreateComponentDescription(
componentCode += " SectionIn RO\n";
} else if (!component->InstallationTypes.empty()) {
std::ostringstream out;
- std::vector<cmCPackInstallationType*>::iterator installTypeIter;
- for (installTypeIter = component->InstallationTypes.begin();
- installTypeIter != component->InstallationTypes.end();
- ++installTypeIter) {
- out << " " << (*installTypeIter)->Index;
+ for (cmCPackInstallationType const* installType :
+ component->InstallationTypes) {
+ out << " " << installType->Index;
}
componentCode += " SectionIn" + out.str() + "\n";
}
@@ -730,19 +716,17 @@ std::string cmCPackNSISGenerator::CreateComponentDescription(
unsigned long totalSize = 0;
{ // the scope is needed for cmGeneratedFileStream
cmGeneratedFileStream out(zipListFileName.c_str());
- std::vector<std::string>::iterator fileIt;
- for (fileIt = component->Files.begin(); fileIt != component->Files.end();
- ++fileIt) {
+ for (std::string const& file : component->Files) {
if (needQuotesInFile) {
out << "\"";
}
- out << *fileIt;
+ out << file;
if (needQuotesInFile) {
out << "\"";
}
out << std::endl;
- totalSize += cmSystemTools::FileLength(dirName + *fileIt);
+ totalSize += cmSystemTools::FileLength(dirName + file);
}
}
@@ -798,17 +782,14 @@ std::string cmCPackNSISGenerator::CreateComponentDescription(
macrosOut << "!macro Remove_${" << component->Name << "}\n";
macrosOut << " IntCmp $" << component->Name << "_was_installed 0 noremove_"
<< component->Name << "\n";
- std::vector<std::string>::iterator pathIt;
std::string path;
- for (pathIt = component->Files.begin(); pathIt != component->Files.end();
- ++pathIt) {
- path = *pathIt;
+ for (std::string const& pathIt : component->Files) {
+ path = pathIt;
std::replace(path.begin(), path.end(), '/', '\\');
macrosOut << " Delete \"" << componentOutputDir << "\\" << path << "\"\n";
}
- for (pathIt = component->Directories.begin();
- pathIt != component->Directories.end(); ++pathIt) {
- path = *pathIt;
+ for (std::string const& pathIt : component->Directories) {
+ path = pathIt;
std::replace(path.begin(), path.end(), '/', '\\');
macrosOut << " RMDir \"" << componentOutputDir << "\\" << path << "\"\n";
}
@@ -841,17 +822,14 @@ std::string cmCPackNSISGenerator::CreateSelectionDependenciesDescription(
visited.insert(component);
std::ostringstream out;
- std::vector<cmCPackComponent*>::iterator dependIt;
- for (dependIt = component->Dependencies.begin();
- dependIt != component->Dependencies.end(); ++dependIt) {
+ for (cmCPackComponent* depend : component->Dependencies) {
// Write NSIS code to select this dependency
- out << " SectionGetFlags ${" << (*dependIt)->Name << "} $0\n";
+ out << " SectionGetFlags ${" << depend->Name << "} $0\n";
out << " IntOp $0 $0 | ${SF_SELECTED}\n";
- out << " SectionSetFlags ${" << (*dependIt)->Name << "} $0\n";
- out << " IntOp $" << (*dependIt)->Name
- << "_selected 0 + ${SF_SELECTED}\n";
+ out << " SectionSetFlags ${" << depend->Name << "} $0\n";
+ out << " IntOp $" << depend->Name << "_selected 0 + ${SF_SELECTED}\n";
// Recurse
- out << CreateSelectionDependenciesDescription(*dependIt, visited).c_str();
+ out << CreateSelectionDependenciesDescription(depend, visited).c_str();
}
return out.str();
@@ -867,19 +845,16 @@ std::string cmCPackNSISGenerator::CreateDeselectionDependenciesDescription(
visited.insert(component);
std::ostringstream out;
- std::vector<cmCPackComponent*>::iterator dependIt;
- for (dependIt = component->ReverseDependencies.begin();
- dependIt != component->ReverseDependencies.end(); ++dependIt) {
+ for (cmCPackComponent* depend : component->ReverseDependencies) {
// Write NSIS code to deselect this dependency
- out << " SectionGetFlags ${" << (*dependIt)->Name << "} $0\n";
+ out << " SectionGetFlags ${" << depend->Name << "} $0\n";
out << " IntOp $1 ${SF_SELECTED} ~\n";
out << " IntOp $0 $0 & $1\n";
- out << " SectionSetFlags ${" << (*dependIt)->Name << "} $0\n";
- out << " IntOp $" << (*dependIt)->Name << "_selected 0 + 0\n";
+ out << " SectionSetFlags ${" << depend->Name << "} $0\n";
+ out << " IntOp $" << depend->Name << "_selected 0 + 0\n";
// Recurse
- out
- << CreateDeselectionDependenciesDescription(*dependIt, visited).c_str();
+ out << CreateDeselectionDependenciesDescription(depend, visited).c_str();
}
return out.str();
@@ -903,20 +878,16 @@ std::string cmCPackNSISGenerator::CreateComponentGroupDescription(
code += "\"" + group->DisplayName + "\" " + group->Name + "\n";
}
- std::vector<cmCPackComponentGroup*>::iterator groupIt;
- for (groupIt = group->Subgroups.begin(); groupIt != group->Subgroups.end();
- ++groupIt) {
- code += this->CreateComponentGroupDescription(*groupIt, macrosOut);
+ for (cmCPackComponentGroup* g : group->Subgroups) {
+ code += this->CreateComponentGroupDescription(g, macrosOut);
}
- std::vector<cmCPackComponent*>::iterator comp;
- for (comp = group->Components.begin(); comp != group->Components.end();
- ++comp) {
- if ((*comp)->Files.empty()) {
+ for (cmCPackComponent* comp : group->Components) {
+ if (comp->Files.empty()) {
continue;
}
- code += this->CreateComponentDescription(*comp, macrosOut);
+ code += this->CreateComponentDescription(comp, macrosOut);
}
code += "SectionGroupEnd\n";
return code;
diff --git a/Source/CPack/cmCPackNSISGenerator.h b/Source/CPack/cmCPackNSISGenerator.h
index 77be3256d..fc9ad9ace 100644
--- a/Source/CPack/cmCPackNSISGenerator.h
+++ b/Source/CPack/cmCPackNSISGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackNSISGenerator_h
#define cmCPackNSISGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCPackGenerator.h"
@@ -34,22 +34,22 @@ public:
* Construct generator
*/
cmCPackNSISGenerator(bool nsis64 = false);
- ~cmCPackNSISGenerator() CM_OVERRIDE;
+ ~cmCPackNSISGenerator() override;
protected:
- int InitializeInternal() CM_OVERRIDE;
+ int InitializeInternal() override;
void CreateMenuLinks(std::ostream& str, std::ostream& deleteStr);
- int PackageFiles() CM_OVERRIDE;
- const char* GetOutputExtension() CM_OVERRIDE { return ".exe"; }
- const char* GetOutputPostfix() CM_OVERRIDE { return "win32"; }
+ int PackageFiles() override;
+ const char* GetOutputExtension() override { return ".exe"; }
+ const char* GetOutputPostfix() override { return "win32"; }
bool GetListOfSubdirectories(const char* dir,
std::vector<std::string>& dirs);
- enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir() const
- CM_OVERRIDE;
- bool SupportsAbsoluteDestination() const CM_OVERRIDE;
- bool SupportsComponentInstallation() const CM_OVERRIDE;
+ enum cmCPackGenerator::CPackSetDestdirSupport SupportsSetDestdir()
+ const override;
+ bool SupportsAbsoluteDestination() const override;
+ bool SupportsComponentInstallation() const override;
/// Produce a string that contains the NSIS code to describe a
/// particular component. Any added macros will be emitted via
diff --git a/Source/CPack/cmCPackOSXX11Generator.cxx b/Source/CPack/cmCPackOSXX11Generator.cxx
index 8ea88a87a..8d3c40c5c 100644
--- a/Source/CPack/cmCPackOSXX11Generator.cxx
+++ b/Source/CPack/cmCPackOSXX11Generator.cxx
@@ -144,8 +144,8 @@ int cmCPackOSXX11Generator::PackageFiles()
tmpFile += "/hdiutilOutput.log";
std::ostringstream dmgCmd;
dmgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM_DISK_IMAGE")
- << "\" create -ov -format UDZO -srcfolder \"" << diskImageDirectory
- << "\" \"" << packageFileNames[0] << "\"";
+ << "\" create -ov -fs HFS+ -format UDZO -srcfolder \""
+ << diskImageDirectory << "\" \"" << packageFileNames[0] << "\"";
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Compress disk image using command: "
<< dmgCmd.str() << std::endl);
// since we get random dashboard failures with this one
@@ -154,9 +154,9 @@ int cmCPackOSXX11Generator::PackageFiles()
int numTries = 10;
bool res = false;
while (numTries > 0) {
- res =
- cmSystemTools::RunSingleCommand(dmgCmd.str().c_str(), &output, &output,
- &retVal, 0, this->GeneratorVerbose, 0);
+ res = cmSystemTools::RunSingleCommand(dmgCmd.str().c_str(), &output,
+ &output, &retVal, nullptr,
+ this->GeneratorVerbose, 0);
if (res && !retVal) {
numTries = -1;
break;
diff --git a/Source/CPack/cmCPackOSXX11Generator.h b/Source/CPack/cmCPackOSXX11Generator.h
index 0eebc6dd1..a6461c854 100644
--- a/Source/CPack/cmCPackOSXX11Generator.h
+++ b/Source/CPack/cmCPackOSXX11Generator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackOSXX11Generator_h
#define cmCPackOSXX11Generator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
@@ -23,13 +23,13 @@ public:
* Construct generator
*/
cmCPackOSXX11Generator();
- virtual ~cmCPackOSXX11Generator();
+ ~cmCPackOSXX11Generator() override;
protected:
- virtual int InitializeInternal() CM_OVERRIDE;
- int PackageFiles() CM_OVERRIDE;
- const char* GetPackagingInstallPrefix() CM_OVERRIDE;
- const char* GetOutputExtension() CM_OVERRIDE { return ".dmg"; }
+ virtual int InitializeInternal() override;
+ int PackageFiles() override;
+ const char* GetPackagingInstallPrefix() override;
+ const char* GetOutputExtension() override { return ".dmg"; }
// bool CopyCreateResourceFile(const std::string& name,
// const std::string& dir);
diff --git a/Source/CPack/cmCPackPKGGenerator.cxx b/Source/CPack/cmCPackPKGGenerator.cxx
index 70ae267fb..4f5b2a05a 100644
--- a/Source/CPack/cmCPackPKGGenerator.cxx
+++ b/Source/CPack/cmCPackPKGGenerator.cxx
@@ -42,9 +42,9 @@ std::string cmCPackPKGGenerator::GetPackageName(
out << cmSystemTools::GetFilenameWithoutLastExtension(packagesDir) << "-"
<< component.Name << ".pkg";
return out.str();
- } else {
- return component.ArchiveFile + ".pkg";
}
+
+ return component.ArchiveFile + ".pkg";
}
void cmCPackPKGGenerator::WriteDistributionFile(const char* metapackageFile)
@@ -70,7 +70,7 @@ void cmCPackPKGGenerator::WriteDistributionFile(const char* metapackageFile)
std::map<std::string, cmCPackComponentGroup>::iterator groupIt;
for (groupIt = this->ComponentGroups.begin();
groupIt != this->ComponentGroups.end(); ++groupIt) {
- if (groupIt->second.ParentGroup == 0) {
+ if (groupIt->second.ParentGroup == nullptr) {
CreateChoiceOutline(groupIt->second, xout);
}
}
diff --git a/Source/CPack/cmCPackPKGGenerator.h b/Source/CPack/cmCPackPKGGenerator.h
index f873c5936..69286ffde 100644
--- a/Source/CPack/cmCPackPKGGenerator.h
+++ b/Source/CPack/cmCPackPKGGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackPKGGenerator_h
#define cmCPackPKGGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <set>
#include <sstream>
@@ -27,13 +27,13 @@ public:
* Construct generator
*/
cmCPackPKGGenerator();
- virtual ~cmCPackPKGGenerator();
+ ~cmCPackPKGGenerator() override;
- bool SupportsComponentInstallation() const CM_OVERRIDE;
+ bool SupportsComponentInstallation() const override;
protected:
- int InitializeInternal() CM_OVERRIDE;
- const char* GetOutputPostfix() CM_OVERRIDE { return "darwin"; }
+ int InitializeInternal() override;
+ const char* GetOutputPostfix() override { return "darwin"; }
// Copies or creates the resource file with the given name to the
// package or package staging directory dirName. The variable
diff --git a/Source/CPack/cmCPackPackageMakerGenerator.cxx b/Source/CPack/cmCPackPackageMakerGenerator.cxx
index 8db7cfb3d..dbcb02231 100644
--- a/Source/CPack/cmCPackPackageMakerGenerator.cxx
+++ b/Source/CPack/cmCPackPackageMakerGenerator.cxx
@@ -275,8 +275,9 @@ int cmCPackPackageMakerGenerator::PackageFiles()
if (this->PackageMakerVersion > 2.0) {
pkgCmd << " -v";
}
- if (!RunPackageMaker(pkgCmd.str().c_str(), packageDirFileName.c_str()))
+ if (!RunPackageMaker(pkgCmd.str().c_str(), packageDirFileName.c_str())) {
return 0;
+ }
} else {
// We have built the package in place. Generate the
// distribution.dist file to describe it for the installer.
@@ -287,16 +288,16 @@ int cmCPackPackageMakerGenerator::PackageFiles()
tmpFile += "/hdiutilOutput.log";
std::ostringstream dmgCmd;
dmgCmd << "\"" << this->GetOption("CPACK_INSTALLER_PROGRAM_DISK_IMAGE")
- << "\" create -ov -format UDZO -srcfolder \"" << packageDirFileName
- << "\" \"" << packageFileNames[0] << "\"";
+ << "\" create -ov -fs HFS+ -format UDZO -srcfolder \""
+ << packageDirFileName << "\" \"" << packageFileNames[0] << "\"";
std::string output;
int retVal = 1;
int numTries = 10;
bool res = false;
while (numTries > 0) {
- res =
- cmSystemTools::RunSingleCommand(dmgCmd.str().c_str(), &output, &output,
- &retVal, 0, this->GeneratorVerbose, 0);
+ res = cmSystemTools::RunSingleCommand(dmgCmd.str().c_str(), &output,
+ &output, &retVal, nullptr,
+ this->GeneratorVerbose, 0);
if (res && !retVal) {
numTries = -1;
break;
@@ -466,7 +467,7 @@ bool cmCPackPackageMakerGenerator::RunPackageMaker(const char* command,
std::string output;
int retVal = 1;
bool res = cmSystemTools::RunSingleCommand(
- command, &output, &output, &retVal, 0, this->GeneratorVerbose, 0);
+ command, &output, &output, &retVal, nullptr, this->GeneratorVerbose, 0);
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Done running package maker"
<< std::endl);
if (!res || retVal) {
diff --git a/Source/CPack/cmCPackPackageMakerGenerator.h b/Source/CPack/cmCPackPackageMakerGenerator.h
index 62745152b..0575587d5 100644
--- a/Source/CPack/cmCPackPackageMakerGenerator.h
+++ b/Source/CPack/cmCPackPackageMakerGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackPackageMakerGenerator_h
#define cmCPackPackageMakerGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCPackGenerator.h"
#include "cmCPackPKGGenerator.h"
@@ -25,13 +25,13 @@ public:
* Construct generator
*/
cmCPackPackageMakerGenerator();
- virtual ~cmCPackPackageMakerGenerator();
- bool SupportsComponentInstallation() const CM_OVERRIDE;
+ ~cmCPackPackageMakerGenerator() override;
+ bool SupportsComponentInstallation() const override;
protected:
- int InitializeInternal() CM_OVERRIDE;
- int PackageFiles() CM_OVERRIDE;
- const char* GetOutputExtension() CM_OVERRIDE { return ".dmg"; }
+ int InitializeInternal() override;
+ int PackageFiles() override;
+ const char* GetOutputExtension() override { return ".dmg"; }
// Run PackageMaker with the given command line, which will (if
// successful) produce the given package file. Returns true if
diff --git a/Source/CPack/cmCPackProductBuildGenerator.cxx b/Source/CPack/cmCPackProductBuildGenerator.cxx
index 1389eaa5a..6a6dc828f 100644
--- a/Source/CPack/cmCPackProductBuildGenerator.cxx
+++ b/Source/CPack/cmCPackProductBuildGenerator.cxx
@@ -54,7 +54,7 @@ int cmCPackProductBuildGenerator::PackageFiles()
} else {
if (!this->GenerateComponentPackage(basePackageDir,
this->GetOption("CPACK_PACKAGE_NAME"),
- toplevel, NULL)) {
+ toplevel, nullptr)) {
return 0;
}
}
@@ -145,9 +145,9 @@ bool cmCPackProductBuildGenerator::RunProductBuild(const std::string& command)
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Execute: " << command << std::endl);
std::string output, error_output;
int retVal = 1;
- bool res =
- cmSystemTools::RunSingleCommand(command.c_str(), &output, &error_output,
- &retVal, 0, this->GeneratorVerbose, 0);
+ bool res = cmSystemTools::RunSingleCommand(command.c_str(), &output,
+ &error_output, &retVal, nullptr,
+ this->GeneratorVerbose, 0);
cmCPackLogger(cmCPackLog::LOG_VERBOSE, "Done running command" << std::endl);
if (!res || retVal) {
cmGeneratedFileStream ofs(tmpFile.c_str());
@@ -174,7 +174,7 @@ bool cmCPackProductBuildGenerator::GenerateComponentPackage(
cmCPackLogger(cmCPackLog::LOG_OUTPUT, "- Building component package: "
<< packageFile << std::endl);
- const char* comp_name = component ? component->Name.c_str() : NULL;
+ 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);
@@ -190,7 +190,7 @@ bool cmCPackProductBuildGenerator::GenerateComponentPackage(
cmCPackLogger(cmCPackLog::LOG_ERROR,
"Problem creating installer directory: " << scriptDir
<< std::endl);
- return 0;
+ return false;
}
// if preflight, postflight, or postupgrade are set
diff --git a/Source/CPack/cmCPackProductBuildGenerator.h b/Source/CPack/cmCPackProductBuildGenerator.h
index 12093a0e8..015fe4ace 100644
--- a/Source/CPack/cmCPackProductBuildGenerator.h
+++ b/Source/CPack/cmCPackProductBuildGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackProductBuildGenerator_h
#define cmCPackProductBuildGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
@@ -25,12 +25,12 @@ public:
* Construct generator
*/
cmCPackProductBuildGenerator();
- virtual ~cmCPackProductBuildGenerator();
+ ~cmCPackProductBuildGenerator() override;
protected:
- int InitializeInternal() CM_OVERRIDE;
- int PackageFiles() CM_OVERRIDE;
- const char* GetOutputExtension() CM_OVERRIDE { return ".pkg"; }
+ int InitializeInternal() override;
+ int PackageFiles() override;
+ const char* GetOutputExtension() override { return ".pkg"; }
// Run ProductBuild with the given command line, which will (if
// successful) produce the given package file. Returns true if
diff --git a/Source/CPack/cmCPackRPMGenerator.cxx b/Source/CPack/cmCPackRPMGenerator.cxx
index 8ec03c236..e40b74d7e 100644
--- a/Source/CPack/cmCPackRPMGenerator.cxx
+++ b/Source/CPack/cmCPackRPMGenerator.cxx
@@ -148,7 +148,7 @@ int cmCPackRPMGenerator::PackageComponents(bool ignoreGroup)
for (compIt = this->Components.begin();
compIt != this->Components.end(); ++compIt) {
// Does the component belong to a group?
- if (compIt->second.Group == CM_NULLPTR) {
+ if (compIt->second.Group == nullptr) {
std::string component(compIt->first);
std::transform(component.begin(), component.end(),
component.begin(), ::toupper);
@@ -214,7 +214,7 @@ int cmCPackRPMGenerator::PackageComponents(bool ignoreGroup)
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt) {
// Does the component belong to a group?
- if (compIt->second.Group == CM_NULLPTR) {
+ if (compIt->second.Group == nullptr) {
std::string component(compIt->first);
std::transform(component.begin(), component.end(), component.begin(),
::toupper);
@@ -299,7 +299,7 @@ int cmCPackRPMGenerator::PackageComponents(bool ignoreGroup)
for (compIt = this->Components.begin(); compIt != this->Components.end();
++compIt) {
// Does the component belong to a group?
- if (compIt->second.Group == CM_NULLPTR) {
+ if (compIt->second.Group == nullptr) {
cmCPackLogger(
cmCPackLog::LOG_VERBOSE, "Component <"
<< compIt->second.Name
@@ -430,7 +430,7 @@ std::string cmCPackRPMGenerator::GetComponentInstallDirNameSuffix(
// the current COMPONENT belongs to.
std::string groupVar =
"CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP";
- if (CM_NULLPTR != GetOption(groupVar)) {
+ if (nullptr != GetOption(groupVar)) {
return std::string(GetOption(groupVar));
}
return componentName;
diff --git a/Source/CPack/cmCPackRPMGenerator.h b/Source/CPack/cmCPackRPMGenerator.h
index 52cfc13ed..27d3b6339 100644
--- a/Source/CPack/cmCPackRPMGenerator.h
+++ b/Source/CPack/cmCPackRPMGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackRPMGenerator_h
#define cmCPackRPMGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCPackGenerator.h"
@@ -26,7 +26,7 @@ public:
* Construct generator
*/
cmCPackRPMGenerator();
- ~cmCPackRPMGenerator() CM_OVERRIDE;
+ ~cmCPackRPMGenerator() override;
static bool CanGenerate()
{
@@ -43,8 +43,8 @@ public:
}
protected:
- int InitializeInternal() CM_OVERRIDE;
- int PackageFiles() CM_OVERRIDE;
+ int InitializeInternal() override;
+ int PackageFiles() override;
/**
* This method factors out the work done in component packaging case.
*/
@@ -61,10 +61,10 @@ protected:
* components will be put in a single installer.
*/
int PackageComponentsAllInOne(const std::string& compInstDirName);
- const char* GetOutputExtension() CM_OVERRIDE { return ".rpm"; }
- bool SupportsComponentInstallation() const CM_OVERRIDE;
+ const char* GetOutputExtension() override { return ".rpm"; }
+ bool SupportsComponentInstallation() const override;
std::string GetComponentInstallDirNameSuffix(
- const std::string& componentName) CM_OVERRIDE;
+ const std::string& componentName) override;
void AddGeneratedPackageNames();
};
diff --git a/Source/CPack/cmCPackSTGZGenerator.cxx b/Source/CPack/cmCPackSTGZGenerator.cxx
index c54161426..3d7fd3c14 100644
--- a/Source/CPack/cmCPackSTGZGenerator.cxx
+++ b/Source/CPack/cmCPackSTGZGenerator.cxx
@@ -6,7 +6,6 @@
#include <sstream>
#include <stdio.h>
#include <string>
-#include <vector>
#include "cmCPackGenerator.h"
#include "cmCPackLog.h"
@@ -48,9 +47,8 @@ int cmCPackSTGZGenerator::PackageFiles()
* have generated several packages (component packaging)
* so we must iterate over generated packages.
*/
- for (std::vector<std::string>::iterator it = packageFileNames.begin();
- it != packageFileNames.end(); ++it) {
- retval &= cmSystemTools::SetPermissions((*it).c_str(),
+ for (std::string const& pfn : packageFileNames) {
+ retval &= cmSystemTools::SetPermissions(pfn.c_str(),
#if defined(_MSC_VER) || defined(__MINGW32__)
S_IREAD | S_IWRITE | S_IEXEC
#else
diff --git a/Source/CPack/cmCPackSTGZGenerator.h b/Source/CPack/cmCPackSTGZGenerator.h
index 8304e8076..9cf184b19 100644
--- a/Source/CPack/cmCPackSTGZGenerator.h
+++ b/Source/CPack/cmCPackSTGZGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackSTGZGenerator_h
#define cmCPackSTGZGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCPackGenerator.h"
#include "cmCPackTGZGenerator.h"
@@ -23,13 +23,13 @@ public:
* Construct generator
*/
cmCPackSTGZGenerator();
- ~cmCPackSTGZGenerator() CM_OVERRIDE;
+ ~cmCPackSTGZGenerator() override;
protected:
- int PackageFiles() CM_OVERRIDE;
- int InitializeInternal() CM_OVERRIDE;
- int GenerateHeader(std::ostream* os) CM_OVERRIDE;
- const char* GetOutputExtension() CM_OVERRIDE { return ".sh"; }
+ int PackageFiles() override;
+ int InitializeInternal() override;
+ int GenerateHeader(std::ostream* os) override;
+ const char* GetOutputExtension() override { return ".sh"; }
};
#endif
diff --git a/Source/CPack/cmCPackTGZGenerator.h b/Source/CPack/cmCPackTGZGenerator.h
index 9426b3a01..7be3d9d33 100644
--- a/Source/CPack/cmCPackTGZGenerator.h
+++ b/Source/CPack/cmCPackTGZGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackTGZGenerator_h
#define cmCPackTGZGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCPackArchiveGenerator.h"
#include "cmCPackGenerator.h"
@@ -20,10 +20,10 @@ public:
* Construct generator
*/
cmCPackTGZGenerator();
- ~cmCPackTGZGenerator() CM_OVERRIDE;
+ ~cmCPackTGZGenerator() override;
protected:
- const char* GetOutputExtension() CM_OVERRIDE { return ".tar.gz"; }
+ const char* GetOutputExtension() override { return ".tar.gz"; }
};
#endif
diff --git a/Source/CPack/cmCPackTXZGenerator.h b/Source/CPack/cmCPackTXZGenerator.h
index 3b96e2d78..4aa59730e 100644
--- a/Source/CPack/cmCPackTXZGenerator.h
+++ b/Source/CPack/cmCPackTXZGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackTXZGenerator_h
#define cmCPackTXZGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCPackArchiveGenerator.h"
#include "cmCPackGenerator.h"
@@ -20,10 +20,10 @@ public:
* Construct generator
*/
cmCPackTXZGenerator();
- ~cmCPackTXZGenerator() CM_OVERRIDE;
+ ~cmCPackTXZGenerator() override;
protected:
- const char* GetOutputExtension() CM_OVERRIDE { return ".tar.xz"; }
+ const char* GetOutputExtension() override { return ".tar.xz"; }
};
#endif
diff --git a/Source/CPack/cmCPackTarBZip2Generator.h b/Source/CPack/cmCPackTarBZip2Generator.h
index 9b4b8f4ff..7975ddaee 100644
--- a/Source/CPack/cmCPackTarBZip2Generator.h
+++ b/Source/CPack/cmCPackTarBZip2Generator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackTarBZip2Generator_h
#define cmCPackTarBZip2Generator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCPackArchiveGenerator.h"
#include "cmCPackGenerator.h"
@@ -19,10 +19,10 @@ public:
* Construct generator
*/
cmCPackTarBZip2Generator();
- ~cmCPackTarBZip2Generator() CM_OVERRIDE;
+ ~cmCPackTarBZip2Generator() override;
protected:
- const char* GetOutputExtension() CM_OVERRIDE { return ".tar.bz2"; }
+ const char* GetOutputExtension() override { return ".tar.bz2"; }
};
#endif
diff --git a/Source/CPack/cmCPackTarCompressGenerator.h b/Source/CPack/cmCPackTarCompressGenerator.h
index 381d6eb2f..37c7f48c8 100644
--- a/Source/CPack/cmCPackTarCompressGenerator.h
+++ b/Source/CPack/cmCPackTarCompressGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackTarCompressGenerator_h
#define cmCPackTarCompressGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCPackArchiveGenerator.h"
#include "cmCPackGenerator.h"
@@ -19,10 +19,10 @@ public:
* Construct generator
*/
cmCPackTarCompressGenerator();
- ~cmCPackTarCompressGenerator() CM_OVERRIDE;
+ ~cmCPackTarCompressGenerator() override;
protected:
- const char* GetOutputExtension() CM_OVERRIDE { return ".tar.Z"; }
+ const char* GetOutputExtension() override { return ".tar.Z"; }
};
#endif
diff --git a/Source/CPack/cmCPackZIPGenerator.h b/Source/CPack/cmCPackZIPGenerator.h
index 00c872029..58ec79ef1 100644
--- a/Source/CPack/cmCPackZIPGenerator.h
+++ b/Source/CPack/cmCPackZIPGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackZIPGenerator_h
#define cmCPackZIPGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCPackArchiveGenerator.h"
#include "cmCPackGenerator.h"
@@ -20,10 +20,10 @@ public:
* Construct generator
*/
cmCPackZIPGenerator();
- ~cmCPackZIPGenerator() CM_OVERRIDE;
+ ~cmCPackZIPGenerator() override;
protected:
- const char* GetOutputExtension() CM_OVERRIDE { return ".zip"; }
+ const char* GetOutputExtension() override { return ".zip"; }
};
#endif
diff --git a/Source/CPack/cpack.cxx b/Source/CPack/cpack.cxx
index a44bc3d68..addb54ea0 100644
--- a/Source/CPack/cpack.cxx
+++ b/Source/CPack/cpack.cxx
@@ -1,11 +1,11 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmConfigure.h"
#include "cmsys/CommandLineArguments.hxx"
#include "cmsys/Encoding.hxx"
#include <iostream>
#include <map>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stddef.h>
#include <string>
@@ -25,17 +25,16 @@
#include "cmMakefile.h"
#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
static const char* cmDocumentationName[][2] = {
- { CM_NULLPTR, " cpack - Packaging driver provided by CMake." },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, " cpack - Packaging driver provided by CMake." },
+ { nullptr, nullptr }
};
static const char* cmDocumentationUsage[][2] = {
- { CM_NULLPTR, " cpack -G <generator> [options]" },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, " cpack -G <generator> [options]" },
+ { nullptr, nullptr }
};
static const char* cmDocumentationOptions[][2] = {
@@ -49,7 +48,7 @@ static const char* cmDocumentationOptions[][2] = {
{ "-R <package version>", "override/define CPACK_PACKAGE_VERSION" },
{ "-B <package directory>", "override/define CPACK_PACKAGE_DIRECTORY" },
{ "--vendor <vendor name>", "override/define CPACK_PACKAGE_VENDOR" },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, nullptr }
};
int cpackUnknownArgument(const char* /*unused*/, void* /*unused*/)
@@ -136,7 +135,7 @@ int main(int argc, char const* const* argv)
cpackDefinitions definitions;
definitions.Log = &log;
- cpackConfigFile = "";
+ cpackConfigFile.clear();
cmsys::CommandLineArguments arg;
arg.Initialize(argc, argv);
@@ -193,10 +192,9 @@ int main(int argc, char const* const* argv)
cminst.SetHomeOutputDirectory("");
cminst.GetCurrentSnapshot().SetDefaultDefinitions();
cmGlobalGenerator cmgg(&cminst);
- CM_AUTO_PTR<cmMakefile> globalMF(
- new cmMakefile(&cmgg, cminst.GetCurrentSnapshot()));
+ cmMakefile globalMF(&cmgg, cminst.GetCurrentSnapshot());
#if defined(__CYGWIN__)
- globalMF->AddDefinition("CMAKE_LEGACY_CYGWIN_WIN32", "0");
+ globalMF.AddDefinition("CMAKE_LEGACY_CYGWIN_WIN32", "0");
#endif
bool cpackConfigFileSpecified = true;
@@ -208,7 +206,7 @@ int main(int argc, char const* const* argv)
cmCPackGeneratorFactory generators;
generators.SetLogger(&log);
- cmCPackGenerator* cpackGenerator = CM_NULLPTR;
+ cmCPackGenerator* cpackGenerator = nullptr;
cmDocumentation doc;
doc.addCPackStandardDocSections();
@@ -226,16 +224,16 @@ int main(int argc, char const* const* argv)
// find out which system cpack is running on, so it can setup the search
// paths, so FIND_XXX() commands can be used in scripts
std::string systemFile =
- globalMF->GetModulesFile("CMakeDetermineSystem.cmake");
- if (!globalMF->ReadListFile(systemFile.c_str())) {
+ globalMF.GetModulesFile("CMakeDetermineSystem.cmake");
+ if (!globalMF.ReadListFile(systemFile.c_str())) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"Error reading CMakeDetermineSystem.cmake" << std::endl);
return 1;
}
systemFile =
- globalMF->GetModulesFile("CMakeSystemSpecificInformation.cmake");
- if (!globalMF->ReadListFile(systemFile.c_str())) {
+ globalMF.GetModulesFile("CMakeSystemSpecificInformation.cmake");
+ if (!globalMF.ReadListFile(systemFile.c_str())) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"Error reading CMakeSystemSpecificInformation.cmake"
<< std::endl);
@@ -243,7 +241,7 @@ int main(int argc, char const* const* argv)
}
if (!cpackBuildConfig.empty()) {
- globalMF->AddDefinition("CPACK_BUILD_CONFIG", cpackBuildConfig.c_str());
+ globalMF.AddDefinition("CPACK_BUILD_CONFIG", cpackBuildConfig.c_str());
}
if (cmSystemTools::FileExists(cpackConfigFile.c_str())) {
@@ -251,7 +249,7 @@ int main(int argc, char const* const* argv)
cmCPack_Log(&log, cmCPackLog::LOG_VERBOSE,
"Read CPack configuration file: " << cpackConfigFile
<< std::endl);
- if (!globalMF->ReadListFile(cpackConfigFile.c_str())) {
+ if (!globalMF.ReadListFile(cpackConfigFile.c_str())) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR,
"Problem reading CPack config file: \""
<< cpackConfigFile << "\"" << std::endl);
@@ -265,58 +263,53 @@ int main(int argc, char const* const* argv)
}
if (!generator.empty()) {
- globalMF->AddDefinition("CPACK_GENERATOR", generator.c_str());
+ globalMF.AddDefinition("CPACK_GENERATOR", generator.c_str());
}
if (!cpackProjectName.empty()) {
- globalMF->AddDefinition("CPACK_PACKAGE_NAME", cpackProjectName.c_str());
+ globalMF.AddDefinition("CPACK_PACKAGE_NAME", cpackProjectName.c_str());
}
if (!cpackProjectVersion.empty()) {
- globalMF->AddDefinition("CPACK_PACKAGE_VERSION",
- cpackProjectVersion.c_str());
+ globalMF.AddDefinition("CPACK_PACKAGE_VERSION",
+ cpackProjectVersion.c_str());
}
if (!cpackProjectVendor.empty()) {
- globalMF->AddDefinition("CPACK_PACKAGE_VENDOR",
- cpackProjectVendor.c_str());
+ globalMF.AddDefinition("CPACK_PACKAGE_VENDOR",
+ cpackProjectVendor.c_str());
}
// if this is not empty it has been set on the command line
// go for it. Command line override values set in config file.
if (!cpackProjectDirectory.empty()) {
- globalMF->AddDefinition("CPACK_PACKAGE_DIRECTORY",
- cpackProjectDirectory.c_str());
+ globalMF.AddDefinition("CPACK_PACKAGE_DIRECTORY",
+ cpackProjectDirectory.c_str());
}
// The value has not been set on the command line
else {
// get a default value (current working directory)
cpackProjectDirectory = cmsys::SystemTools::GetCurrentWorkingDirectory();
// use default value iff no value has been provided by the config file
- if (!globalMF->IsSet("CPACK_PACKAGE_DIRECTORY")) {
- globalMF->AddDefinition("CPACK_PACKAGE_DIRECTORY",
- cpackProjectDirectory.c_str());
+ if (!globalMF.IsSet("CPACK_PACKAGE_DIRECTORY")) {
+ globalMF.AddDefinition("CPACK_PACKAGE_DIRECTORY",
+ cpackProjectDirectory.c_str());
}
}
- cpackDefinitions::MapType::iterator cdit;
- for (cdit = definitions.Map.begin(); cdit != definitions.Map.end();
- ++cdit) {
- globalMF->AddDefinition(cdit->first, cdit->second.c_str());
+ for (auto const& cd : definitions.Map) {
+ globalMF.AddDefinition(cd.first, cd.second.c_str());
}
- const char* cpackModulesPath =
- globalMF->GetDefinition("CPACK_MODULE_PATH");
+ const char* cpackModulesPath = globalMF.GetDefinition("CPACK_MODULE_PATH");
if (cpackModulesPath) {
- globalMF->AddDefinition("CMAKE_MODULE_PATH", cpackModulesPath);
+ globalMF.AddDefinition("CMAKE_MODULE_PATH", cpackModulesPath);
}
- const char* genList = globalMF->GetDefinition("CPACK_GENERATOR");
+ const char* genList = globalMF.GetDefinition("CPACK_GENERATOR");
if (!genList) {
cmCPack_Log(&log, cmCPackLog::LOG_ERROR, "CPack generator not specified"
<< std::endl);
} else {
std::vector<std::string> generatorsVector;
cmSystemTools::ExpandListArgument(genList, generatorsVector);
- std::vector<std::string>::iterator it;
- for (it = generatorsVector.begin(); it != generatorsVector.end(); ++it) {
- const char* gen = it->c_str();
- cmMakefile::ScopePushPop raii(globalMF.get());
- cmMakefile* mf = globalMF.get();
+ for (std::string const& gen : generatorsVector) {
+ cmMakefile::ScopePushPop raii(&globalMF);
+ cmMakefile* mf = &globalMF;
cmCPack_Log(&log, cmCPackLog::LOG_VERBOSE,
"Specified generator: " << gen << std::endl);
if (parsed && !mf->GetDefinition("CPACK_PACKAGE_NAME")) {
@@ -355,13 +348,14 @@ int main(int argc, char const* const* argv)
}
if (!mf->GetDefinition("CPACK_INSTALL_COMMANDS") &&
+ !mf->GetDefinition("CPACK_INSTALL_SCRIPT") &&
!mf->GetDefinition("CPACK_INSTALLED_DIRECTORIES") &&
!mf->GetDefinition("CPACK_INSTALL_CMAKE_PROJECTS")) {
cmCPack_Log(
&log, cmCPackLog::LOG_ERROR,
"Please specify build tree of the project that uses CMake "
"using CPACK_INSTALL_CMAKE_PROJECTS, specify "
- "CPACK_INSTALL_COMMANDS, or specify "
+ "CPACK_INSTALL_COMMANDS, CPACK_INSTALL_SCRIPT, or "
"CPACK_INSTALLED_DIRECTORIES."
<< std::endl);
parsed = 0;
@@ -414,12 +408,10 @@ int main(int argc, char const* const* argv)
doc.PrependSection("Options", cmDocumentationOptions);
std::vector<cmDocumentationEntry> v;
- cmCPackGeneratorFactory::DescriptionsMap::const_iterator generatorIt;
- for (generatorIt = generators.GetGeneratorsList().begin();
- generatorIt != generators.GetGeneratorsList().end(); ++generatorIt) {
+ for (auto const& g : generators.GetGeneratorsList()) {
cmDocumentationEntry e;
- e.Name = generatorIt->first;
- e.Brief = generatorIt->second;
+ e.Name = g.first;
+ e.Brief = g.second;
v.push_back(e);
}
doc.SetSection("Generators", v);
diff --git a/Source/CTest/cmCTestBZR.cxx b/Source/CTest/cmCTestBZR.cxx
index 94f39c265..015220091 100644
--- a/Source/CTest/cmCTestBZR.cxx
+++ b/Source/CTest/cmCTestBZR.cxx
@@ -98,7 +98,7 @@ private:
bool CheckOutFound;
cmsys::RegularExpression RegexCheckOut;
cmsys::RegularExpression RegexParent;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexCheckOut.find(this->Line)) {
this->BZR->URL = this->RegexCheckOut.match(1);
@@ -123,7 +123,7 @@ public:
private:
std::string& Rev;
cmsys::RegularExpression RegexRevno;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexRevno.find(this->Line)) {
this->Rev = this->RegexRevno.match(1);
@@ -136,13 +136,13 @@ std::string cmCTestBZR::LoadInfo()
{
// Run "bzr info" to get the repository info from the work tree.
const char* bzr = this->CommandLineTool.c_str();
- const char* bzr_info[] = { bzr, "info", CM_NULLPTR };
+ const char* bzr_info[] = { bzr, "info", nullptr };
InfoParser iout(this, "info-out> ");
OutputLogger ierr(this->Log, "info-err> ");
this->RunChild(bzr_info, &iout, &ierr);
// Run "bzr revno" to get the repository revision number from the work tree.
- const char* bzr_revno[] = { bzr, "revno", CM_NULLPTR };
+ const char* bzr_revno[] = { bzr, "revno", nullptr };
std::string rev;
RevnoParser rout(this, "revno-out> ", rev);
OutputLogger rerr(this->Log, "revno-err> ");
@@ -182,15 +182,15 @@ public:
{
this->InitializeParser();
}
- ~LogParser() CM_OVERRIDE { this->CleanupParser(); }
+ ~LogParser() override { this->CleanupParser(); }
- int InitializeParser() CM_OVERRIDE
+ int InitializeParser() override
{
int res = cmXMLParser::InitializeParser();
if (res) {
XML_SetUnknownEncodingHandler(static_cast<XML_Parser>(this->Parser),
cmBZRXMLParserUnknownEncodingHandler,
- CM_NULLPTR);
+ nullptr);
}
return res;
}
@@ -207,14 +207,14 @@ private:
cmsys::RegularExpression EmailRegex;
- bool ProcessChunk(const char* data, int length) CM_OVERRIDE
+ bool ProcessChunk(const char* data, int length) override
{
this->OutputLogger::ProcessChunk(data, length);
this->ParseChunk(data, length);
return true;
}
- void StartElement(const std::string& name, const char** /*atts*/) CM_OVERRIDE
+ void StartElement(const std::string& name, const char** /*atts*/) override
{
this->CData.clear();
if (name == "log") {
@@ -239,12 +239,12 @@ private:
}
}
- void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
+ void CharacterDataHandler(const char* data, int length) override
{
this->CData.insert(this->CData.end(), data, data + length);
}
- void EndElement(const std::string& name) CM_OVERRIDE
+ void EndElement(const std::string& name) override
{
if (name == "log") {
this->BZR->DoRevision(this->Rev, this->Changes);
@@ -274,7 +274,7 @@ private:
this->CData.clear();
}
- void ReportError(int /*line*/, int /*column*/, const char* msg) CM_OVERRIDE
+ void ReportError(int /*line*/, int /*column*/, const char* msg) override
{
this->BZR->Log << "Error parsing bzr log xml: " << msg << "\n";
}
@@ -294,7 +294,7 @@ private:
cmCTestBZR* BZR;
cmsys::RegularExpression RegexUpdate;
- bool ProcessChunk(const char* first, int length) CM_OVERRIDE
+ bool ProcessChunk(const char* first, int length) override
{
bool last_is_new_line = (*first == '\r' || *first == '\n');
@@ -309,11 +309,11 @@ private:
// Hand this line to the subclass implementation.
if (!this->ProcessLine()) {
- this->Line = "";
+ this->Line.clear();
return false;
}
- this->Line = "";
+ this->Line.clear();
last_is_new_line = true;
}
} else {
@@ -325,7 +325,7 @@ private:
return true;
}
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexUpdate.find(this->Line)) {
this->DoPath(this->RegexUpdate.match(1)[0],
@@ -373,14 +373,13 @@ bool cmCTestBZR::UpdateImpl()
bzr_update.push_back(this->CommandLineTool.c_str());
bzr_update.push_back("pull");
- for (std::vector<std::string>::const_iterator ai = args.begin();
- ai != args.end(); ++ai) {
- bzr_update.push_back(ai->c_str());
+ for (std::string const& arg : args) {
+ bzr_update.push_back(arg.c_str());
}
bzr_update.push_back(this->URL.c_str());
- bzr_update.push_back(CM_NULLPTR);
+ bzr_update.push_back(nullptr);
// For some reason bzr uses stderr to display the update status.
OutputLogger out(this->Log, "pull-out> ");
@@ -408,8 +407,7 @@ bool cmCTestBZR::LoadRevisions()
// Run "bzr log" to get all global revisions of interest.
const char* bzr = this->CommandLineTool.c_str();
const char* bzr_log[] = {
- bzr, "log", "-v", "-r", revs.c_str(), "--xml", this->URL.c_str(),
- CM_NULLPTR
+ bzr, "log", "-v", "-r", revs.c_str(), "--xml", this->URL.c_str(), nullptr
};
{
LogParser out(this, "log-out> ");
@@ -433,7 +431,7 @@ public:
private:
cmCTestBZR* BZR;
cmsys::RegularExpression RegexStatus;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexStatus.find(this->Line)) {
this->DoPath(this->RegexStatus.match(1)[0],
@@ -467,7 +465,7 @@ bool cmCTestBZR::LoadModifications()
{
// Run "bzr status" which reports local modifications.
const char* bzr = this->CommandLineTool.c_str();
- const char* bzr_status[] = { bzr, "status", "-SV", CM_NULLPTR };
+ const char* bzr_status[] = { bzr, "status", "-SV", nullptr };
StatusParser out(this, "status-out> ");
OutputLogger err(this->Log, "status-err> ");
this->RunChild(bzr_status, &out, &err);
diff --git a/Source/CTest/cmCTestBZR.h b/Source/CTest/cmCTestBZR.h
index 2e8e88f95..d5c78c760 100644
--- a/Source/CTest/cmCTestBZR.h
+++ b/Source/CTest/cmCTestBZR.h
@@ -3,7 +3,7 @@
#ifndef cmCTestBZR_h
#define cmCTestBZR_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestGlobalVC.h"
@@ -22,20 +22,20 @@ public:
/** Construct with a CTest instance and update log stream. */
cmCTestBZR(cmCTest* ctest, std::ostream& log);
- ~cmCTestBZR() CM_OVERRIDE;
+ ~cmCTestBZR() override;
private:
// Implement cmCTestVC internal API.
- bool NoteOldRevision() CM_OVERRIDE;
- bool NoteNewRevision() CM_OVERRIDE;
- bool UpdateImpl() CM_OVERRIDE;
+ bool NoteOldRevision() override;
+ bool NoteNewRevision() override;
+ bool UpdateImpl() override;
// URL of repository directory checked out in the working tree.
std::string URL;
std::string LoadInfo();
- bool LoadModifications() CM_OVERRIDE;
- bool LoadRevisions() CM_OVERRIDE;
+ bool LoadModifications() override;
+ bool LoadRevisions() override;
// Parsing helper classes.
class InfoParser;
diff --git a/Source/CTest/cmCTestBatchTestHandler.cxx b/Source/CTest/cmCTestBatchTestHandler.cxx
index beee53a13..2eed8bed9 100644
--- a/Source/CTest/cmCTestBatchTestHandler.cxx
+++ b/Source/CTest/cmCTestBatchTestHandler.cxx
@@ -29,10 +29,9 @@ void cmCTestBatchTestHandler::WriteBatchScript()
fout.open(this->Script.c_str());
fout << "#!/bin/sh\n";
- for (TestMap::iterator i = this->Tests.begin(); i != this->Tests.end();
- ++i) {
- this->WriteSrunArgs(i->first, fout);
- this->WriteTestCommand(i->first, fout);
+ for (auto const& t : this->Tests) {
+ this->WriteSrunArgs(t.first, fout);
+ this->WriteTestCommand(t.first, fout);
fout << "\n";
}
fout.flush();
@@ -80,9 +79,8 @@ void cmCTestBatchTestHandler::WriteTestCommand(int test, std::ostream& fout)
this->TestHandler->GenerateTestCommand(processArgs, test);
processArgs.push_back(command);
- for (std::vector<std::string>::iterator arg = processArgs.begin();
- arg != processArgs.end(); ++arg) {
- fout << *arg << " ";
+ for (std::string const& arg : processArgs) {
+ fout << arg << " ";
}
std::vector<std::string>::iterator i = args.begin();
diff --git a/Source/CTest/cmCTestBatchTestHandler.h b/Source/CTest/cmCTestBatchTestHandler.h
index 4a5dac1d6..42f87bddd 100644
--- a/Source/CTest/cmCTestBatchTestHandler.h
+++ b/Source/CTest/cmCTestBatchTestHandler.h
@@ -3,7 +3,7 @@
#ifndef cmCTestBatchTestHandler_h
#define cmCTestBatchTestHandler_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestMultiProcessHandler.h"
#include "cmsys/FStream.hxx"
@@ -17,8 +17,8 @@
class cmCTestBatchTestHandler : public cmCTestMultiProcessHandler
{
public:
- ~cmCTestBatchTestHandler() CM_OVERRIDE;
- void RunTests() CM_OVERRIDE;
+ ~cmCTestBatchTestHandler() override;
+ void RunTests() override;
protected:
void WriteBatchScript();
diff --git a/Source/CTest/cmCTestBuildAndTestHandler.cxx b/Source/CTest/cmCTestBuildAndTestHandler.cxx
index cc290715c..a0d68a066 100644
--- a/Source/CTest/cmCTestBuildAndTestHandler.cxx
+++ b/Source/CTest/cmCTestBuildAndTestHandler.cxx
@@ -32,7 +32,7 @@ const char* cmCTestBuildAndTestHandler::GetOutput()
}
int cmCTestBuildAndTestHandler::ProcessHandler()
{
- this->Output = "";
+ this->Output.clear();
std::string output;
cmSystemTools::ResetErrorOccuredFlag();
int retv = this->RunCMakeAndTest(&this->Output);
@@ -45,7 +45,6 @@ int cmCTestBuildAndTestHandler::RunCMake(std::string* outstring,
std::string& cmakeOutString,
cmake* cm)
{
- unsigned int k;
std::vector<std::string> args;
args.push_back(cmSystemTools::GetCMakeCommand());
args.push_back(this->SourceDir);
@@ -65,7 +64,7 @@ int cmCTestBuildAndTestHandler::RunCMake(std::string* outstring,
args.push_back(toolset);
}
- const char* config = CM_NULLPTR;
+ const char* config = nullptr;
if (!this->CTest->GetConfigType().empty()) {
config = this->CTest->GetConfigType().c_str();
}
@@ -80,8 +79,8 @@ int cmCTestBuildAndTestHandler::RunCMake(std::string* outstring,
args.push_back(btype);
}
- for (k = 0; k < this->BuildOptions.size(); ++k) {
- args.push_back(this->BuildOptions[k]);
+ for (std::string const& opt : this->BuildOptions) {
+ args.push_back(opt);
}
if (cm->Run(args) != 0) {
out << "Error: cmake execution failed\n";
@@ -115,21 +114,21 @@ int cmCTestBuildAndTestHandler::RunCMake(std::string* outstring,
void CMakeMessageCallback(const char* m, const char* /*unused*/,
bool& /*unused*/, void* s)
{
- std::string* out = (std::string*)s;
+ std::string* out = static_cast<std::string*>(s);
*out += m;
*out += "\n";
}
void CMakeProgressCallback(const char* msg, float /*unused*/, void* s)
{
- std::string* out = (std::string*)s;
+ std::string* out = static_cast<std::string*>(s);
*out += msg;
*out += "\n";
}
void CMakeOutputCallback(const char* m, size_t len, void* s)
{
- std::string* out = (std::string*)s;
+ std::string* out = static_cast<std::string*>(s);
out->append(m, len);
}
@@ -148,10 +147,10 @@ public:
}
~cmCTestBuildAndTestCaptureRAII()
{
- this->CM.SetProgressCallback(CM_NULLPTR, CM_NULLPTR);
- cmSystemTools::SetStderrCallback(CM_NULLPTR, CM_NULLPTR);
- cmSystemTools::SetStdoutCallback(CM_NULLPTR, CM_NULLPTR);
- cmSystemTools::SetMessageCallback(CM_NULLPTR, CM_NULLPTR);
+ this->CM.SetProgressCallback(nullptr, nullptr);
+ cmSystemTools::SetStderrCallback(nullptr, nullptr);
+ cmSystemTools::SetStdoutCallback(nullptr, nullptr);
+ cmSystemTools::SetMessageCallback(nullptr, nullptr);
}
};
@@ -219,12 +218,10 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
}
// do the build
- std::vector<std::string>::iterator tarIt;
if (this->BuildTargets.empty()) {
this->BuildTargets.push_back("");
}
- for (tarIt = this->BuildTargets.begin(); tarIt != this->BuildTargets.end();
- ++tarIt) {
+ for (std::string const& tar : this->BuildTargets) {
double remainingTime = 0;
if (this->Timeout > 0) {
remainingTime = this->Timeout - cmSystemTools::GetTime() + clock_start;
@@ -236,7 +233,7 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
}
}
std::string output;
- const char* config = CM_NULLPTR;
+ const char* config = nullptr;
if (!this->CTest->GetConfigType().empty()) {
config = this->CTest->GetConfigType().c_str();
}
@@ -249,7 +246,7 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
config = "Debug";
}
int retVal = cm.GetGlobalGenerator()->Build(
- this->SourceDir, this->BinaryDir, this->BuildProject, *tarIt, output,
+ this->SourceDir, this->BinaryDir, this->BuildProject, tar, output,
this->BuildMakeProgram, config, !this->BuildNoClean, false, false,
remainingTime);
out << output;
@@ -292,8 +289,8 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
<< this->TestCommand << "\n";
out << "tried to find it in these places:\n";
out << fullPath << "\n";
- for (unsigned int i = 0; i < failed.size(); ++i) {
- out << failed[i] << "\n";
+ for (std::string const& fail : failed) {
+ out << fail << "\n";
}
if (outstring) {
*outstring = out.str();
@@ -305,10 +302,10 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
std::vector<const char*> testCommand;
testCommand.push_back(fullPath.c_str());
- for (size_t k = 0; k < this->TestCommandArgs.size(); ++k) {
- testCommand.push_back(this->TestCommandArgs[k].c_str());
+ for (std::string const& testCommandArg : this->TestCommandArgs) {
+ testCommand.push_back(testCommandArg.c_str());
}
- testCommand.push_back(CM_NULLPTR);
+ testCommand.push_back(nullptr);
std::string outs;
int retval = 0;
// run the test from the this->BuildRunDir if set
@@ -317,8 +314,8 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
cmSystemTools::ChangeDirectory(this->BuildRunDir);
}
out << "Running test command: \"" << fullPath << "\"";
- for (size_t k = 0; k < this->TestCommandArgs.size(); ++k) {
- out << " \"" << this->TestCommandArgs[k] << "\"";
+ for (std::string const& testCommandArg : this->TestCommandArgs) {
+ out << " \"" << testCommandArg << "\"";
}
out << "\n";
@@ -334,8 +331,8 @@ int cmCTestBuildAndTestHandler::RunCMakeAndTest(std::string* outstring)
}
}
- int runTestRes = this->CTest->RunTest(testCommand, &outs, &retval,
- CM_NULLPTR, remainingTime, CM_NULLPTR);
+ int runTestRes = this->CTest->RunTest(testCommand, &outs, &retval, nullptr,
+ remainingTime, nullptr);
if (runTestRes != cmsysProcess_State_Exited || retval != 0) {
out << "Test command failed: " << testCommand[0] << "\n";
diff --git a/Source/CTest/cmCTestBuildAndTestHandler.h b/Source/CTest/cmCTestBuildAndTestHandler.h
index 2e85e9fed..f19cb67ce 100644
--- a/Source/CTest/cmCTestBuildAndTestHandler.h
+++ b/Source/CTest/cmCTestBuildAndTestHandler.h
@@ -3,7 +3,7 @@
#ifndef cmCTestBuildAndTestHandler_h
#define cmCTestBuildAndTestHandler_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestGenericHandler.h"
@@ -26,12 +26,12 @@ public:
/*
* The main entry point for this class
*/
- int ProcessHandler() CM_OVERRIDE;
+ int ProcessHandler() override;
//! Set all the build and test arguments
- int ProcessCommandLineArguments(const std::string& currentArg, size_t& idx,
- const std::vector<std::string>& allArgs)
- CM_OVERRIDE;
+ int ProcessCommandLineArguments(
+ const std::string& currentArg, size_t& idx,
+ const std::vector<std::string>& allArgs) override;
/*
* Get the output variable
@@ -40,7 +40,7 @@ public:
cmCTestBuildAndTestHandler();
- void Initialize() CM_OVERRIDE;
+ void Initialize() override;
protected:
///! Run CMake and build a test and then run it as a single test.
diff --git a/Source/CTest/cmCTestBuildCommand.cxx b/Source/CTest/cmCTestBuildCommand.cxx
index 4c8276007..ce27da18a 100644
--- a/Source/CTest/cmCTestBuildCommand.cxx
+++ b/Source/CTest/cmCTestBuildCommand.cxx
@@ -17,14 +17,14 @@ class cmExecutionStatus;
cmCTestBuildCommand::cmCTestBuildCommand()
{
- this->GlobalGenerator = CM_NULLPTR;
+ this->GlobalGenerator = nullptr;
this->Arguments[ctb_NUMBER_ERRORS] = "NUMBER_ERRORS";
this->Arguments[ctb_NUMBER_WARNINGS] = "NUMBER_WARNINGS";
this->Arguments[ctb_TARGET] = "TARGET";
this->Arguments[ctb_CONFIGURATION] = "CONFIGURATION";
this->Arguments[ctb_FLAGS] = "FLAGS";
this->Arguments[ctb_PROJECT_NAME] = "PROJECT_NAME";
- this->Arguments[ctb_LAST] = CM_NULLPTR;
+ this->Arguments[ctb_LAST] = nullptr;
this->Last = ctb_LAST;
}
@@ -32,7 +32,7 @@ cmCTestBuildCommand::~cmCTestBuildCommand()
{
if (this->GlobalGenerator) {
delete this->GlobalGenerator;
- this->GlobalGenerator = CM_NULLPTR;
+ this->GlobalGenerator = nullptr;
}
}
@@ -41,9 +41,9 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler()
cmCTestGenericHandler* handler = this->CTest->GetInitializedHandler("build");
if (!handler) {
this->SetError("internal CTest error. Cannot instantiate build handler");
- return CM_NULLPTR;
+ return nullptr;
}
- this->Handler = (cmCTestBuildHandler*)handler;
+ this->Handler = static_cast<cmCTestBuildHandler*>(handler);
const char* ctestBuildCommand =
this->Makefile->GetDefinition("CTEST_BUILD_COMMAND");
@@ -89,7 +89,7 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler()
if (this->GlobalGenerator) {
if (this->GlobalGenerator->GetName() != cmakeGeneratorName) {
delete this->GlobalGenerator;
- this->GlobalGenerator = CM_NULLPTR;
+ this->GlobalGenerator = nullptr;
}
}
if (!this->GlobalGenerator) {
@@ -102,11 +102,11 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler()
e += "\"";
this->Makefile->IssueMessage(cmake::FATAL_ERROR, e);
cmSystemTools::SetFatalErrorOccured();
- return CM_NULLPTR;
+ return nullptr;
}
}
if (strlen(cmakeBuildConfiguration) == 0) {
- const char* config = CM_NULLPTR;
+ const char* config = nullptr;
#ifdef CMAKE_INTDIR
config = CMAKE_INTDIR;
#endif
@@ -143,7 +143,7 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler()
"with a custom command line.";
/* clang-format on */
this->SetError(ostr.str());
- return CM_NULLPTR;
+ return nullptr;
}
}
@@ -153,6 +153,12 @@ cmCTestGenericHandler* cmCTestBuildCommand::InitializeHandler()
this->Quiet);
}
+ if (const char* labelsForSubprojects =
+ this->Makefile->GetDefinition("CTEST_LABELS_FOR_SUBPROJECTS")) {
+ this->CTest->SetCTestConfiguration("LabelsForSubprojects",
+ labelsForSubprojects, this->Quiet);
+ }
+
handler->SetQuiet(this->Quiet);
return handler;
}
diff --git a/Source/CTest/cmCTestBuildCommand.h b/Source/CTest/cmCTestBuildCommand.h
index 9cf6a9652..77b05498d 100644
--- a/Source/CTest/cmCTestBuildCommand.h
+++ b/Source/CTest/cmCTestBuildCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestBuildCommand_h
#define cmCTestBuildCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestHandlerCommand.h"
@@ -25,12 +25,12 @@ class cmCTestBuildCommand : public cmCTestHandlerCommand
{
public:
cmCTestBuildCommand();
- ~cmCTestBuildCommand() CM_OVERRIDE;
+ ~cmCTestBuildCommand() override;
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestBuildCommand* ni = new cmCTestBuildCommand;
ni->CTest = this->CTest;
@@ -41,10 +41,10 @@ public:
/**
* The name of the command as specified in CMakeList.txt.
*/
- std::string GetName() const CM_OVERRIDE { return "ctest_build"; }
+ std::string GetName() const override { return "ctest_build"; }
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
cmGlobalGenerator* GlobalGenerator;
@@ -62,7 +62,7 @@ protected:
ctb_LAST
};
- cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
+ cmCTestGenericHandler* InitializeHandler() override;
};
#endif
diff --git a/Source/CTest/cmCTestBuildHandler.cxx b/Source/CTest/cmCTestBuildHandler.cxx
index 18ef05c67..f4fc76929 100644
--- a/Source/CTest/cmCTestBuildHandler.cxx
+++ b/Source/CTest/cmCTestBuildHandler.cxx
@@ -74,7 +74,7 @@ static const char* cmCTestErrorMatches[] = {
"^The project cannot be built\\.",
"^\\[ERROR\\]",
"^Command .* failed with exit code",
- CM_NULLPTR
+ nullptr
};
static const char* cmCTestErrorExceptions[] = {
@@ -89,7 +89,7 @@ static const char* cmCTestErrorExceptions[] = {
":[ \\t]+Where:",
"([^ :]+):([0-9]+): Warning",
"------ Build started: .* ------",
- CM_NULLPTR
+ nullptr
};
static const char* cmCTestWarningMatches[] = {
@@ -114,7 +114,7 @@ static const char* cmCTestWarningMatches[] = {
"cc-[0-9]* CC: REMARK File = .*, Line = [0-9]*",
"^CMake Warning.*:",
"^\\[WARNING\\]",
- CM_NULLPTR
+ nullptr
};
static const char* cmCTestWarningExceptions[] = {
@@ -134,7 +134,7 @@ static const char* cmCTestWarningExceptions[] = {
"ld32: WARNING 85: definition of dataKey in",
"cc: warning 422: Unknown option \"\\+b",
"_with_warning_C",
- CM_NULLPTR
+ nullptr
};
struct cmCTestBuildCompileErrorWarningRex
@@ -152,7 +152,7 @@ static cmCTestBuildCompileErrorWarningRex cmCTestWarningErrorFileLine[] = {
{ "^([a-zA-Z./0-9_+ ~-]+)\\(([0-9]+)\\)", 1, 2 },
{ "\"([a-zA-Z./0-9_+ ~-]+)\", line ([0-9]+)", 1, 2 },
{ "File = ([a-zA-Z./0-9_+ ~-]+), Line = ([0-9]+)", 1, 2 },
- { CM_NULLPTR, 0, 0 }
+ { nullptr, 0, 0 }
};
cmCTestBuildHandler::cmCTestBuildHandler()
@@ -171,8 +171,8 @@ cmCTestBuildHandler::cmCTestBuildHandler()
void cmCTestBuildHandler::Initialize()
{
this->Superclass::Initialize();
- this->StartBuild = "";
- this->EndBuild = "";
+ this->StartBuild.clear();
+ this->EndBuild.clear();
this->CustomErrorMatches.clear();
this->CustomErrorExceptions.clear();
this->CustomWarningMatches.clear();
@@ -190,8 +190,8 @@ void cmCTestBuildHandler::Initialize()
this->BuildOutputLogSize = 0;
this->CurrentProcessingLine.clear();
- this->SimplifySourceDir = "";
- this->SimplifyBuildDir = "";
+ this->SimplifySourceDir.clear();
+ this->SimplifyBuildDir.clear();
this->OutputLineCounter = 0;
this->ErrorsAndWarnings.clear();
this->LastErrorOrWarning = this->ErrorsAndWarnings.end();
@@ -260,11 +260,11 @@ std::string cmCTestBuildHandler::GetMakeCommand()
"MakeCommand:" << makeCommand << "\n", this->Quiet);
std::string configType = this->CTest->GetConfigType();
- if (configType == "") {
+ if (configType.empty()) {
configType =
this->CTest->GetCTestConfiguration("DefaultCTestConfigurationType");
}
- if (configType == "") {
+ if (configType.empty()) {
configType = "Release";
}
@@ -350,18 +350,16 @@ int cmCTestBuildHandler::ProcessHandler()
this->CustomWarningExceptions.push_back(cmCTestWarningExceptions[cc]);
}
- // Pre-compile regular expressions objects for all regular expressions
- std::vector<std::string>::iterator it;
+// Pre-compile regular expressions objects for all regular expressions
#define cmCTestBuildHandlerPopulateRegexVector(strings, regexes) \
regexes.clear(); \
cmCTestOptionalLog(this->CTest, DEBUG, \
this << "Add " #regexes << std::endl, this->Quiet); \
- for (it = (strings).begin(); it != (strings).end(); ++it) { \
+ for (std::string const& s : (strings)) { \
cmCTestOptionalLog(this->CTest, DEBUG, \
- "Add " #strings ": " << *it << std::endl, \
- this->Quiet); \
- (regexes).push_back(it->c_str()); \
+ "Add " #strings ": " << s << std::endl, this->Quiet); \
+ (regexes).push_back(s.c_str()); \
}
cmCTestBuildHandlerPopulateRegexVector(this->CustomErrorMatches,
this->ErrorMatchRegex);
@@ -373,8 +371,8 @@ int cmCTestBuildHandler::ProcessHandler()
this->WarningExceptionRegex);
// Determine source and binary tree substitutions to simplify the output.
- this->SimplifySourceDir = "";
- this->SimplifyBuildDir = "";
+ this->SimplifySourceDir.clear();
+ this->SimplifyBuildDir.clear();
if (this->CTest->GetCTestConfiguration("SourceDirectory").size() > 20) {
std::string srcdir =
this->CTest->GetCTestConfiguration("SourceDirectory") + "/";
@@ -426,27 +424,24 @@ int cmCTestBuildHandler::ProcessHandler()
double elapsed_build_time = cmSystemTools::GetTime() - elapsed_time_start;
// Cleanups strings in the errors and warnings list.
- t_ErrorsAndWarningsVector::iterator evit;
if (!this->SimplifySourceDir.empty()) {
- for (evit = this->ErrorsAndWarnings.begin();
- evit != this->ErrorsAndWarnings.end(); ++evit) {
- cmSystemTools::ReplaceString(evit->Text, this->SimplifySourceDir.c_str(),
+ for (cmCTestBuildErrorWarning& evit : this->ErrorsAndWarnings) {
+ cmSystemTools::ReplaceString(evit.Text, this->SimplifySourceDir.c_str(),
"/.../");
- cmSystemTools::ReplaceString(evit->PreContext,
+ cmSystemTools::ReplaceString(evit.PreContext,
this->SimplifySourceDir.c_str(), "/.../");
- cmSystemTools::ReplaceString(evit->PostContext,
+ cmSystemTools::ReplaceString(evit.PostContext,
this->SimplifySourceDir.c_str(), "/.../");
}
}
if (!this->SimplifyBuildDir.empty()) {
- for (evit = this->ErrorsAndWarnings.begin();
- evit != this->ErrorsAndWarnings.end(); ++evit) {
- cmSystemTools::ReplaceString(evit->Text, this->SimplifyBuildDir.c_str(),
+ for (cmCTestBuildErrorWarning& evit : this->ErrorsAndWarnings) {
+ cmSystemTools::ReplaceString(evit.Text, this->SimplifyBuildDir.c_str(),
"/.../");
- cmSystemTools::ReplaceString(evit->PreContext,
+ cmSystemTools::ReplaceString(evit.PreContext,
this->SimplifyBuildDir.c_str(), "/.../");
- cmSystemTools::ReplaceString(evit->PostContext,
+ cmSystemTools::ReplaceString(evit.PostContext,
this->SimplifyBuildDir.c_str(), "/.../");
}
}
@@ -488,6 +483,7 @@ int cmCTestBuildHandler::ProcessHandler()
void cmCTestBuildHandler::GenerateXMLHeader(cmXMLWriter& xml)
{
this->CTest->StartXML(xml, this->AppendXML);
+ this->CTest->GenerateSubprojectsOutput(xml);
xml.StartElement("Build");
xml.Element("StartDateTime", this->StartBuild);
xml.Element("StartBuildTime",
@@ -503,7 +499,7 @@ public:
{
}
FragmentCompare()
- : FTC(CM_NULLPTR)
+ : FTC(nullptr)
{
}
bool operator()(std::string const& l, std::string const& r) const
@@ -555,9 +551,8 @@ void cmCTestBuildHandler::GenerateXMLLaunched(cmXMLWriter& xml)
}
// Copy the fragments into the final XML file.
- for (Fragments::const_iterator fi = fragments.begin(); fi != fragments.end();
- ++fi) {
- xml.FragmentFile(fi->c_str());
+ for (std::string const& f : fragments) {
+ xml.FragmentFile(f.c_str());
}
}
@@ -587,12 +582,11 @@ void cmCTestBuildHandler::GenerateXMLLogScraped(cmXMLWriter& xml)
xml.StartElement(cm->Error ? "Error" : "Warning");
xml.Element("BuildLogLine", cm->LogLine);
xml.Element("Text", cm->Text);
- std::vector<cmCTestCompileErrorWarningRex>::iterator rit;
- for (rit = this->ErrorWarningFileLineRegex.begin();
- rit != this->ErrorWarningFileLineRegex.end(); ++rit) {
- cmsys::RegularExpression* re = &rit->RegularExpression;
+ for (cmCTestCompileErrorWarningRex& rit :
+ this->ErrorWarningFileLineRegex) {
+ cmsys::RegularExpression* re = &rit.RegularExpression;
if (re->find(cm->Text.c_str())) {
- cm->SourceFile = re->match(rit->FileIndex);
+ cm->SourceFile = re->match(rit.FileIndex);
// At this point we need to make this->SourceFile relative to
// the source root of the project, so cvs links will work
cmSystemTools::ConvertToUnixSlashes(cm->SourceFile);
@@ -608,7 +602,7 @@ void cmCTestBuildHandler::GenerateXMLLogScraped(cmXMLWriter& xml)
cm->SourceFile = cmSystemTools::CollapseFullPath(cm->SourceFile);
cmSystemTools::ReplaceString(cm->SourceFile, srcdir.c_str(), "");
}
- cm->LineNumber = atoi(re->match(rit->LineIndex).c_str());
+ cm->LineNumber = atoi(re->match(rit.LineIndex).c_str());
break;
}
}
@@ -758,9 +752,8 @@ void cmCTestBuildHandler::LaunchHelper::WriteScrapeMatchers(
fname += purpose;
fname += ".txt";
cmGeneratedFileStream fout(fname.c_str());
- for (std::vector<std::string>::const_iterator mi = matchers.begin();
- mi != matchers.end(); ++mi) {
- fout << *mi << "\n";
+ for (std::string const& m : matchers) {
+ fout << m << "\n";
}
}
@@ -776,18 +769,20 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
}
std::vector<const char*> argv;
- for (std::vector<std::string>::const_iterator a = args.begin();
- a != args.end(); ++a) {
- argv.push_back(a->c_str());
+ argv.reserve(args.size() + 1);
+ for (std::string const& arg : args) {
+ argv.push_back(arg.c_str());
}
- argv.push_back(CM_NULLPTR);
+ argv.push_back(nullptr);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Run command:",
this->Quiet);
- std::vector<const char*>::iterator ait;
- for (ait = argv.begin(); ait != argv.end() && *ait; ++ait) {
+ for (char const* arg : argv) {
+ if (!arg) {
+ break;
+ }
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
- " \"" << *ait << "\"", this->Quiet);
+ " \"" << arg << "\"", this->Quiet);
}
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl,
this->Quiet);
@@ -834,7 +829,7 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
// For every chunk of data
int res;
- while ((res = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR))) {
+ while ((res = cmsysProcess_WaitForData(cp, &data, &length, nullptr))) {
// Replace '\0' with '\n', since '\0' does not really make sense. This is
// for Visual Studio output
for (int cc = 0; cc < length; ++cc) {
@@ -865,9 +860,9 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
&this->BuildProcessingQueue);
}
- this->ProcessBuffer(CM_NULLPTR, 0, tick, tick_len, ofs,
+ this->ProcessBuffer(nullptr, 0, tick, tick_len, ofs,
&this->BuildProcessingQueue);
- this->ProcessBuffer(CM_NULLPTR, 0, tick, tick_len, ofs,
+ this->ProcessBuffer(nullptr, 0, tick, tick_len, ofs,
&this->BuildProcessingErrorQueue);
cmCTestOptionalLog(this->CTest, HANDLER_PROGRESS_OUTPUT, " Size of output: "
<< ((this->BuildOutputLogSize + 512) / 1024) << "K"
@@ -875,7 +870,7 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
this->Quiet);
// Properly handle output of the build command
- cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ cmsysProcess_WaitForExit(cp, nullptr);
int result = cmsysProcess_GetState(cp);
if (result == cmsysProcess_State_Exited) {
@@ -894,8 +889,8 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
errorwarning.Text =
"*** WARNING non-zero return value in ctest from: ";
errorwarning.Text += argv[0];
- errorwarning.PreContext = "";
- errorwarning.PostContext = "";
+ errorwarning.PreContext.clear();
+ errorwarning.PostContext.clear();
errorwarning.Error = false;
this->ErrorsAndWarnings.push_back(errorwarning);
this->TotalWarnings++;
@@ -917,8 +912,8 @@ int cmCTestBuildHandler::RunMakeCommand(const char* command, int* retVal,
errorwarning.LogLine = 1;
errorwarning.Text = "*** ERROR executing: ";
errorwarning.Text += cmsysProcess_GetErrorString(cp);
- errorwarning.PreContext = "";
- errorwarning.PostContext = "";
+ errorwarning.PreContext.clear();
+ errorwarning.PostContext.clear();
errorwarning.Error = true;
this->ErrorsAndWarnings.push_back(errorwarning);
this->TotalErrors++;
@@ -1002,14 +997,12 @@ void cmCTestBuildHandler::ProcessBuffer(const char* data, size_t length,
// This is an error or warning, so generate report
errorwarning.LogLine = static_cast<int>(this->OutputLineCounter + 1);
errorwarning.Text = line;
- errorwarning.PreContext = "";
- errorwarning.PostContext = "";
+ errorwarning.PreContext.clear();
+ errorwarning.PostContext.clear();
// Copy pre-context to report
- std::deque<std::string>::iterator pcit;
- for (pcit = this->PreContext.begin(); pcit != this->PreContext.end();
- ++pcit) {
- errorwarning.PreContext += *pcit + "\n";
+ for (std::string const& pc : this->PreContext) {
+ errorwarning.PreContext += pc + "\n";
}
this->PreContext.clear();
@@ -1081,8 +1074,6 @@ int cmCTestBuildHandler::ProcessSingleLine(const char* data)
cmCTestOptionalLog(this->CTest, DEBUG, "Line: [" << data << "]" << std::endl,
this->Quiet);
- std::vector<cmsys::RegularExpression>::iterator it;
-
int warningLine = 0;
int errorLine = 0;
@@ -1091,9 +1082,8 @@ int cmCTestBuildHandler::ProcessSingleLine(const char* data)
if (!this->ErrorQuotaReached) {
// Errors
int wrxCnt = 0;
- for (it = this->ErrorMatchRegex.begin(); it != this->ErrorMatchRegex.end();
- ++it) {
- if (it->find(data)) {
+ for (cmsys::RegularExpression& rx : this->ErrorMatchRegex) {
+ if (rx.find(data)) {
errorLine = 1;
cmCTestOptionalLog(this->CTest, DEBUG,
" Error Line: " << data << " (matches: "
@@ -1106,9 +1096,8 @@ int cmCTestBuildHandler::ProcessSingleLine(const char* data)
}
// Error exceptions
wrxCnt = 0;
- for (it = this->ErrorExceptionRegex.begin();
- it != this->ErrorExceptionRegex.end(); ++it) {
- if (it->find(data)) {
+ for (cmsys::RegularExpression& rx : this->ErrorExceptionRegex) {
+ if (rx.find(data)) {
errorLine = 0;
cmCTestOptionalLog(this->CTest, DEBUG, " Not an error Line: "
<< data << " (matches: "
@@ -1123,9 +1112,8 @@ int cmCTestBuildHandler::ProcessSingleLine(const char* data)
if (!this->WarningQuotaReached) {
// Warnings
int wrxCnt = 0;
- for (it = this->WarningMatchRegex.begin();
- it != this->WarningMatchRegex.end(); ++it) {
- if (it->find(data)) {
+ for (cmsys::RegularExpression& rx : this->WarningMatchRegex) {
+ if (rx.find(data)) {
warningLine = 1;
cmCTestOptionalLog(this->CTest, DEBUG, " Warning Line: "
<< data << " (matches: "
@@ -1139,9 +1127,8 @@ int cmCTestBuildHandler::ProcessSingleLine(const char* data)
wrxCnt = 0;
// Warning exceptions
- for (it = this->WarningExceptionRegex.begin();
- it != this->WarningExceptionRegex.end(); ++it) {
- if (it->find(data)) {
+ for (cmsys::RegularExpression& rx : this->WarningExceptionRegex) {
+ if (rx.find(data)) {
warningLine = 0;
cmCTestOptionalLog(this->CTest, DEBUG, " Not a warning Line: "
<< data << " (matches: "
diff --git a/Source/CTest/cmCTestBuildHandler.h b/Source/CTest/cmCTestBuildHandler.h
index ef3cddf1b..6e71ad6ae 100644
--- a/Source/CTest/cmCTestBuildHandler.h
+++ b/Source/CTest/cmCTestBuildHandler.h
@@ -3,7 +3,7 @@
#ifndef cmCTestBuildHandler_h
#define cmCTestBuildHandler_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestGenericHandler.h"
@@ -31,16 +31,16 @@ public:
/*
* The main entry point for this class
*/
- int ProcessHandler() CM_OVERRIDE;
+ int ProcessHandler() override;
cmCTestBuildHandler();
- void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE;
+ void PopulateCustomVectors(cmMakefile* mf) override;
/**
* Initialize handler
*/
- void Initialize() CM_OVERRIDE;
+ void Initialize() override;
int GetTotalErrors() { return this->TotalErrors; }
int GetTotalWarnings() { return this->TotalWarnings; }
diff --git a/Source/CTest/cmCTestCVS.cxx b/Source/CTest/cmCTestCVS.cxx
index fad360ba4..5779935aa 100644
--- a/Source/CTest/cmCTestCVS.cxx
+++ b/Source/CTest/cmCTestCVS.cxx
@@ -46,7 +46,7 @@ private:
cmsys::RegularExpression RegexFileRemoved1;
cmsys::RegularExpression RegexFileRemoved2;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexFileUpdated.find(this->Line)) {
this->DoFile(PathUpdated, this->RegexFileUpdated.match(2));
@@ -92,11 +92,10 @@ bool cmCTestCVS::UpdateImpl()
cvs_update.push_back(this->CommandLineTool.c_str());
cvs_update.push_back("-z3");
cvs_update.push_back("update");
- for (std::vector<std::string>::const_iterator ai = args.begin();
- ai != args.end(); ++ai) {
- cvs_update.push_back(ai->c_str());
+ for (std::string const& arg : args) {
+ cvs_update.push_back(arg.c_str());
}
- cvs_update.push_back(CM_NULLPTR);
+ cvs_update.push_back(nullptr);
UpdateParser out(this, "up-out> ");
UpdateParser err(this, "up-err> ");
@@ -133,7 +132,7 @@ private:
SectionType Section;
Revision Rev;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->Line == ("======================================="
"======================================")) {
@@ -221,8 +220,9 @@ void cmCTestCVS::LoadRevisions(std::string const& file, const char* branchFlag,
// Run "cvs log" to get revisions of this file on this branch.
const char* cvs = this->CommandLineTool.c_str();
- const char* cvs_log[] = { cvs, "log", "-N",
- branchFlag, file.c_str(), CM_NULLPTR };
+ const char* cvs_log[] = {
+ cvs, "log", "-N", branchFlag, file.c_str(), nullptr
+ };
LogParser out(this, "log-out> ", revisions);
OutputLogger err(this->Log, "log-err> ");
@@ -241,12 +241,12 @@ void cmCTestCVS::WriteXMLDirectory(cmXMLWriter& xml, std::string const& path,
// Load revisions and write an entry for each file in this directory.
std::vector<Revision> revisions;
- for (Directory::const_iterator fi = dir.begin(); fi != dir.end(); ++fi) {
- std::string full = path + slash + fi->first;
+ for (auto const& fi : dir) {
+ std::string full = path + slash + fi.first;
// Load two real or unknown revisions.
revisions.clear();
- if (fi->second != PathUpdated) {
+ if (fi.second != PathUpdated) {
// For local modifications the current rev is unknown and the
// prior rev is the latest from cvs.
revisions.push_back(this->Unknown);
@@ -255,8 +255,8 @@ void cmCTestCVS::WriteXMLDirectory(cmXMLWriter& xml, std::string const& path,
revisions.resize(2, this->Unknown);
// Write the entry for this file with these revisions.
- File f(fi->second, &revisions[0], &revisions[1]);
- this->WriteXMLEntry(xml, path, fi->first, full, f);
+ File f(fi.second, &revisions[0], &revisions[1]);
+ this->WriteXMLEntry(xml, path, fi.first, full, f);
}
xml.EndElement(); // Directory
}
@@ -268,10 +268,8 @@ bool cmCTestCVS::WriteXMLUpdates(cmXMLWriter& xml)
" "
<< std::flush);
- for (std::map<std::string, Directory>::const_iterator di =
- this->Dirs.begin();
- di != this->Dirs.end(); ++di) {
- this->WriteXMLDirectory(xml, di->first, di->second);
+ for (auto const& d : this->Dirs) {
+ this->WriteXMLDirectory(xml, d.first, d.second);
}
cmCTestLog(this->CTest, HANDLER_OUTPUT, std::endl);
diff --git a/Source/CTest/cmCTestCVS.h b/Source/CTest/cmCTestCVS.h
index 1208cfad6..77fc3cc25 100644
--- a/Source/CTest/cmCTestCVS.h
+++ b/Source/CTest/cmCTestCVS.h
@@ -3,7 +3,7 @@
#ifndef cmCTestCVS_h
#define cmCTestCVS_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestVC.h"
@@ -25,12 +25,12 @@ public:
/** Construct with a CTest instance and update log stream. */
cmCTestCVS(cmCTest* ctest, std::ostream& log);
- ~cmCTestCVS() CM_OVERRIDE;
+ ~cmCTestCVS() override;
private:
// Implement cmCTestVC internal API.
- bool UpdateImpl() CM_OVERRIDE;
- bool WriteXMLUpdates(cmXMLWriter& xml) CM_OVERRIDE;
+ bool UpdateImpl() override;
+ bool WriteXMLUpdates(cmXMLWriter& xml) override;
// Update status for files in each directory.
class Directory : public std::map<std::string, PathStatus>
diff --git a/Source/CTest/cmCTestCommand.h b/Source/CTest/cmCTestCommand.h
index 6fc237aac..8efb4194c 100644
--- a/Source/CTest/cmCTestCommand.h
+++ b/Source/CTest/cmCTestCommand.h
@@ -20,8 +20,8 @@ class cmCTestCommand : public cmCommand
public:
cmCTestCommand()
{
- this->CTest = CM_NULLPTR;
- this->CTestScriptHandler = CM_NULLPTR;
+ this->CTest = nullptr;
+ this->CTestScriptHandler = nullptr;
}
cmCTest* CTest;
diff --git a/Source/CTest/cmCTestConfigureCommand.cxx b/Source/CTest/cmCTestConfigureCommand.cxx
index 73e893df3..c44b86605 100644
--- a/Source/CTest/cmCTestConfigureCommand.cxx
+++ b/Source/CTest/cmCTestConfigureCommand.cxx
@@ -16,7 +16,7 @@
cmCTestConfigureCommand::cmCTestConfigureCommand()
{
this->Arguments[ctc_OPTIONS] = "OPTIONS";
- this->Arguments[ctc_LAST] = CM_NULLPTR;
+ this->Arguments[ctc_LAST] = nullptr;
this->Last = ctc_LAST;
}
@@ -33,7 +33,7 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
"Build directory not specified. Either use BUILD "
"argument to CTEST_CONFIGURE command or set CTEST_BINARY_DIRECTORY "
"variable");
- return CM_NULLPTR;
+ return nullptr;
}
const char* ctestConfigureCommand =
@@ -53,7 +53,7 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
"Source directory not specified. Either use SOURCE "
"argument to CTEST_CONFIGURE command or set CTEST_SOURCE_DIRECTORY "
"variable");
- return CM_NULLPTR;
+ return nullptr;
}
const std::string cmakelists_file = source_dir + "/CMakeLists.txt";
@@ -61,7 +61,7 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
std::ostringstream e;
e << "CMakeLists.txt file does not exist [" << cmakelists_file << "]";
this->SetError(e.str());
- return CM_NULLPTR;
+ return nullptr;
}
bool multiConfig = false;
@@ -79,18 +79,13 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
cmakeConfigureCommand += cmSystemTools::GetCMakeCommand();
cmakeConfigureCommand += "\"";
- std::vector<std::string>::const_iterator it;
- std::string option;
- for (it = options.begin(); it != options.end(); ++it) {
- option = *it;
-
+ for (std::string const& option : options) {
cmakeConfigureCommand += " \"";
cmakeConfigureCommand += option;
cmakeConfigureCommand += "\"";
- if ((CM_NULLPTR != strstr(option.c_str(), "CMAKE_BUILD_TYPE=")) ||
- (CM_NULLPTR !=
- strstr(option.c_str(), "CMAKE_BUILD_TYPE:STRING="))) {
+ if ((nullptr != strstr(option.c_str(), "CMAKE_BUILD_TYPE=")) ||
+ (nullptr != strstr(option.c_str(), "CMAKE_BUILD_TYPE:STRING="))) {
cmakeBuildTypeInOptions = true;
}
}
@@ -137,16 +132,22 @@ cmCTestGenericHandler* cmCTestConfigureCommand::InitializeHandler()
"Configure command is not specified. If this is a "
"\"built with CMake\" project, set CTEST_CMAKE_GENERATOR. If not, "
"set CTEST_CONFIGURE_COMMAND.");
- return CM_NULLPTR;
+ return nullptr;
}
}
+ if (const char* labelsForSubprojects =
+ this->Makefile->GetDefinition("CTEST_LABELS_FOR_SUBPROJECTS")) {
+ this->CTest->SetCTestConfiguration("LabelsForSubprojects",
+ labelsForSubprojects, this->Quiet);
+ }
+
cmCTestGenericHandler* handler =
this->CTest->GetInitializedHandler("configure");
if (!handler) {
this->SetError(
"internal CTest error. Cannot instantiate configure handler");
- return CM_NULLPTR;
+ return nullptr;
}
handler->SetQuiet(this->Quiet);
return handler;
diff --git a/Source/CTest/cmCTestConfigureCommand.h b/Source/CTest/cmCTestConfigureCommand.h
index 917f5ab8b..0cbcbfaa8 100644
--- a/Source/CTest/cmCTestConfigureCommand.h
+++ b/Source/CTest/cmCTestConfigureCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestConfigureCommand_h
#define cmCTestConfigureCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestHandlerCommand.h"
@@ -25,7 +25,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestConfigureCommand* ni = new cmCTestConfigureCommand;
ni->CTest = this->CTest;
@@ -36,10 +36,10 @@ public:
/**
* The name of the command as specified in CMakeList.txt.
*/
- std::string GetName() const CM_OVERRIDE { return "ctest_configure"; }
+ std::string GetName() const override { return "ctest_configure"; }
protected:
- cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
+ cmCTestGenericHandler* InitializeHandler() override;
enum
{
diff --git a/Source/CTest/cmCTestConfigureHandler.cxx b/Source/CTest/cmCTestConfigureHandler.cxx
index 5d87f3fb4..56a038e38 100644
--- a/Source/CTest/cmCTestConfigureHandler.cxx
+++ b/Source/CTest/cmCTestConfigureHandler.cxx
@@ -73,6 +73,7 @@ int cmCTestConfigureHandler::ProcessHandler()
if (os) {
cmXMLWriter xml(os);
this->CTest->StartXML(xml, this->AppendXML);
+ this->CTest->GenerateSubprojectsOutput(xml);
xml.StartElement("Configure");
xml.Element("StartDateTime", start_time);
xml.Element("StartConfigureTime", start_time_time);
diff --git a/Source/CTest/cmCTestConfigureHandler.h b/Source/CTest/cmCTestConfigureHandler.h
index 2b452829c..680401c84 100644
--- a/Source/CTest/cmCTestConfigureHandler.h
+++ b/Source/CTest/cmCTestConfigureHandler.h
@@ -3,7 +3,7 @@
#ifndef cmCTestConfigureHandler_h
#define cmCTestConfigureHandler_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestGenericHandler.h"
@@ -19,11 +19,11 @@ public:
/*
* The main entry point for this class
*/
- int ProcessHandler() CM_OVERRIDE;
+ int ProcessHandler() override;
cmCTestConfigureHandler();
- void Initialize() CM_OVERRIDE;
+ void Initialize() override;
};
#endif
diff --git a/Source/CTest/cmCTestCoverageCommand.cxx b/Source/CTest/cmCTestCoverageCommand.cxx
index 535da586d..d2003baa3 100644
--- a/Source/CTest/cmCTestCoverageCommand.cxx
+++ b/Source/CTest/cmCTestCoverageCommand.cxx
@@ -23,7 +23,7 @@ cmCTestGenericHandler* cmCTestCoverageCommand::InitializeHandler()
this->CTest->GetInitializedHandler("coverage"));
if (!handler) {
this->SetError("internal CTest error. Cannot instantiate test handler");
- return CM_NULLPTR;
+ return nullptr;
}
// If a LABELS option was given, select only files with the labels.
diff --git a/Source/CTest/cmCTestCoverageCommand.h b/Source/CTest/cmCTestCoverageCommand.h
index 78c4f61f6..1ae2d869a 100644
--- a/Source/CTest/cmCTestCoverageCommand.h
+++ b/Source/CTest/cmCTestCoverageCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestCoverageCommand_h
#define cmCTestCoverageCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestHandlerCommand.h"
@@ -26,7 +26,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestCoverageCommand* ni = new cmCTestCoverageCommand;
ni->CTest = this->CTest;
@@ -37,15 +37,15 @@ public:
/**
* The name of the command as specified in CMakeList.txt.
*/
- std::string GetName() const CM_OVERRIDE { return "ctest_coverage"; }
+ std::string GetName() const override { return "ctest_coverage"; }
typedef cmCTestHandlerCommand Superclass;
protected:
- cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
+ cmCTestGenericHandler* InitializeHandler() override;
- bool CheckArgumentKeyword(std::string const& arg) CM_OVERRIDE;
- bool CheckArgumentValue(std::string const& arg) CM_OVERRIDE;
+ bool CheckArgumentKeyword(std::string const& arg) override;
+ bool CheckArgumentValue(std::string const& arg) override;
enum
{
diff --git a/Source/CTest/cmCTestCoverageHandler.cxx b/Source/CTest/cmCTestCoverageHandler.cxx
index 28fae1c7e..56eeceb0b 100644
--- a/Source/CTest/cmCTestCoverageHandler.cxx
+++ b/Source/CTest/cmCTestCoverageHandler.cxx
@@ -67,12 +67,10 @@ public:
bool StartProcess()
{
std::vector<const char*> args;
- for (std::vector<std::string>::iterator i =
- this->CommandLineStrings.begin();
- i != this->CommandLineStrings.end(); ++i) {
- args.push_back(i->c_str());
+ for (std::string const& cl : this->CommandLineStrings) {
+ args.push_back(cl.c_str());
}
- args.push_back(CM_NULLPTR); // null terminate
+ args.push_back(nullptr); // null terminate
cmsysProcess_SetCommand(this->Process, &*args.begin());
if (!this->WorkingDirectory.empty()) {
cmsysProcess_SetWorkingDirectory(this->Process,
@@ -97,7 +95,7 @@ public:
{
cmsysProcess_SetPipeFile(this->Process, cmsysProcess_Pipe_STDERR, fname);
}
- int WaitForExit(double* timeout = CM_NULLPTR)
+ int WaitForExit(double* timeout = nullptr)
{
this->PipeState = cmsysProcess_WaitForExit(this->Process, timeout);
return this->PipeState;
@@ -136,10 +134,9 @@ void cmCTestCoverageHandler::CleanCoverageLogFiles(std::ostream& log)
cmsys::Glob gl;
gl.FindFiles(logGlob);
std::vector<std::string> const& files = gl.GetFiles();
- for (std::vector<std::string>::const_iterator fi = files.begin();
- fi != files.end(); ++fi) {
- log << "Removing old coverage log: " << *fi << "\n";
- cmSystemTools::RemoveFile(*fi);
+ for (std::string const& f : files) {
+ log << "Removing old coverage log: " << f << "\n";
+ cmSystemTools::RemoveFile(f);
}
}
@@ -188,18 +185,16 @@ void cmCTestCoverageHandler::EndCoverageLogXML(cmXMLWriter& xml)
this->CTest->EndXML(xml);
}
-bool cmCTestCoverageHandler::ShouldIDoCoverage(const char* file,
- const char* srcDir,
- const char* binDir)
+bool cmCTestCoverageHandler::ShouldIDoCoverage(std::string const& file,
+ std::string const& srcDir,
+ std::string const& binDir)
{
if (this->IsFilteredOut(file)) {
return false;
}
- std::vector<cmsys::RegularExpression>::iterator sit;
- for (sit = this->CustomCoverageExcludeRegex.begin();
- sit != this->CustomCoverageExcludeRegex.end(); ++sit) {
- if (sit->find(file)) {
+ for (cmsys::RegularExpression& rx : this->CustomCoverageExcludeRegex) {
+ if (rx.find(file)) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " File "
<< file << " is excluded in CTestCustom.ctest"
<< std::endl;
@@ -319,11 +314,9 @@ int cmCTestCoverageHandler::ProcessHandler()
// setup the regex exclude stuff
this->CustomCoverageExcludeRegex.clear();
- std::vector<std::string>::iterator rexIt;
- for (rexIt = this->CustomCoverageExclude.begin();
- rexIt != this->CustomCoverageExclude.end(); ++rexIt) {
+ for (std::string const& rex : this->CustomCoverageExclude) {
this->CustomCoverageExcludeRegex.push_back(
- cmsys::RegularExpression(rexIt->c_str()));
+ cmsys::RegularExpression(rex.c_str()));
}
if (this->HandleBullseyeCoverage(&cont)) {
@@ -414,7 +407,6 @@ int cmCTestCoverageHandler::ProcessHandler()
return -1;
}
this->StartCoverageLogXML(covLogXML);
- cmCTestCoverageHandlerContainer::TotalCoverageMap::iterator fileIterator;
int cnt = 0;
long total_tested = 0;
long total_untested = 0;
@@ -430,8 +422,7 @@ int cmCTestCoverageHandler::ProcessHandler()
std::vector<std::string> errorsWhileAccumulating;
file_count = 0;
- for (fileIterator = cont.TotalCoverage.begin();
- fileIterator != cont.TotalCoverage.end(); ++fileIterator) {
+ for (auto const& file : cont.TotalCoverage) {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush,
this->Quiet);
file_count++;
@@ -443,9 +434,9 @@ int cmCTestCoverageHandler::ProcessHandler()
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " ", this->Quiet);
}
- const std::string fullFileName = fileIterator->first;
- bool shouldIDoCoverage = this->ShouldIDoCoverage(
- fullFileName.c_str(), sourceDir.c_str(), binaryDir.c_str());
+ const std::string fullFileName = file.first;
+ bool shouldIDoCoverage =
+ this->ShouldIDoCoverage(fullFileName, sourceDir, binaryDir);
if (!shouldIDoCoverage) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
".NoDartCoverage found, so skip coverage check for: "
@@ -478,7 +469,7 @@ int cmCTestCoverageHandler::ProcessHandler()
std::string shortFileName =
this->CTest->GetShortPathToFile(fullFileName.c_str());
const cmCTestCoverageHandlerContainer::SingleFileCoverageVector& fcov =
- fileIterator->second;
+ file.second;
covLogXML.StartElement("File");
covLogXML.Attribute("Name", fileName);
covLogXML.Attribute("FullPath", shortFileName);
@@ -554,14 +545,13 @@ int cmCTestCoverageHandler::ProcessHandler()
}
// Handle all the files in the extra coverage globs that have no cov data
- for (std::set<std::string>::iterator i = uncovered.begin();
- i != uncovered.end(); ++i) {
- std::string fileName = cmSystemTools::GetFilenameName(*i);
- std::string fullPath = cont.SourceDir + "/" + *i;
+ for (std::string const& u : uncovered) {
+ std::string fileName = cmSystemTools::GetFilenameName(u);
+ std::string fullPath = cont.SourceDir + "/" + u;
covLogXML.StartElement("File");
covLogXML.Attribute("Name", fileName);
- covLogXML.Attribute("FullPath", *i);
+ covLogXML.Attribute("FullPath", u);
covLogXML.StartElement("Report");
cmsys::ifstream ifs(fullPath.c_str());
@@ -577,7 +567,7 @@ int cmCTestCoverageHandler::ProcessHandler()
int untested = 0;
std::string line;
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
- "Actually performing coverage for: " << *i << std::endl,
+ "Actually performing coverage for: " << u << std::endl,
this->Quiet);
while (cmSystemTools::GetLineFromStream(ifs, line)) {
covLogXML.StartElement("Line");
@@ -593,13 +583,13 @@ int cmCTestCoverageHandler::ProcessHandler()
total_untested += untested;
covSumXML.StartElement("File");
covSumXML.Attribute("Name", fileName);
- covSumXML.Attribute("FullPath", *i);
+ covSumXML.Attribute("FullPath", u);
covSumXML.Attribute("Covered", "true");
covSumXML.Element("LOCTested", 0);
covSumXML.Element("LOCUnTested", untested);
covSumXML.Element("PercentCoverage", 0);
covSumXML.Element("CoverageMetric", 0);
- this->WriteXMLLabels(covSumXML, *i);
+ this->WriteXMLLabels(covSumXML, u);
covSumXML.EndElement(); // File
}
@@ -610,10 +600,8 @@ int cmCTestCoverageHandler::ProcessHandler()
cmCTestLog(this->CTest, ERROR_MESSAGE, std::endl);
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Error(s) while accumulating results:" << std::endl);
- std::vector<std::string>::iterator erIt;
- for (erIt = errorsWhileAccumulating.begin();
- erIt != errorsWhileAccumulating.end(); ++erIt) {
- cmCTestLog(this->CTest, ERROR_MESSAGE, " " << *erIt << std::endl);
+ for (std::string const& er : errorsWhileAccumulating) {
+ cmCTestLog(this->CTest, ERROR_MESSAGE, " " << er << std::endl);
}
}
@@ -670,17 +658,14 @@ void cmCTestCoverageHandler::PopulateCustomVectors(cmMakefile* mf)
this->CustomCoverageExclude);
this->CTest->PopulateCustomVector(mf, "CTEST_EXTRA_COVERAGE_GLOB",
this->ExtraCoverageGlobs);
- std::vector<std::string>::iterator it;
- for (it = this->CustomCoverageExclude.begin();
- it != this->CustomCoverageExclude.end(); ++it) {
+ for (std::string const& cce : this->CustomCoverageExclude) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
- " Add coverage exclude: " << *it << std::endl,
+ " Add coverage exclude: " << cce << std::endl,
this->Quiet);
}
- for (it = this->ExtraCoverageGlobs.begin();
- it != this->ExtraCoverageGlobs.end(); ++it) {
+ for (std::string const& ecg : this->ExtraCoverageGlobs) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
- " Add coverage glob: " << *it << std::endl,
+ " Add coverage glob: " << ecg << std::endl,
this->Quiet);
}
}
@@ -877,6 +862,24 @@ int cmCTestCoverageHandler::HandleDelphiCoverage(
return static_cast<int>(cont->TotalCoverage.size());
}
+static std::string joinCommandLine(const std::vector<std::string>& args)
+{
+ std::string ret;
+
+ for (std::string const& s : args) {
+ if (s.find(' ') == std::string::npos) {
+ ret += s + ' ';
+ } else {
+ ret += "\"" + s + "\" ";
+ }
+ }
+
+ // drop trailing whitespace
+ ret.erase(ret.size() - 1);
+
+ return ret;
+}
+
int cmCTestCoverageHandler::HandleBlanketJSCoverage(
cmCTestCoverageHandlerContainer* cont)
{
@@ -895,12 +898,12 @@ int cmCTestCoverageHandler::HandleBlanketJSCoverage(
// Blanket.js output. Check for the "node-jscoverage"
// string on the second line
std::string line;
- for (unsigned int fileEntry = 0; fileEntry < files.size(); fileEntry++) {
- cmsys::ifstream in(files[fileEntry].c_str());
+ for (std::string const& fileEntry : files) {
+ cmsys::ifstream in(fileEntry.c_str());
cmSystemTools::GetLineFromStream(in, line);
cmSystemTools::GetLineFromStream(in, line);
if (line.find("node-jscoverage") != std::string::npos) {
- blanketFiles.push_back(files[fileEntry]);
+ blanketFiles.push_back(fileEntry);
}
}
// Take all files with the node-jscoverage string and parse those
@@ -961,7 +964,6 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
std::vector<std::string> files;
this->FindGCovFiles(files);
- std::vector<std::string>::iterator it;
if (files.empty()) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
@@ -992,19 +994,26 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
cmCTestCoverageHandlerLocale locale_C;
static_cast<void>(locale_C);
+ std::vector<std::string> basecovargs =
+ cmSystemTools::ParseArguments(gcovExtraFlags.c_str());
+ basecovargs.insert(basecovargs.begin(), gcovCommand);
+ basecovargs.push_back("-o");
+
// files is a list of *.da and *.gcda files with coverage data in them.
// These are binary files that you give as input to gcov so that it will
// give us text output we can analyze to summarize coverage.
//
- for (it = files.begin(); it != files.end(); ++it) {
+ for (std::string const& f : files) {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush,
this->Quiet);
// Call gcov to get coverage data for this *.gcda file:
//
- std::string fileDir = cmSystemTools::GetFilenamePath(*it);
- std::string command = "\"" + gcovCommand + "\" " + gcovExtraFlags + " " +
- "-o \"" + fileDir + "\" " + "\"" + *it + "\"";
+ std::string fileDir = cmSystemTools::GetFilenamePath(f);
+ std::vector<std::string> covargs = basecovargs;
+ covargs.push_back(fileDir);
+ covargs.push_back(f);
+ const std::string command = joinCommandLine(covargs);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
command << std::endl, this->Quiet);
@@ -1014,15 +1023,14 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
int retVal = 0;
*cont->OFS << "* Run coverage for: " << fileDir << std::endl;
*cont->OFS << " Command: " << command << std::endl;
- int res =
- this->CTest->RunCommand(command.c_str(), &output, &errors, &retVal,
- tempDir.c_str(), 0 /*this->TimeOut*/);
+ int res = this->CTest->RunCommand(covargs, &output, &errors, &retVal,
+ tempDir.c_str(), 0 /*this->TimeOut*/);
*cont->OFS << " Output: " << output << std::endl;
*cont->OFS << " Errors: " << errors << std::endl;
if (!res) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
- "Problem running coverage on file: " << *it << std::endl);
+ "Problem running coverage on file: " << f << std::endl);
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Command produced error: " << errors << std::endl);
cont->Error++;
@@ -1030,7 +1038,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
}
if (retVal != 0) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Coverage command returned: "
- << retVal << " while processing: " << *it << std::endl);
+ << retVal << " while processing: " << f << std::endl);
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Command produced error: " << cont->Error << std::endl);
}
@@ -1044,20 +1052,19 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
this->Quiet);
std::vector<std::string> lines;
- std::vector<std::string>::iterator line;
cmSystemTools::Split(output.c_str(), lines);
- for (line = lines.begin(); line != lines.end(); ++line) {
+ for (std::string const& line : lines) {
std::string sourceFile;
std::string gcovFile;
cmCTestOptionalLog(this->CTest, DEBUG,
- "Line: [" << *line << "]" << std::endl, this->Quiet);
+ "Line: [" << line << "]" << std::endl, this->Quiet);
- if (line->empty()) {
+ if (line.empty()) {
// Ignore empty line; probably style 2
- } else if (st1re1.find(line->c_str())) {
+ } else if (st1re1.find(line.c_str())) {
if (gcovStyle == 0) {
gcovStyle = 1;
}
@@ -1068,9 +1075,9 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
break;
}
- actualSourceFile = "";
+ actualSourceFile.clear();
sourceFile = st1re1.match(2);
- } else if (st1re2.find(line->c_str())) {
+ } else if (st1re2.find(line.c_str())) {
if (gcovStyle == 0) {
gcovStyle = 1;
}
@@ -1082,7 +1089,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
}
gcovFile = st1re2.match(1);
- } else if (st2re1.find(line->c_str())) {
+ } else if (st2re1.find(line.c_str())) {
if (gcovStyle == 0) {
gcovStyle = 2;
}
@@ -1093,9 +1100,9 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
break;
}
- actualSourceFile = "";
+ actualSourceFile.clear();
sourceFile = st2re1.match(1);
- } else if (st2re2.find(line->c_str())) {
+ } else if (st2re2.find(line.c_str())) {
if (gcovStyle == 0) {
gcovStyle = 2;
}
@@ -1105,7 +1112,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
cont->Error++;
break;
}
- } else if (st2re3.find(line->c_str())) {
+ } else if (st2re3.find(line.c_str())) {
if (gcovStyle == 0) {
gcovStyle = 2;
}
@@ -1117,7 +1124,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
}
gcovFile = st2re3.match(2);
- } else if (st2re4.find(line->c_str())) {
+ } else if (st2re4.find(line.c_str())) {
if (gcovStyle == 0) {
gcovStyle = 2;
}
@@ -1132,7 +1139,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
"Warning: " << st2re4.match(1)
<< " had unexpected EOF" << std::endl,
this->Quiet);
- } else if (st2re5.find(line->c_str())) {
+ } else if (st2re5.find(line.c_str())) {
if (gcovStyle == 0) {
gcovStyle = 2;
}
@@ -1146,7 +1153,7 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
cmCTestOptionalLog(this->CTest, WARNING, "Warning: Cannot open file: "
<< st2re5.match(1) << std::endl,
this->Quiet);
- } else if (st2re6.find(line->c_str())) {
+ } else if (st2re6.find(line.c_str())) {
if (gcovStyle == 0) {
gcovStyle = 2;
}
@@ -1164,10 +1171,10 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
} else {
// gcov 4.7 can have output lines saying "No executable lines" and
// "Removing 'filename.gcov'"... Don't log those as "errors."
- if (*line != "No executable lines" &&
- !cmSystemTools::StringStartsWith(line->c_str(), "Removing ")) {
+ if (line != "No executable lines" &&
+ !cmSystemTools::StringStartsWith(line.c_str(), "Removing ")) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Unknown gcov output line: ["
- << *line << "]" << std::endl);
+ << line << "]" << std::endl);
cont->Error++;
// abort();
}
@@ -1235,11 +1242,11 @@ int cmCTestCoverageHandler::HandleGCovCoverage(
}
}
- actualSourceFile = "";
+ actualSourceFile.clear();
}
if (!sourceFile.empty() && actualSourceFile.empty()) {
- gcovFile = "";
+ gcovFile.clear();
// Is it in the source dir or the binary dir?
//
@@ -1332,7 +1339,6 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
"Error while finding LCov files.\n");
return 0;
}
- std::vector<std::string>::iterator it;
if (files.empty()) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
@@ -1357,14 +1363,18 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
cmCTestCoverageHandlerLocale locale_C;
static_cast<void>(locale_C);
+ std::vector<std::string> covargs =
+ cmSystemTools::ParseArguments(lcovExtraFlags.c_str());
+ covargs.insert(covargs.begin(), lcovCommand);
+ const std::string command = joinCommandLine(covargs);
+
// In intel compiler we have to call codecov only once in each executable
// directory. It collects all *.dyn files to generate .dpi file.
- for (it = files.begin(); it != files.end(); ++it) {
+ for (std::string const& f : files) {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "." << std::flush,
this->Quiet);
- std::string fileDir = cmSystemTools::GetFilenamePath(*it);
+ std::string fileDir = cmSystemTools::GetFilenamePath(f);
cmWorkingDirectory workdir(fileDir);
- std::string command = "\"" + lcovCommand + "\" " + lcovExtraFlags + " ";
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Current coverage dir: " << fileDir << std::endl,
@@ -1377,15 +1387,14 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
int retVal = 0;
*cont->OFS << "* Run coverage for: " << fileDir << std::endl;
*cont->OFS << " Command: " << command << std::endl;
- int res =
- this->CTest->RunCommand(command.c_str(), &output, &errors, &retVal,
- fileDir.c_str(), 0 /*this->TimeOut*/);
+ int res = this->CTest->RunCommand(covargs, &output, &errors, &retVal,
+ fileDir.c_str(), 0 /*this->TimeOut*/);
*cont->OFS << " Output: " << output << std::endl;
*cont->OFS << " Errors: " << errors << std::endl;
if (!res) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
- "Problem running coverage on file: " << *it << std::endl);
+ "Problem running coverage on file: " << f << std::endl);
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Command produced error: " << errors << std::endl);
cont->Error++;
@@ -1393,7 +1402,7 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
}
if (retVal != 0) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Coverage command returned: "
- << retVal << " while processing: " << *it << std::endl);
+ << retVal << " while processing: " << f << std::endl);
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Command produced error: " << cont->Error << std::endl);
}
@@ -1407,15 +1416,14 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
this->Quiet);
std::vector<std::string> lines;
- std::vector<std::string>::iterator line;
cmSystemTools::Split(output.c_str(), lines);
- for (line = lines.begin(); line != lines.end(); ++line) {
+ for (std::string const& line : lines) {
std::string sourceFile;
std::string lcovFile;
- if (line->empty()) {
+ if (line.empty()) {
// Ignore empty line
}
// Look for LCOV files in binary directory
@@ -1438,9 +1446,8 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
lcovFiles.insert(lcovFiles.end(), gl.GetFiles().begin(),
gl.GetFiles().end());
- for (std::vector<std::string>::iterator a = lcovFiles.begin();
- a != lcovFiles.end(); ++a) {
- lcovFile = *a;
+ for (std::string const& file : lcovFiles) {
+ lcovFile = file;
cmsys::ifstream srcead(lcovFile.c_str());
if (!srcead) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
@@ -1462,10 +1469,9 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
sourceFile = srcname;
actualSourceFile = srcname;
- for (std::vector<std::string>::iterator t = lcovFiles.begin();
- t != lcovFiles.end(); ++t) {
+ for (std::string const& t : lcovFiles) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
- "Found LCOV File: " << *t << std::endl,
+ "Found LCOV File: " << t << std::endl,
this->Quiet);
}
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
@@ -1537,7 +1543,7 @@ int cmCTestCoverageHandler::HandleLCovCoverage(
}
}
- actualSourceFile = "";
+ actualSourceFile.clear();
}
}
}
@@ -1562,10 +1568,9 @@ void cmCTestCoverageHandler::FindGCovFiles(std::vector<std::string>& files)
gl.RecurseOn();
gl.RecurseThroughSymlinksOff();
- for (LabelMapType::const_iterator lmi = this->TargetDirs.begin();
- lmi != this->TargetDirs.end(); ++lmi) {
+ for (auto const& lm : this->TargetDirs) {
// Skip targets containing no interesting labels.
- if (!this->IntersectsFilter(lmi->second)) {
+ if (!this->IntersectsFilter(lm.second)) {
continue;
}
@@ -1573,12 +1578,12 @@ void cmCTestCoverageHandler::FindGCovFiles(std::vector<std::string>& files)
// support directory.
cmCTestOptionalLog(
this->CTest, HANDLER_VERBOSE_OUTPUT,
- " globbing for coverage in: " << lmi->first << std::endl, this->Quiet);
- std::string daGlob = lmi->first;
+ " globbing for coverage in: " << lm.first << std::endl, this->Quiet);
+ std::string daGlob = lm.first;
daGlob += "/*.da";
gl.FindFiles(daGlob);
files.insert(files.end(), gl.GetFiles().begin(), gl.GetFiles().end());
- daGlob = lmi->first;
+ daGlob = lm.first;
daGlob += "/*.gcda";
gl.FindFiles(daGlob);
files.insert(files.end(), gl.GetFiles().begin(), gl.GetFiles().end());
@@ -1641,14 +1646,13 @@ int cmCTestCoverageHandler::HandleTracePyCoverage(
std::string tempDir = testingDir + "/CoverageInfo";
cmSystemTools::MakeDirectory(tempDir.c_str());
- std::vector<std::string>::iterator fileIt;
int file_count = 0;
- for (fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
- std::string fileName = this->FindFile(cont, *fileIt);
+ for (std::string const& file : files) {
+ std::string fileName = this->FindFile(cont, file);
if (fileName.empty()) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Cannot find source Python file corresponding to: "
- << *fileIt << std::endl);
+ << file << std::endl);
continue;
}
@@ -1660,11 +1664,11 @@ int cmCTestCoverageHandler::HandleTracePyCoverage(
cmCTestCoverageHandlerContainer::SingleFileCoverageVector* vec =
&cont->TotalCoverage[actualSourceFile];
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
- " in file: " << *fileIt << std::endl, this->Quiet);
- cmsys::ifstream ifile(fileIt->c_str());
+ " in file: " << file << std::endl, this->Quiet);
+ cmsys::ifstream ifile(file.c_str());
if (!ifile) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
- "Cannot open file: " << *fileIt << std::endl);
+ "Cannot open file: " << file << std::endl);
} else {
long cnt = -1;
std::string nl;
@@ -1761,7 +1765,7 @@ const char* bullseyeHelp[] = {
" condition evaluated true or false, respectively.",
" * A k indicates a constant decision or condition.",
" * The slash / means this probe is excluded from summary results. ",
- CM_NULLPTR
+ nullptr
};
}
@@ -1789,7 +1793,7 @@ int cmCTestCoverageHandler::RunBullseyeCoverageBranch(
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"run covbr: " << std::endl, this->Quiet);
- if (!this->RunBullseyeCommand(cont, "covbr", CM_NULLPTR, outputFile)) {
+ if (!this->RunBullseyeCommand(cont, "covbr", nullptr, outputFile)) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "error running covbr for."
<< "\n");
return -1;
@@ -1862,7 +1866,7 @@ int cmCTestCoverageHandler::RunBullseyeCoverageBranch(
covLogXML.StartElement("Report");
// write the bullseye header
line = 0;
- for (int k = 0; bullseyeHelp[k] != CM_NULLPTR; ++k) {
+ for (int k = 0; bullseyeHelp[k] != nullptr; ++k) {
covLogXML.StartElement("Line");
covLogXML.Attribute("Number", line);
covLogXML.Attribute("Count", -1);
@@ -2014,8 +2018,8 @@ int cmCTestCoverageHandler::RunBullseyeSourceSummary(
file += sourceFile;
}
file = cmSystemTools::CollapseFullPath(file);
- bool shouldIDoCoverage = this->ShouldIDoCoverage(
- file.c_str(), cont->SourceDir.c_str(), cont->BinaryDir.c_str());
+ bool shouldIDoCoverage =
+ this->ShouldIDoCoverage(file, cont->SourceDir, cont->BinaryDir);
if (!shouldIDoCoverage) {
cmCTestOptionalLog(
this->CTest, HANDLER_VERBOSE_OUTPUT,
@@ -2256,9 +2260,8 @@ void cmCTestCoverageHandler::WriteXMLLabels(cmXMLWriter& xml,
LabelMapType::const_iterator li = this->SourceLabels.find(source);
if (li != this->SourceLabels.end() && !li->second.empty()) {
xml.StartElement("Labels");
- for (LabelSet::const_iterator lsi = li->second.begin();
- lsi != li->second.end(); ++lsi) {
- xml.Element("Label", this->Labels[*lsi]);
+ for (auto const& ls : li->second) {
+ xml.Element("Label", this->Labels[ls]);
}
xml.EndElement(); // Labels
}
@@ -2268,9 +2271,8 @@ void cmCTestCoverageHandler::SetLabelFilter(
std::set<std::string> const& labels)
{
this->LabelFilter.clear();
- for (std::set<std::string>::const_iterator li = labels.begin();
- li != labels.end(); ++li) {
- this->LabelFilter.insert(this->GetLabelId(*li));
+ for (std::string const& l : labels) {
+ this->LabelFilter.insert(this->GetLabelId(l));
}
}
@@ -2310,29 +2312,23 @@ std::set<std::string> cmCTestCoverageHandler::FindUncoveredFiles(
{
std::set<std::string> extraMatches;
- for (std::vector<std::string>::iterator i = this->ExtraCoverageGlobs.begin();
- i != this->ExtraCoverageGlobs.end(); ++i) {
+ for (std::string const& ecg : this->ExtraCoverageGlobs) {
cmsys::Glob gl;
gl.RecurseOn();
gl.RecurseThroughSymlinksOff();
- std::string glob = cont->SourceDir + "/" + *i;
+ std::string glob = cont->SourceDir + "/" + ecg;
gl.FindFiles(glob);
std::vector<std::string> files = gl.GetFiles();
- for (std::vector<std::string>::iterator f = files.begin();
- f != files.end(); ++f) {
- if (this->ShouldIDoCoverage(f->c_str(), cont->SourceDir.c_str(),
- cont->BinaryDir.c_str())) {
- extraMatches.insert(this->CTest->GetShortPathToFile(f->c_str()));
+ for (std::string const& f : files) {
+ if (this->ShouldIDoCoverage(f, cont->SourceDir, cont->BinaryDir)) {
+ extraMatches.insert(this->CTest->GetShortPathToFile(f.c_str()));
}
}
}
if (!extraMatches.empty()) {
- for (cmCTestCoverageHandlerContainer::TotalCoverageMap::iterator i =
- cont->TotalCoverage.begin();
- i != cont->TotalCoverage.end(); ++i) {
- std::string shortPath =
- this->CTest->GetShortPathToFile(i->first.c_str());
+ for (auto const& i : cont->TotalCoverage) {
+ std::string shortPath = this->CTest->GetShortPathToFile(i.first.c_str());
extraMatches.erase(shortPath);
}
}
diff --git a/Source/CTest/cmCTestCoverageHandler.h b/Source/CTest/cmCTestCoverageHandler.h
index 933f60660..6492fe951 100644
--- a/Source/CTest/cmCTestCoverageHandler.h
+++ b/Source/CTest/cmCTestCoverageHandler.h
@@ -3,7 +3,7 @@
#ifndef cmCTestCoverageHandler_h
#define cmCTestCoverageHandler_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestGenericHandler.h"
@@ -42,23 +42,23 @@ public:
/*
* The main entry point for this class
*/
- int ProcessHandler() CM_OVERRIDE;
+ int ProcessHandler() override;
cmCTestCoverageHandler();
- void Initialize() CM_OVERRIDE;
+ void Initialize() override;
/**
* This method is called when reading CTest custom file
*/
- void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE;
+ void PopulateCustomVectors(cmMakefile* mf) override;
/** Report coverage only for sources with these labels. */
void SetLabelFilter(std::set<std::string> const& labels);
private:
- bool ShouldIDoCoverage(const char* file, const char* srcDir,
- const char* binDir);
+ bool ShouldIDoCoverage(std::string const& file, std::string const& srcDir,
+ std::string const& binDir);
void CleanCoverageLogFiles(std::ostream& log);
bool StartCoverageLogFile(cmGeneratedFileStream& ostr, int logFileCount);
void EndCoverageLogFile(cmGeneratedFileStream& ostr, int logFileCount);
diff --git a/Source/CTest/cmCTestCurl.cxx b/Source/CTest/cmCTestCurl.cxx
index b80ea5ade..7b5ea6005 100644
--- a/Source/CTest/cmCTestCurl.cxx
+++ b/Source/CTest/cmCTestCurl.cxx
@@ -5,7 +5,6 @@
#include "cmCTest.h"
#include "cmSystemTools.h"
-#include "cmConfigure.h"
#include <ostream>
#include <stdio.h>
@@ -42,7 +41,7 @@ namespace {
size_t curlWriteMemoryCallback(void* ptr, size_t size, size_t nmemb,
void* data)
{
- int realsize = (int)(size * nmemb);
+ int realsize = static_cast<int>(size * nmemb);
std::vector<char>* vec = static_cast<std::vector<char>*>(data);
const char* chPtr = static_cast<char*>(ptr);
@@ -62,12 +61,11 @@ size_t curlDebugCallback(CURL* /*unused*/, curl_infotype /*unused*/,
void cmCTestCurl::SetCurlOptions(std::vector<std::string> const& args)
{
- for (std::vector<std::string>::const_iterator i = args.begin();
- i != args.end(); ++i) {
- if (*i == "CURLOPT_SSL_VERIFYPEER_OFF") {
+ for (std::string const& arg : args) {
+ if (arg == "CURLOPT_SSL_VERIFYPEER_OFF") {
this->VerifyPeerOff = true;
}
- if (*i == "CURLOPT_SSL_VERIFYHOST_OFF") {
+ if (arg == "CURLOPT_SSL_VERIFYHOST_OFF") {
this->VerifyHostOff = true;
}
}
@@ -111,7 +109,7 @@ bool cmCTestCurl::UploadFile(std::string const& local_file,
std::string const& url, std::string const& fields,
std::string& response)
{
- response = "";
+ response.clear();
if (!this->InitCurl()) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Initialization of curl failed");
return false;
@@ -145,20 +143,19 @@ bool cmCTestCurl::UploadFile(std::string const& local_file,
::curl_easy_setopt(this->Curl, CURLOPT_DEBUGFUNCTION, curlDebugCallback);
// Set Content-Type to satisfy fussy modsecurity rules.
struct curl_slist* headers =
- ::curl_slist_append(CM_NULLPTR, "Content-Type: text/xml");
+ ::curl_slist_append(nullptr, "Content-Type: text/xml");
// Add any additional headers that the user specified.
- for (std::vector<std::string>::const_iterator h = this->HttpHeaders.begin();
- h != this->HttpHeaders.end(); ++h) {
+ for (std::string const& h : this->HttpHeaders) {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
- " Add HTTP Header: \"" << *h << "\"" << std::endl,
+ " Add HTTP Header: \"" << h << "\"" << std::endl,
this->Quiet);
- headers = ::curl_slist_append(headers, h->c_str());
+ headers = ::curl_slist_append(headers, h.c_str());
}
::curl_easy_setopt(this->Curl, CURLOPT_HTTPHEADER, headers);
std::vector<char> responseData;
std::vector<char> debugData;
- ::curl_easy_setopt(this->Curl, CURLOPT_FILE, (void*)&responseData);
- ::curl_easy_setopt(this->Curl, CURLOPT_DEBUGDATA, (void*)&debugData);
+ ::curl_easy_setopt(this->Curl, CURLOPT_FILE, &responseData);
+ ::curl_easy_setopt(this->Curl, CURLOPT_DEBUGDATA, &debugData);
::curl_easy_setopt(this->Curl, CURLOPT_FAILONERROR, 1);
// Now run off and do what you've been told!
::curl_easy_perform(this->Curl);
@@ -188,7 +185,7 @@ bool cmCTestCurl::UploadFile(std::string const& local_file,
bool cmCTestCurl::HttpRequest(std::string const& url,
std::string const& fields, std::string& response)
{
- response = "";
+ response.clear();
cmCTestOptionalLog(this->CTest, DEBUG, "HttpRequest\n"
<< "url: " << url << "\n"
<< "fields " << fields << "\n",
@@ -207,20 +204,18 @@ bool cmCTestCurl::HttpRequest(std::string const& url,
::curl_easy_setopt(this->Curl, CURLOPT_DEBUGFUNCTION, curlDebugCallback);
std::vector<char> responseData;
std::vector<char> debugData;
- ::curl_easy_setopt(this->Curl, CURLOPT_FILE, (void*)&responseData);
- ::curl_easy_setopt(this->Curl, CURLOPT_DEBUGDATA, (void*)&debugData);
+ ::curl_easy_setopt(this->Curl, CURLOPT_FILE, &responseData);
+ ::curl_easy_setopt(this->Curl, CURLOPT_DEBUGDATA, &debugData);
::curl_easy_setopt(this->Curl, CURLOPT_FAILONERROR, 1);
// Add headers if any were specified.
- struct curl_slist* headers = CM_NULLPTR;
+ struct curl_slist* headers = nullptr;
if (!this->HttpHeaders.empty()) {
- for (std::vector<std::string>::const_iterator h =
- this->HttpHeaders.begin();
- h != this->HttpHeaders.end(); ++h) {
+ for (std::string const& h : this->HttpHeaders) {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
- " Add HTTP Header: \"" << *h << "\"" << std::endl,
+ " Add HTTP Header: \"" << h << "\"" << std::endl,
this->Quiet);
- headers = ::curl_slist_append(headers, h->c_str());
+ headers = ::curl_slist_append(headers, h.c_str());
}
}
@@ -245,10 +240,10 @@ bool cmCTestCurl::HttpRequest(std::string const& url,
void cmCTestCurl::SetProxyType()
{
- this->HTTPProxy = "";
+ this->HTTPProxy.clear();
// this is the default
this->HTTPProxyType = CURLPROXY_HTTP;
- this->HTTPProxyAuth = "";
+ this->HTTPProxyAuth.clear();
if (cmSystemTools::GetEnv("HTTP_PROXY", this->HTTPProxy)) {
std::string port;
if (cmSystemTools::GetEnv("HTTP_PROXY_PORT", port)) {
diff --git a/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h b/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h
index 503ed234d..9425ece95 100644
--- a/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h
+++ b/Source/CTest/cmCTestEmptyBinaryDirectoryCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestEmptyBinaryDirectoryCommand_h
#define cmCTestEmptyBinaryDirectoryCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestCommand.h"
@@ -27,7 +27,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestEmptyBinaryDirectoryCommand* ni =
new cmCTestEmptyBinaryDirectoryCommand;
@@ -41,7 +41,7 @@ public:
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/CTest/cmCTestGIT.cxx b/Source/CTest/cmCTestGIT.cxx
index 230aedf3b..8cb795e22 100644
--- a/Source/CTest/cmCTestGIT.cxx
+++ b/Source/CTest/cmCTestGIT.cxx
@@ -46,7 +46,7 @@ public:
private:
std::string& Line1;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
// Only the first line is of interest.
this->Line1 = this->Line;
@@ -58,8 +58,8 @@ std::string cmCTestGIT::GetWorkingRevision()
{
// Run plumbing "git rev-list" to get work tree revision.
const char* git = this->CommandLineTool.c_str();
- const char* git_rev_list[] = { git, "rev-list", "-n", "1",
- "HEAD", "--", CM_NULLPTR };
+ const char* git_rev_list[] = { git, "rev-list", "-n", "1",
+ "HEAD", "--", nullptr };
std::string rev;
OneLineParser out(this, "rl-out> ", rev);
OutputLogger err(this->Log, "rl-err> ");
@@ -90,11 +90,11 @@ std::string cmCTestGIT::FindGitDir()
// Run "git rev-parse --git-dir" to locate the real .git directory.
const char* git = this->CommandLineTool.c_str();
- char const* git_rev_parse[] = { git, "rev-parse", "--git-dir", CM_NULLPTR };
+ char const* git_rev_parse[] = { git, "rev-parse", "--git-dir", nullptr };
std::string git_dir_line;
OneLineParser rev_parse_out(this, "rev-parse-out> ", git_dir_line);
OutputLogger rev_parse_err(this->Log, "rev-parse-err> ");
- if (this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err, CM_NULLPTR,
+ if (this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err, nullptr,
cmProcessOutput::UTF8)) {
git_dir = git_dir_line;
}
@@ -118,7 +118,7 @@ std::string cmCTestGIT::FindGitDir()
0 };
OneLineParser cygpath_out(this, "cygpath-out> ", git_dir_line);
OutputLogger cygpath_err(this->Log, "cygpath-err> ");
- if (this->RunChild(cygpath, &cygpath_out, &cygpath_err, CM_NULLPTR,
+ if (this->RunChild(cygpath, &cygpath_out, &cygpath_err, nullptr,
cmProcessOutput::UTF8)) {
git_dir = git_dir_line;
}
@@ -134,12 +134,11 @@ std::string cmCTestGIT::FindTopDir()
// Run "git rev-parse --show-cdup" to locate the top of the tree.
const char* git = this->CommandLineTool.c_str();
- char const* git_rev_parse[] = { git, "rev-parse", "--show-cdup",
- CM_NULLPTR };
+ char const* git_rev_parse[] = { git, "rev-parse", "--show-cdup", nullptr };
std::string cdup;
OneLineParser rev_parse_out(this, "rev-parse-out> ", cdup);
OutputLogger rev_parse_err(this->Log, "rev-parse-err> ");
- if (this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err, CM_NULLPTR,
+ if (this->RunChild(git_rev_parse, &rev_parse_out, &rev_parse_err, nullptr,
cmProcessOutput::UTF8) &&
!cdup.empty()) {
top_dir += "/";
@@ -164,13 +163,12 @@ bool cmCTestGIT::UpdateByFetchAndReset()
opts = this->CTest->GetCTestConfiguration("GITUpdateOptions");
}
std::vector<std::string> args = cmSystemTools::ParseArguments(opts.c_str());
- for (std::vector<std::string>::const_iterator ai = args.begin();
- ai != args.end(); ++ai) {
- git_fetch.push_back(ai->c_str());
+ for (std::string const& arg : args) {
+ git_fetch.push_back(arg.c_str());
}
// Sentinel argument.
- git_fetch.push_back(CM_NULLPTR);
+ git_fetch.push_back(nullptr);
// Fetch upstream refs.
OutputLogger fetch_out(this->Log, "fetch-out> ");
@@ -205,8 +203,7 @@ bool cmCTestGIT::UpdateByFetchAndReset()
}
// Reset the local branch to point at that tracked from upstream.
- char const* git_reset[] = { git, "reset", "--hard", sha1.c_str(),
- CM_NULLPTR };
+ char const* git_reset[] = { git, "reset", "--hard", sha1.c_str(), nullptr };
OutputLogger reset_out(this->Log, "reset-out> ");
OutputLogger reset_err(this->Log, "reset-err> ");
return this->RunChild(&git_reset[0], &reset_out, &reset_err);
@@ -217,11 +214,11 @@ bool cmCTestGIT::UpdateByCustom(std::string const& custom)
std::vector<std::string> git_custom_command;
cmSystemTools::ExpandListArgument(custom, git_custom_command, true);
std::vector<char const*> git_custom;
- for (std::vector<std::string>::const_iterator i = git_custom_command.begin();
- i != git_custom_command.end(); ++i) {
- git_custom.push_back(i->c_str());
+ git_custom.reserve(git_custom_command.size() + 1);
+ for (std::string const& i : git_custom_command) {
+ git_custom.push_back(i.c_str());
}
- git_custom.push_back(CM_NULLPTR);
+ git_custom.push_back(nullptr);
OutputLogger custom_out(this->Log, "custom-out> ");
OutputLogger custom_err(this->Log, "custom-err> ");
@@ -250,7 +247,7 @@ bool cmCTestGIT::UpdateImpl()
// Git < 1.6.5 did not support submodule --recursive
if (this->GetGitVersion() < cmCTestGITVersion(1, 6, 5, 0)) {
- recursive = CM_NULLPTR;
+ recursive = nullptr;
// No need to require >= 1.6.5 if there are no submodules.
if (cmSystemTools::FileExists((top_dir + "/.gitmodules").c_str())) {
this->Log << "Git < 1.6.5 cannot update submodules recursively\n";
@@ -259,7 +256,7 @@ bool cmCTestGIT::UpdateImpl()
// Git < 1.8.1 did not support sync --recursive
if (this->GetGitVersion() < cmCTestGITVersion(1, 8, 1, 0)) {
- sync_recursive = CM_NULLPTR;
+ sync_recursive = nullptr;
// No need to require >= 1.8.1 if there are no submodules.
if (cmSystemTools::FileExists((top_dir + "/.gitmodules").c_str())) {
this->Log << "Git < 1.8.1 cannot synchronize submodules recursively\n";
@@ -274,8 +271,7 @@ bool cmCTestGIT::UpdateImpl()
std::string init_submodules =
this->CTest->GetCTestConfiguration("GITInitSubmodules");
if (cmSystemTools::IsOn(init_submodules.c_str())) {
- char const* git_submodule_init[] = { git, "submodule", "init",
- CM_NULLPTR };
+ char const* git_submodule_init[] = { git, "submodule", "init", nullptr };
ret = this->RunChild(git_submodule_init, &submodule_out, &submodule_err,
top_dir.c_str());
@@ -285,7 +281,7 @@ bool cmCTestGIT::UpdateImpl()
}
char const* git_submodule_sync[] = { git, "submodule", "sync",
- sync_recursive, CM_NULLPTR };
+ sync_recursive, nullptr };
ret = this->RunChild(git_submodule_sync, &submodule_out, &submodule_err,
top_dir.c_str());
@@ -294,7 +290,7 @@ bool cmCTestGIT::UpdateImpl()
}
char const* git_submodule[] = { git, "submodule", "update", recursive,
- CM_NULLPTR };
+ nullptr };
return this->RunChild(git_submodule, &submodule_out, &submodule_err,
top_dir.c_str());
}
@@ -303,7 +299,7 @@ unsigned int cmCTestGIT::GetGitVersion()
{
if (!this->CurrentGitVersion) {
const char* git = this->CommandLineTool.c_str();
- char const* git_version[] = { git, "--version", CM_NULLPTR };
+ char const* git_version[] = { git, "--version", nullptr };
std::string version;
OneLineParser version_out(this, "version-out> ", version);
OutputLogger version_err(this->Log, "version-err> ");
@@ -359,7 +355,7 @@ protected:
this->Changes.clear();
}
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->Line[0] == ':') {
this->DiffField = DiffFieldChange;
@@ -513,11 +509,11 @@ private:
const char* email_last = *c ? c++ : c;
person.EMail.assign(email_first, email_last - email_first);
- person.Time = strtoul(c, (char**)&c, 10);
- person.TimeZone = strtol(c, (char**)&c, 10);
+ person.Time = strtoul(c, const_cast<char**>(&c), 10);
+ person.TimeZone = strtol(c, const_cast<char**>(&c), 10);
}
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->Line.empty()) {
if (this->Section == SectionBody && this->LineEnd == '\0') {
@@ -615,10 +611,10 @@ bool cmCTestGIT::LoadRevisions()
std::string range = this->OldRevision + ".." + this->NewRevision;
const char* git = this->CommandLineTool.c_str();
const char* git_rev_list[] = { git, "rev-list", "--reverse",
- range.c_str(), "--", CM_NULLPTR };
+ range.c_str(), "--", nullptr };
const char* git_diff_tree[] = {
git, "diff-tree", "--stdin", "--always", "-z",
- "-r", "--pretty=raw", "--encoding=utf-8", CM_NULLPTR
+ "-r", "--pretty=raw", "--encoding=utf-8", nullptr
};
this->Log << this->ComputeCommandLine(git_rev_list) << " | "
<< this->ComputeCommandLine(git_diff_tree) << "\n";
@@ -645,23 +641,21 @@ bool cmCTestGIT::LoadModifications()
// Use 'git update-index' to refresh the index w.r.t. the work tree.
const char* git_update_index[] = { git, "update-index", "--refresh",
- CM_NULLPTR };
+ nullptr };
OutputLogger ui_out(this->Log, "ui-out> ");
OutputLogger ui_err(this->Log, "ui-err> ");
- this->RunChild(git_update_index, &ui_out, &ui_err, CM_NULLPTR,
+ this->RunChild(git_update_index, &ui_out, &ui_err, nullptr,
cmProcessOutput::UTF8);
// Use 'git diff-index' to get modified files.
const char* git_diff_index[] = { git, "diff-index", "-z",
- "HEAD", "--", CM_NULLPTR };
+ "HEAD", "--", nullptr };
DiffParser out(this, "di-out> ");
OutputLogger err(this->Log, "di-err> ");
- this->RunChild(git_diff_index, &out, &err, CM_NULLPTR,
- cmProcessOutput::UTF8);
+ this->RunChild(git_diff_index, &out, &err, nullptr, cmProcessOutput::UTF8);
- for (std::vector<Change>::const_iterator ci = out.Changes.begin();
- ci != out.Changes.end(); ++ci) {
- this->DoModification(PathModified, ci->Path);
+ for (Change const& c : out.Changes) {
+ this->DoModification(PathModified, c.Path);
}
return true;
}
diff --git a/Source/CTest/cmCTestGIT.h b/Source/CTest/cmCTestGIT.h
index 4bf8294e6..ade430fae 100644
--- a/Source/CTest/cmCTestGIT.h
+++ b/Source/CTest/cmCTestGIT.h
@@ -3,7 +3,7 @@
#ifndef cmCTestGIT_h
#define cmCTestGIT_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestGlobalVC.h"
@@ -22,15 +22,15 @@ public:
/** Construct with a CTest instance and update log stream. */
cmCTestGIT(cmCTest* ctest, std::ostream& log);
- ~cmCTestGIT() CM_OVERRIDE;
+ ~cmCTestGIT() override;
private:
unsigned int CurrentGitVersion;
unsigned int GetGitVersion();
std::string GetWorkingRevision();
- bool NoteOldRevision() CM_OVERRIDE;
- bool NoteNewRevision() CM_OVERRIDE;
- bool UpdateImpl() CM_OVERRIDE;
+ bool NoteOldRevision() override;
+ bool NoteNewRevision() override;
+ bool UpdateImpl() override;
std::string FindGitDir();
std::string FindTopDir();
@@ -39,8 +39,8 @@ private:
bool UpdateByCustom(std::string const& custom);
bool UpdateInternal();
- bool LoadRevisions() CM_OVERRIDE;
- bool LoadModifications() CM_OVERRIDE;
+ bool LoadRevisions() override;
+ bool LoadModifications() override;
// "public" needed by older Sun compilers
public:
diff --git a/Source/CTest/cmCTestGenericHandler.cxx b/Source/CTest/cmCTestGenericHandler.cxx
index 19034c01b..ce8f70998 100644
--- a/Source/CTest/cmCTestGenericHandler.cxx
+++ b/Source/CTest/cmCTestGenericHandler.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCTestGenericHandler.h"
-#include "cmConfigure.h"
#include <sstream>
#include <utility>
@@ -12,7 +11,7 @@
cmCTestGenericHandler::cmCTestGenericHandler()
{
this->HandlerVerbose = cmSystemTools::OUTPUT_NONE;
- this->CTest = CM_NULLPTR;
+ this->CTest = nullptr;
this->SubmitIndex = 0;
this->AppendXML = false;
this->Quiet = false;
@@ -58,10 +57,8 @@ void cmCTestGenericHandler::Initialize()
this->AppendXML = false;
this->TestLoad = 0;
this->Options.clear();
- t_StringToString::iterator it;
- for (it = this->PersistentOptions.begin();
- it != this->PersistentOptions.end(); ++it) {
- this->Options[it->first] = it->second;
+ for (auto const& po : this->PersistentOptions) {
+ this->Options[po.first] = po.second;
}
}
@@ -70,7 +67,7 @@ const char* cmCTestGenericHandler::GetOption(const std::string& op)
cmCTestGenericHandler::t_StringToString::iterator remit =
this->Options.find(op);
if (remit == this->Options.end()) {
- return CM_NULLPTR;
+ return nullptr;
}
return remit->second.c_str();
}
diff --git a/Source/CTest/cmCTestGlobalVC.cxx b/Source/CTest/cmCTestGlobalVC.cxx
index 25294b5ae..d2714d90b 100644
--- a/Source/CTest/cmCTestGlobalVC.cxx
+++ b/Source/CTest/cmCTestGlobalVC.cxx
@@ -48,15 +48,14 @@ void cmCTestGlobalVC::DoRevision(Revision const& revision,
/* clang-format on */
// Update information about revisions of the changed files.
- for (std::vector<Change>::const_iterator ci = changes.begin();
- ci != changes.end(); ++ci) {
- if (const char* local = this->LocalPath(ci->Path)) {
+ for (Change const& c : changes) {
+ if (const char* local = this->LocalPath(c.Path)) {
std::string dir = cmSystemTools::GetFilenamePath(local);
std::string name = cmSystemTools::GetFilenameName(local);
File& file = this->Dirs[dir][name];
file.PriorRev = file.Rev ? file.Rev : &this->PriorRev;
file.Rev = &rev;
- this->Log << " " << ci->Action << " " << local << " "
+ this->Log << " " << c.Action << " " << local << " "
<< "\n";
}
}
@@ -83,9 +82,9 @@ void cmCTestGlobalVC::WriteXMLDirectory(cmXMLWriter& xml,
const char* slash = path.empty() ? "" : "/";
xml.StartElement("Directory");
xml.Element("Name", path);
- for (Directory::const_iterator fi = dir.begin(); fi != dir.end(); ++fi) {
- std::string full = path + slash + fi->first;
- this->WriteXMLEntry(xml, path, fi->first, full, fi->second);
+ for (auto const& f : dir) {
+ std::string const full = path + slash + f.first;
+ this->WriteXMLEntry(xml, path, f.first, full, f.second);
}
xml.EndElement(); // Directory
}
@@ -114,10 +113,8 @@ bool cmCTestGlobalVC::WriteXMLUpdates(cmXMLWriter& xml)
this->WriteXMLGlobal(xml);
- for (std::map<std::string, Directory>::const_iterator di =
- this->Dirs.begin();
- di != this->Dirs.end(); ++di) {
- this->WriteXMLDirectory(xml, di->first, di->second);
+ for (auto const& d : this->Dirs) {
+ this->WriteXMLDirectory(xml, d.first, d.second);
}
return result;
diff --git a/Source/CTest/cmCTestGlobalVC.h b/Source/CTest/cmCTestGlobalVC.h
index a5273d3dd..76377ed17 100644
--- a/Source/CTest/cmCTestGlobalVC.h
+++ b/Source/CTest/cmCTestGlobalVC.h
@@ -3,7 +3,7 @@
#ifndef cmCTestGlobalVC_h
#define cmCTestGlobalVC_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestVC.h"
@@ -26,11 +26,11 @@ public:
/** Construct with a CTest instance and update log stream. */
cmCTestGlobalVC(cmCTest* ctest, std::ostream& log);
- ~cmCTestGlobalVC() CM_OVERRIDE;
+ ~cmCTestGlobalVC() override;
protected:
// Implement cmCTestVC internal API.
- bool WriteXMLUpdates(cmXMLWriter& xml) CM_OVERRIDE;
+ bool WriteXMLUpdates(cmXMLWriter& xml) override;
/** Represent a vcs-reported action for one path in a revision. */
struct Change
diff --git a/Source/CTest/cmCTestHG.cxx b/Source/CTest/cmCTestHG.cxx
index 49f9a6500..525dacc1d 100644
--- a/Source/CTest/cmCTestHG.cxx
+++ b/Source/CTest/cmCTestHG.cxx
@@ -36,7 +36,7 @@ private:
std::string& Rev;
cmsys::RegularExpression RegexIdentify;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexIdentify.find(this->Line)) {
this->Rev = this->RegexIdentify.match(1);
@@ -60,7 +60,7 @@ private:
cmCTestHG* HG;
cmsys::RegularExpression RegexStatus;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexStatus.find(this->Line)) {
this->DoPath(this->RegexStatus.match(1)[0], this->RegexStatus.match(2));
@@ -96,7 +96,7 @@ std::string cmCTestHG::GetWorkingRevision()
{
// Run plumbing "hg identify" to get work tree revision.
const char* hg = this->CommandLineTool.c_str();
- const char* hg_identify[] = { hg, "identify", "-i", CM_NULLPTR };
+ const char* hg_identify[] = { hg, "identify", "-i", nullptr };
std::string rev;
IdentifyParser out(this, "rev-out> ", rev);
OutputLogger err(this->Log, "rev-err> ");
@@ -126,7 +126,7 @@ bool cmCTestHG::UpdateImpl()
// Use "hg pull" followed by "hg update" to update the working tree.
{
const char* hg = this->CommandLineTool.c_str();
- const char* hg_pull[] = { hg, "pull", "-v", CM_NULLPTR };
+ const char* hg_pull[] = { hg, "pull", "-v", nullptr };
OutputLogger out(this->Log, "pull-out> ");
OutputLogger err(this->Log, "pull-err> ");
this->RunChild(&hg_pull[0], &out, &err);
@@ -145,13 +145,12 @@ bool cmCTestHG::UpdateImpl()
opts = this->CTest->GetCTestConfiguration("HGUpdateOptions");
}
std::vector<std::string> args = cmSystemTools::ParseArguments(opts.c_str());
- for (std::vector<std::string>::const_iterator ai = args.begin();
- ai != args.end(); ++ai) {
- hg_update.push_back(ai->c_str());
+ for (std::string const& arg : args) {
+ hg_update.push_back(arg.c_str());
}
// Sentinel argument.
- hg_update.push_back(CM_NULLPTR);
+ hg_update.push_back(nullptr);
OutputLogger out(this->Log, "update-out> ");
OutputLogger err(this->Log, "update-err> ");
@@ -168,7 +167,7 @@ public:
{
this->InitializeParser();
}
- ~LogParser() CM_OVERRIDE { this->CleanupParser(); }
+ ~LogParser() override { this->CleanupParser(); }
private:
cmCTestHG* HG;
@@ -179,14 +178,14 @@ private:
Change CurChange;
std::vector<char> CData;
- bool ProcessChunk(const char* data, int length) CM_OVERRIDE
+ bool ProcessChunk(const char* data, int length) override
{
this->OutputLogger::ProcessChunk(data, length);
this->ParseChunk(data, length);
return true;
}
- void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
+ void StartElement(const std::string& name, const char** atts) override
{
this->CData.clear();
if (name == "logentry") {
@@ -198,12 +197,12 @@ private:
}
}
- void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
+ void CharacterDataHandler(const char* data, int length) override
{
this->CData.insert(this->CData.end(), data, data + length);
}
- void EndElement(const std::string& name) CM_OVERRIDE
+ void EndElement(const std::string& name) override
{
if (name == "logentry") {
this->HG->DoRevision(this->Rev, this->Changes);
@@ -217,25 +216,25 @@ private:
this->Rev.Log.assign(&this->CData[0], this->CData.size());
} else if (!this->CData.empty() && name == "files") {
std::vector<std::string> paths = this->SplitCData();
- for (unsigned int i = 0; i < paths.size(); ++i) {
+ for (std::string const& path : paths) {
// Updated by default, will be modified using file_adds and
// file_dels.
this->CurChange = Change('U');
- this->CurChange.Path = paths[i];
+ this->CurChange.Path = path;
this->Changes.push_back(this->CurChange);
}
} else if (!this->CData.empty() && name == "file_adds") {
std::string added_paths(this->CData.begin(), this->CData.end());
- for (unsigned int i = 0; i < this->Changes.size(); ++i) {
- if (added_paths.find(this->Changes[i].Path) != std::string::npos) {
- this->Changes[i].Action = 'A';
+ for (Change& change : this->Changes) {
+ if (added_paths.find(change.Path) != std::string::npos) {
+ change.Action = 'A';
}
}
} else if (!this->CData.empty() && name == "file_dels") {
std::string added_paths(this->CData.begin(), this->CData.end());
- for (unsigned int i = 0; i < this->Changes.size(); ++i) {
- if (added_paths.find(this->Changes[i].Path) != std::string::npos) {
- this->Changes[i].Action = 'D';
+ for (Change& change : this->Changes) {
+ if (added_paths.find(change.Path) != std::string::npos) {
+ change.Action = 'D';
}
}
}
@@ -246,19 +245,19 @@ private:
{
std::vector<std::string> output;
std::string currPath;
- for (unsigned int i = 0; i < this->CData.size(); ++i) {
- if (this->CData[i] != ' ') {
- currPath += this->CData[i];
+ for (char i : this->CData) {
+ if (i != ' ') {
+ currPath += i;
} else {
output.push_back(currPath);
- currPath = "";
+ currPath.clear();
}
}
output.push_back(currPath);
return output;
}
- void ReportError(int /*line*/, int /*column*/, const char* msg) CM_OVERRIDE
+ void ReportError(int /*line*/, int /*column*/, const char* msg) override
{
this->HG->Log << "Error parsing hg log xml: " << msg << "\n";
}
@@ -286,7 +285,7 @@ bool cmCTestHG::LoadRevisions()
"</logentry>\n";
const char* hg_log[] = {
hg, "log", "--removed", "-r", range.c_str(),
- "--template", hgXMLTemplate, CM_NULLPTR
+ "--template", hgXMLTemplate, nullptr
};
LogParser out(this, "log-out> ");
@@ -302,7 +301,7 @@ bool cmCTestHG::LoadModifications()
{
// Use 'hg status' to get modified files.
const char* hg = this->CommandLineTool.c_str();
- const char* hg_status[] = { hg, "status", CM_NULLPTR };
+ const char* hg_status[] = { hg, "status", nullptr };
StatusParser out(this, "status-out> ");
OutputLogger err(this->Log, "status-err> ");
this->RunChild(hg_status, &out, &err);
diff --git a/Source/CTest/cmCTestHG.h b/Source/CTest/cmCTestHG.h
index ec9eaffe8..c12d61887 100644
--- a/Source/CTest/cmCTestHG.h
+++ b/Source/CTest/cmCTestHG.h
@@ -3,7 +3,7 @@
#ifndef cmCTestHG_h
#define cmCTestHG_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestGlobalVC.h"
@@ -22,16 +22,16 @@ public:
/** Construct with a CTest instance and update log stream. */
cmCTestHG(cmCTest* ctest, std::ostream& log);
- ~cmCTestHG() CM_OVERRIDE;
+ ~cmCTestHG() override;
private:
std::string GetWorkingRevision();
- bool NoteOldRevision() CM_OVERRIDE;
- bool NoteNewRevision() CM_OVERRIDE;
- bool UpdateImpl() CM_OVERRIDE;
+ bool NoteOldRevision() override;
+ bool NoteNewRevision() override;
+ bool UpdateImpl() override;
- bool LoadRevisions() CM_OVERRIDE;
- bool LoadModifications() CM_OVERRIDE;
+ bool LoadRevisions() override;
+ bool LoadModifications() override;
// Parsing helper classes.
class IdentifyParser;
diff --git a/Source/CTest/cmCTestHandlerCommand.cxx b/Source/CTest/cmCTestHandlerCommand.cxx
index c99e450d0..5a7baf545 100644
--- a/Source/CTest/cmCTestHandlerCommand.cxx
+++ b/Source/CTest/cmCTestHandlerCommand.cxx
@@ -20,7 +20,7 @@ cmCTestHandlerCommand::cmCTestHandlerCommand()
size_t cc;
this->Arguments.reserve(INIT_SIZE);
for (cc = 0; cc < INIT_SIZE; ++cc) {
- this->Arguments.push_back(CM_NULLPTR);
+ this->Arguments.push_back(nullptr);
}
this->Arguments[ct_RETURN_VALUE] = "RETURN_VALUE";
this->Arguments[ct_CAPTURE_CMAKE_ERROR] = "CAPTURE_CMAKE_ERROR";
@@ -89,7 +89,7 @@ bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args,
SaveRestoreErrorState errorState;
// Allocate space for argument values.
this->Values.clear();
- this->Values.resize(this->Last, CM_NULLPTR);
+ this->Values.resize(this->Last, nullptr);
// Process input arguments.
this->ArgumentDoing = ArgumentDoingNone;
@@ -97,12 +97,11 @@ bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args,
// bad one so that CAPTURE_CMAKE_ERROR can override setting the
// global error state
bool foundBadArgument = false;
- for (unsigned int i = 0; i < args.size(); ++i) {
+ for (std::string const& arg : args) {
// Check this argument.
- if (!this->CheckArgumentKeyword(args[i]) &&
- !this->CheckArgumentValue(args[i])) {
+ if (!this->CheckArgumentKeyword(arg) && !this->CheckArgumentValue(arg)) {
std::ostringstream e;
- e << "called with unknown argument \"" << args[i] << "\".";
+ e << "called with unknown argument \"" << arg << "\".";
this->SetError(e.str());
foundBadArgument = true;
}
diff --git a/Source/CTest/cmCTestHandlerCommand.h b/Source/CTest/cmCTestHandlerCommand.h
index 0ea061225..79d61f3c7 100644
--- a/Source/CTest/cmCTestHandlerCommand.h
+++ b/Source/CTest/cmCTestHandlerCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestHandlerCommand_h
#define cmCTestHandlerCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestCommand.h"
@@ -34,7 +34,7 @@ public:
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
enum
{
diff --git a/Source/CTest/cmCTestLaunch.cxx b/Source/CTest/cmCTestLaunch.cxx
index 5b213518a..a1249f5b3 100644
--- a/Source/CTest/cmCTestLaunch.cxx
+++ b/Source/CTest/cmCTestLaunch.cxx
@@ -2,12 +2,11 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCTestLaunch.h"
-#include "cmConfigure.h"
-
#include "cmsys/FStream.hxx"
#include "cmsys/Process.h"
#include "cmsys/RegularExpression.hxx"
#include <iostream>
+#include <memory> // IWYU pragma: keep
#include <stdlib.h>
#include <string.h>
@@ -19,7 +18,6 @@
#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
#include "cmXMLWriter.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
#ifdef _WIN32
@@ -31,7 +29,7 @@
cmCTestLaunch::cmCTestLaunch(int argc, const char* const* argv)
{
this->Passthru = true;
- this->Process = CM_NULLPTR;
+ this->Process = nullptr;
this->ExitCode = 1;
this->CWD = cmSystemTools::GetCurrentWorkingDirectory();
@@ -129,7 +127,7 @@ bool cmCTestLaunch::ParseArguments(int argc, const char* const* argv)
return true;
}
this->RealArgC = 0;
- this->RealArgV = CM_NULLPTR;
+ this->RealArgV = nullptr;
std::cerr << "No launch/command separator ('--') found!\n";
return false;
}
@@ -171,9 +169,8 @@ void cmCTestLaunch::ComputeFileNames()
cmCryptoHash md5(cmCryptoHash::AlgoMD5);
md5.Initialize();
md5.Append(this->CWD);
- for (std::vector<std::string>::const_iterator ai = this->RealArgs.begin();
- ai != this->RealArgs.end(); ++ai) {
- md5.Append(*ai);
+ for (std::string const& realArg : this->RealArgs) {
+ md5.Append(realArg);
}
this->LogHash = md5.FinalizeHex();
@@ -224,11 +221,11 @@ void cmCTestLaunch::RunChild()
// Record child stdout and stderr if necessary.
if (!this->Passthru) {
- char* data = CM_NULLPTR;
+ char* data = nullptr;
int length = 0;
cmProcessOutput processOutput;
std::string strdata;
- while (int p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
+ while (int p = cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
if (p == cmsysProcess_Pipe_STDOUT) {
processOutput.DecodeText(data, length, strdata, 1);
fout.write(strdata.c_str(), strdata.size());
@@ -254,7 +251,7 @@ void cmCTestLaunch::RunChild()
}
// Wait for the real command to finish.
- cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ cmsysProcess_WaitForExit(cp, nullptr);
this->ExitCode = cmsysProcess_GetExitValue(cp);
}
@@ -396,7 +393,7 @@ void cmCTestLaunch::WriteXMLAction(cmXMLWriter& xml)
}
// OutputType
- const char* outputType = CM_NULLPTR;
+ const char* outputType = nullptr;
if (!this->OptionTargetType.empty()) {
if (this->OptionTargetType == "EXECUTABLE") {
outputType = "executable";
@@ -424,9 +421,8 @@ void cmCTestLaunch::WriteXMLCommand(cmXMLWriter& xml)
if (!this->CWD.empty()) {
xml.Element("WorkingDirectory", this->CWD);
}
- for (std::vector<std::string>::const_iterator ai = this->RealArgs.begin();
- ai != this->RealArgs.end(); ++ai) {
- xml.Element("Argument", *ai);
+ for (std::string const& realArg : this->RealArgs) {
+ xml.Element("Argument", realArg);
}
xml.EndElement(); // Command
}
@@ -489,9 +485,8 @@ void cmCTestLaunch::WriteXMLLabels(cmXMLWriter& xml)
if (!this->Labels.empty()) {
xml.Comment("Interested parties");
xml.StartElement("Labels");
- for (std::set<std::string>::const_iterator li = this->Labels.begin();
- li != this->Labels.end(); ++li) {
- xml.Element("Label", *li);
+ for (std::string const& label : this->Labels) {
+ xml.Element("Label", label);
}
xml.EndElement(); // Labels
}
@@ -508,7 +503,11 @@ void cmCTestLaunch::DumpFileToXML(cmXMLWriter& xml, std::string const& fname)
if (MatchesFilterPrefix(line)) {
continue;
}
-
+ if (this->Match(line, this->RegexWarningSuppress)) {
+ line = "[CTest: warning suppressed] " + line;
+ } else if (this->Match(line, this->RegexWarning)) {
+ line = "[CTest: warning matched] " + line;
+ }
xml.Content(sep);
xml.Content(line);
sep = "\n";
@@ -595,9 +594,8 @@ bool cmCTestLaunch::ScrapeLog(std::string const& fname)
bool cmCTestLaunch::Match(std::string const& line,
std::vector<cmsys::RegularExpression>& regexps)
{
- for (std::vector<cmsys::RegularExpression>::iterator ri = regexps.begin();
- ri != regexps.end(); ++ri) {
- if (ri->find(line.c_str())) {
+ for (cmsys::RegularExpression& r : regexps) {
+ if (r.find(line.c_str())) {
return true;
}
}
@@ -628,12 +626,12 @@ void cmCTestLaunch::LoadConfig()
cm.SetHomeOutputDirectory("");
cm.GetCurrentSnapshot().SetDefaultDefinitions();
cmGlobalGenerator gg(&cm);
- CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
+ cmMakefile mf(&gg, cm.GetCurrentSnapshot());
std::string fname = this->LogDir;
fname += "CTestLaunchConfig.cmake";
if (cmSystemTools::FileExists(fname.c_str()) &&
- mf->ReadListFile(fname.c_str())) {
- this->SourceDir = mf->GetSafeDefinition("CTEST_SOURCE_DIRECTORY");
+ mf.ReadListFile(fname.c_str())) {
+ this->SourceDir = mf.GetSafeDefinition("CTEST_SOURCE_DIRECTORY");
cmSystemTools::ConvertToUnixSlashes(this->SourceDir);
}
}
diff --git a/Source/CTest/cmCTestMemCheckCommand.cxx b/Source/CTest/cmCTestMemCheckCommand.cxx
index b9cae3bfe..a5d599583 100644
--- a/Source/CTest/cmCTestMemCheckCommand.cxx
+++ b/Source/CTest/cmCTestMemCheckCommand.cxx
@@ -14,7 +14,7 @@
cmCTestMemCheckCommand::cmCTestMemCheckCommand()
{
this->Arguments[ctm_DEFECT_COUNT] = "DEFECT_COUNT";
- this->Arguments[ctm_LAST] = CM_NULLPTR;
+ this->Arguments[ctm_LAST] = nullptr;
this->Last = ctm_LAST;
}
diff --git a/Source/CTest/cmCTestMemCheckCommand.h b/Source/CTest/cmCTestMemCheckCommand.h
index fa595594a..b6b3c4028 100644
--- a/Source/CTest/cmCTestMemCheckCommand.h
+++ b/Source/CTest/cmCTestMemCheckCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestMemCheckCommand_h
#define cmCTestMemCheckCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestTestCommand.h"
@@ -23,7 +23,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestMemCheckCommand* ni = new cmCTestMemCheckCommand;
ni->CTest = this->CTest;
@@ -32,9 +32,9 @@ public:
}
protected:
- cmCTestGenericHandler* InitializeActualHandler() CM_OVERRIDE;
+ cmCTestGenericHandler* InitializeActualHandler() override;
- void ProcessAdditionalValues(cmCTestGenericHandler* handler) CM_OVERRIDE;
+ void ProcessAdditionalValues(cmCTestGenericHandler* handler) override;
enum
{
diff --git a/Source/CTest/cmCTestMemCheckHandler.cxx b/Source/CTest/cmCTestMemCheckHandler.cxx
index c35f0bc70..3efb039ea 100644
--- a/Source/CTest/cmCTestMemCheckHandler.cxx
+++ b/Source/CTest/cmCTestMemCheckHandler.cxx
@@ -28,12 +28,12 @@ static CatToErrorType cmCTestMemCheckBoundsChecker[] = {
{ "Allocation Conflict", cmCTestMemCheckHandler::FMM },
{ "Bad Pointer Use", cmCTestMemCheckHandler::FMW },
{ "Dangling Pointer", cmCTestMemCheckHandler::FMR },
- { CM_NULLPTR, 0 }
+ { nullptr, 0 }
};
static void xmlReportError(int line, const char* msg, void* data)
{
- cmCTest* ctest = (cmCTest*)data;
+ cmCTest* ctest = static_cast<cmCTest*>(data);
cmCTestLog(ctest, ERROR_MESSAGE, "Error parsing XML in stream at line "
<< line << ": " << msg << std::endl);
}
@@ -45,9 +45,9 @@ public:
cmBoundsCheckerParser(cmCTest* c)
{
this->CTest = c;
- this->SetErrorCallback(xmlReportError, (void*)c);
+ this->SetErrorCallback(xmlReportError, c);
}
- void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
+ void StartElement(const std::string& name, const char** atts) override
{
if (name == "MemoryLeak" || name == "ResourceLeak") {
this->Errors.push_back(cmCTestMemCheckHandler::MLK);
@@ -58,23 +58,23 @@ public:
std::ostringstream ostr;
ostr << name << ":\n";
int i = 0;
- for (; atts[i] != CM_NULLPTR; i += 2) {
+ for (; atts[i] != nullptr; i += 2) {
ostr << " " << atts[i] << " - " << atts[i + 1] << "\n";
}
ostr << "\n";
this->Log += ostr.str();
}
- void EndElement(const std::string& /*name*/) CM_OVERRIDE {}
+ void EndElement(const std::string& /*name*/) override {}
const char* GetAttribute(const char* name, const char** atts)
{
int i = 0;
- for (; atts[i] != CM_NULLPTR; ++i) {
+ for (; atts[i] != nullptr; ++i) {
if (strcmp(name, atts[i]) == 0) {
return atts[i + 1];
}
}
- return CM_NULLPTR;
+ return nullptr;
}
void ParseError(const char** atts)
{
@@ -122,11 +122,11 @@ void cmCTestMemCheckHandler::Initialize()
this->LogWithPID = false;
this->CustomMaximumPassedTestOutputSize = 0;
this->CustomMaximumFailedTestOutputSize = 0;
- this->MemoryTester = "";
+ this->MemoryTester.clear();
this->MemoryTesterDynamicOptions.clear();
this->MemoryTesterOptions.clear();
this->MemoryTesterStyle = UNKNOWN;
- this->MemoryTesterOutputFile = "";
+ this->MemoryTesterOutputFile.clear();
this->DefectCount = 0;
}
@@ -157,15 +157,13 @@ int cmCTestMemCheckHandler::PostProcessHandler()
void cmCTestMemCheckHandler::GenerateTestCommand(
std::vector<std::string>& args, int test)
{
- std::vector<std::string>::size_type pp;
std::string index;
std::ostringstream stream;
std::string memcheckcommand =
cmSystemTools::ConvertToOutputPath(this->MemoryTester.c_str());
stream << test;
index = stream.str();
- for (pp = 0; pp < this->MemoryTesterDynamicOptions.size(); pp++) {
- std::string arg = this->MemoryTesterDynamicOptions[pp];
+ for (std::string arg : this->MemoryTesterDynamicOptions) {
std::string::size_type pos = arg.find("??");
if (pos != std::string::npos) {
arg.replace(pos, 2, index);
@@ -180,18 +178,18 @@ void cmCTestMemCheckHandler::GenerateTestCommand(
// via environment varaibles.
std::string memTesterEnvironmentVariable =
this->MemoryTesterEnvironmentVariable;
- for (pp = 0; pp < this->MemoryTesterOptions.size(); pp++) {
+ for (std::string const& arg : this->MemoryTesterOptions) {
if (!memTesterEnvironmentVariable.empty()) {
// If we are using env to pass options, append all the options to
// this string with space separation.
- memTesterEnvironmentVariable += " " + this->MemoryTesterOptions[pp];
+ memTesterEnvironmentVariable += " " + arg;
}
// for regular options just add them to args and memcheckcommand
// which is just used for display
else {
- args.push_back(this->MemoryTesterOptions[pp]);
+ args.push_back(arg);
memcheckcommand += " \"";
- memcheckcommand += this->MemoryTesterOptions[pp];
+ memcheckcommand += arg;
memcheckcommand += "\"";
}
}
@@ -228,9 +226,9 @@ void cmCTestMemCheckHandler::InitializeResultsVectors()
// define the standard set of errors
//----------------------------------------------------------------------
static const char* cmCTestMemCheckResultStrings[] = {
- "ABR", "ABW", "ABWL", "COR", "EXU", "FFM", "FIM", "FMM",
- "FMR", "FMW", "FUM", "IPR", "IPW", "MAF", "MLK", "MPK",
- "NPR", "ODS", "PAR", "PLK", "UMC", "UMR", CM_NULLPTR
+ "ABR", "ABW", "ABWL", "COR", "EXU", "FFM", "FIM", "FMM",
+ "FMR", "FMW", "FUM", "IPR", "IPW", "MAF", "MLK", "MPK",
+ "NPR", "ODS", "PAR", "PLK", "UMC", "UMR", nullptr
};
static const char* cmCTestMemCheckResultLongStrings[] = {
"Threading Problem",
@@ -255,10 +253,10 @@ void cmCTestMemCheckHandler::InitializeResultsVectors()
"PLK",
"Uninitialized Memory Conditional",
"Uninitialized Memory Read",
- CM_NULLPTR
+ nullptr
};
this->GlobalResults.clear();
- for (int i = 0; cmCTestMemCheckResultStrings[i] != CM_NULLPTR; ++i) {
+ for (int i = 0; cmCTestMemCheckResultStrings[i] != nullptr; ++i) {
this->ResultStrings.push_back(cmCTestMemCheckResultStrings[i]);
this->ResultStringsLong.push_back(cmCTestMemCheckResultLongStrings[i]);
this->GlobalResults.push_back(0);
@@ -291,6 +289,7 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
return;
}
this->CTest->StartXML(xml, this->AppendXML);
+ this->CTest->GenerateSubprojectsOutput(xml);
xml.StartElement("DynamicAnalysis");
switch (this->MemoryTesterStyle) {
case cmCTestMemCheckHandler::VALGRIND:
@@ -325,9 +324,8 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
xml.Element("StartTestTime", this->StartTestTime);
xml.StartElement("TestList");
cmCTestMemCheckHandler::TestResultsVector::size_type cc;
- for (cc = 0; cc < this->TestResults.size(); cc++) {
- cmCTestTestResult* result = &this->TestResults[cc];
- std::string testPath = result->Path + "/" + result->Name;
+ for (cmCTestTestResult const& result : this->TestResults) {
+ std::string testPath = result.Path + "/" + result.Name;
xml.Element("Test", this->CTest->GetShortPathToFile(testPath.c_str()));
}
xml.EndElement(); // TestList
@@ -335,12 +333,12 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
"-- Processing memory checking output:\n", this->Quiet);
size_t total = this->TestResults.size();
for (cc = 0; cc < this->TestResults.size(); cc++) {
- cmCTestTestResult* result = &this->TestResults[cc];
+ cmCTestTestResult const& result = this->TestResults[cc];
std::string memcheckstr;
std::vector<int> memcheckresults(this->ResultStrings.size(), 0);
- bool res = this->ProcessMemCheckOutput(result->Output, memcheckstr,
- memcheckresults);
- if (res && result->Status == cmCTestMemCheckHandler::COMPLETED) {
+ bool res =
+ this->ProcessMemCheckOutput(result.Output, memcheckstr, memcheckresults);
+ if (res && result.Status == cmCTestMemCheckHandler::COMPLETED) {
continue;
}
this->CleanTestOutput(
@@ -363,11 +361,11 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
xml.EndElement(); // Results
if (memoryErrors > 0) {
const int maxTestNameWidth = this->CTest->GetMaxTestNameWidth();
- std::string outname = result->Name + " ";
+ std::string outname = result.Name + " ";
outname.resize(maxTestNameWidth + 4, '.');
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, cc + 1
<< "/" << total << " MemCheck: #"
- << result->TestCount << ": " << outname
+ << result.TestCount << ": " << outname
<< " Defects: " << memoryErrors << std::endl,
this->Quiet);
}
@@ -419,8 +417,8 @@ void cmCTestMemCheckHandler::GenerateDartOutput(cmXMLWriter& xml)
bool cmCTestMemCheckHandler::InitializeMemoryChecking()
{
- this->MemoryTesterEnvironmentVariable = "";
- this->MemoryTester = "";
+ this->MemoryTesterEnvironmentVariable.clear();
+ this->MemoryTester.clear();
// Setup the command
if (cmSystemTools::FileExists(
this->CTest->GetCTestConfiguration("MemoryCheckCommand").c_str())) {
@@ -727,13 +725,12 @@ bool cmCTestMemCheckHandler::ProcessMemCheckSanitizerOutput(
std::vector<std::string> lines;
cmSystemTools::Split(str.c_str(), lines);
std::ostringstream ostr;
- log = "";
- for (std::vector<std::string>::iterator i = lines.begin(); i != lines.end();
- ++i) {
+ log.clear();
+ for (std::string const& l : lines) {
std::string resultFound;
- if (leakWarning.find(*i)) {
+ if (leakWarning.find(l)) {
resultFound = leakWarning.match(1) + " leak";
- } else if (sanitizerWarning.find(*i)) {
+ } else if (sanitizerWarning.find(l)) {
resultFound = sanitizerWarning.match(1);
}
if (!resultFound.empty()) {
@@ -746,7 +743,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckSanitizerOutput(
defects++;
ostr << "<b>" << this->ResultStrings[idx] << "</b> ";
}
- ostr << *i << std::endl;
+ ostr << l << std::endl;
}
log = ostr.str();
this->DefectCount += defects;
@@ -758,16 +755,15 @@ bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput(
std::vector<std::string> lines;
cmSystemTools::Split(str.c_str(), lines);
std::ostringstream ostr;
- log = "";
+ log.clear();
cmsys::RegularExpression pfW("^\\[[WEI]\\] ([A-Z][A-Z][A-Z][A-Z]*): ");
int defects = 0;
- for (std::vector<std::string>::iterator i = lines.begin(); i != lines.end();
- ++i) {
+ for (std::string const& l : lines) {
std::vector<int>::size_type failure = this->ResultStrings.size();
- if (pfW.find(*i)) {
+ if (pfW.find(l)) {
std::vector<int>::size_type cc;
for (cc = 0; cc < this->ResultStrings.size(); cc++) {
if (pfW.match(1) == this->ResultStrings[cc]) {
@@ -787,7 +783,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckPurifyOutput(
results[failure]++;
defects++;
}
- ostr << *i << std::endl;
+ ostr << l << std::endl;
}
log = ostr.str();
@@ -809,7 +805,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput(
std::string::size_type cc;
std::ostringstream ostr;
- log = "";
+ log.clear();
int defects = 0;
@@ -907,11 +903,9 @@ bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput(
// Now put all all the non valgrind output into the test output
// This should be last in case it gets truncated by the output
// limiting code
- for (std::vector<std::string::size_type>::iterator i =
- nonValGrindOutput.begin();
- i != nonValGrindOutput.end(); ++i) {
- totalOutputSize += lines[*i].size();
- ostr << lines[*i] << std::endl;
+ for (std::string::size_type i : nonValGrindOutput) {
+ totalOutputSize += lines[i].size();
+ ostr << lines[i] << std::endl;
if (!unlimitedOutput &&
totalOutputSize >
static_cast<size_t>(this->CustomMaximumFailedTestOutputSize)) {
@@ -934,7 +928,7 @@ bool cmCTestMemCheckHandler::ProcessMemCheckValgrindOutput(
bool cmCTestMemCheckHandler::ProcessMemCheckBoundsCheckerOutput(
const std::string& str, std::string& log, std::vector<int>& results)
{
- log = "";
+ log.clear();
double sttime = cmSystemTools::GetTime();
std::vector<std::string> lines;
cmSystemTools::Split(str.c_str(), lines);
@@ -962,8 +956,8 @@ bool cmCTestMemCheckHandler::ProcessMemCheckBoundsCheckerOutput(
}
}
int defects = 0;
- for (cc = 0; cc < parser.Errors.size(); ++cc) {
- results[parser.Errors[cc]]++;
+ for (int err : parser.Errors) {
+ results[err]++;
defects++;
}
cmCTestOptionalLog(this->CTest, DEBUG, "End test (elapsed: "
@@ -990,9 +984,8 @@ void cmCTestMemCheckHandler::PostProcessTest(cmCTestTestResult& res, int test)
} else {
std::vector<std::string> files;
this->TestOutputFileNames(test, files);
- for (std::vector<std::string>::iterator i = files.begin();
- i != files.end(); ++i) {
- this->AppendMemTesterOutput(res, *i);
+ for (std::string const& f : files) {
+ this->AppendMemTesterOutput(res, f);
}
}
}
@@ -1086,7 +1079,7 @@ void cmCTestMemCheckHandler::TestOutputFileNames(
if (g.GetFiles().empty()) {
std::string log = "Cannot find memory tester output file: " + ofile;
cmCTestLog(this->CTest, ERROR_MESSAGE, log << std::endl);
- ofile = "";
+ ofile.clear();
} else {
files = g.GetFiles();
return;
@@ -1094,7 +1087,7 @@ void cmCTestMemCheckHandler::TestOutputFileNames(
} else if (!cmSystemTools::FileExists(ofile.c_str())) {
std::string log = "Cannot find memory tester output file: " + ofile;
cmCTestLog(this->CTest, ERROR_MESSAGE, log << std::endl);
- ofile = "";
+ ofile.clear();
}
files.push_back(ofile);
}
diff --git a/Source/CTest/cmCTestMemCheckHandler.h b/Source/CTest/cmCTestMemCheckHandler.h
index 333c2e2dd..921829429 100644
--- a/Source/CTest/cmCTestMemCheckHandler.h
+++ b/Source/CTest/cmCTestMemCheckHandler.h
@@ -3,7 +3,7 @@
#ifndef cmCTestMemCheckHandler_h
#define cmCTestMemCheckHandler_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestTestHandler.h"
@@ -24,19 +24,18 @@ class cmCTestMemCheckHandler : public cmCTestTestHandler
public:
typedef cmCTestTestHandler Superclass;
- void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE;
+ void PopulateCustomVectors(cmMakefile* mf) override;
cmCTestMemCheckHandler();
- void Initialize() CM_OVERRIDE;
+ void Initialize() override;
int GetDefectCount();
protected:
- int PreProcessHandler() CM_OVERRIDE;
- int PostProcessHandler() CM_OVERRIDE;
- void GenerateTestCommand(std::vector<std::string>& args,
- int test) CM_OVERRIDE;
+ int PreProcessHandler() override;
+ int PostProcessHandler() override;
+ void GenerateTestCommand(std::vector<std::string>& args, int test) override;
private:
enum
@@ -121,7 +120,7 @@ private:
/**
* Generate the Dart compatible output
*/
- void GenerateDartOutput(cmXMLWriter& xml) CM_OVERRIDE;
+ void GenerateDartOutput(cmXMLWriter& xml) override;
std::vector<std::string> CustomPreMemCheck;
std::vector<std::string> CustomPostMemCheck;
diff --git a/Source/CTest/cmCTestMultiProcessHandler.cxx b/Source/CTest/cmCTestMultiProcessHandler.cxx
index 2c16a0d1e..6a7bdc03e 100644
--- a/Source/CTest/cmCTestMultiProcessHandler.cxx
+++ b/Source/CTest/cmCTestMultiProcessHandler.cxx
@@ -64,10 +64,9 @@ void cmCTestMultiProcessHandler::SetTests(TestMap& tests,
this->Properties = properties;
this->Total = this->Tests.size();
// set test run map to false for all
- for (TestMap::iterator i = this->Tests.begin(); i != this->Tests.end();
- ++i) {
- this->TestRunningMap[i->first] = false;
- this->TestFinishMap[i->first] = false;
+ for (auto const& t : this->Tests) {
+ this->TestRunningMap[t.first] = false;
+ this->TestFinishMap[t.first] = false;
}
if (!this->CTest->GetShowOnly()) {
this->ReadCostData();
@@ -131,11 +130,10 @@ void cmCTestMultiProcessHandler::StartTestProcess(int test)
// Find any failed dependencies for this test. We assume the more common
// scenario has no failed tests, so make it the outer loop.
- for (std::vector<std::string>::const_iterator it = this->Failed->begin();
- it != this->Failed->end(); ++it) {
- if (this->Properties[test]->RequireSuccessDepends.find(*it) !=
+ for (std::string const& f : *this->Failed) {
+ if (this->Properties[test]->RequireSuccessDepends.find(f) !=
this->Properties[test]->RequireSuccessDepends.end()) {
- testRun->AddFailedDependency(*it);
+ testRun->AddFailedDependency(f);
}
}
@@ -152,9 +150,8 @@ void cmCTestMultiProcessHandler::StartTestProcess(int test)
return;
} else {
- for (TestMap::iterator j = this->Tests.begin(); j != this->Tests.end();
- ++j) {
- j->second.erase(test);
+ for (auto& j : this->Tests) {
+ j.second.erase(test);
}
this->UnlockResources(test);
@@ -183,10 +180,8 @@ void cmCTestMultiProcessHandler::LockResources(int index)
void cmCTestMultiProcessHandler::UnlockResources(int index)
{
- for (std::set<std::string>::iterator i =
- this->Properties[index]->LockedResources.begin();
- i != this->Properties[index]->LockedResources.end(); ++i) {
- this->LockedResources.erase(*i);
+ for (std::string const& i : this->Properties[index]->LockedResources) {
+ this->LockedResources.erase(i);
}
if (this->Properties[index]->RunSerial) {
this->SerialTestRunning = false;
@@ -219,10 +214,8 @@ std::string cmCTestMultiProcessHandler::GetName(int test)
bool cmCTestMultiProcessHandler::StartTest(int test)
{
// Check for locked resources
- for (std::set<std::string>::iterator i =
- this->Properties[test]->LockedResources.begin();
- i != this->Properties[test]->LockedResources.end(); ++i) {
- if (this->LockedResources.find(*i) != this->LockedResources.end()) {
+ for (std::string const& i : this->Properties[test]->LockedResources) {
+ if (this->LockedResources.find(i) != this->LockedResources.end()) {
return false;
}
}
@@ -292,22 +285,22 @@ void cmCTestMultiProcessHandler::StartNextTests()
}
TestList copy = this->SortedTests;
- for (TestList::iterator test = copy.begin(); test != copy.end(); ++test) {
+ for (auto const& test : copy) {
// Take a nap if we're currently performing a RUN_SERIAL test.
if (this->SerialTestRunning) {
break;
}
// We can only start a RUN_SERIAL test if no other tests are also running.
- if (this->Properties[*test]->RunSerial && this->RunningCount > 0) {
+ if (this->Properties[test]->RunSerial && this->RunningCount > 0) {
continue;
}
- size_t processors = GetProcessorsUsed(*test);
+ size_t processors = GetProcessorsUsed(test);
bool testLoadOk = true;
if (this->TestLoad > 0) {
if (processors <= spareLoad) {
cmCTestLog(this->CTest, DEBUG, "OK to run "
- << GetName(*test) << ", it requires " << processors
+ << GetName(test) << ", it requires " << processors
<< " procs & system load is: " << systemLoad
<< std::endl);
allTestsFailedTestLoadCheck = false;
@@ -318,10 +311,10 @@ void cmCTestMultiProcessHandler::StartNextTests()
if (processors <= minProcessorsRequired) {
minProcessorsRequired = processors;
- testWithMinProcessors = GetName(*test);
+ testWithMinProcessors = GetName(test);
}
- if (testLoadOk && processors <= numToStart && this->StartTest(*test)) {
+ if (testLoadOk && processors <= numToStart && this->StartTest(test)) {
if (this->StopTimePassed) {
return;
}
@@ -368,18 +361,13 @@ bool cmCTestMultiProcessHandler::CheckOutput()
}
std::vector<cmCTestRunTest*> finished;
std::string out, err;
- for (std::set<cmCTestRunTest*>::const_iterator i =
- this->RunningTests.begin();
- i != this->RunningTests.end(); ++i) {
- cmCTestRunTest* p = *i;
+ for (cmCTestRunTest* p : this->RunningTests) {
if (!p->CheckOutput()) {
finished.push_back(p);
}
}
- for (std::vector<cmCTestRunTest*>::iterator i = finished.begin();
- i != finished.end(); ++i) {
+ for (cmCTestRunTest* p : finished) {
this->Completed++;
- cmCTestRunTest* p = *i;
int test = p->GetIndex();
bool testResult = p->EndTest(this->Completed, this->Total, true);
@@ -392,9 +380,8 @@ bool cmCTestMultiProcessHandler::CheckOutput()
} else {
this->Failed->push_back(p->GetTestProperties()->Name);
}
- for (TestMap::iterator j = this->Tests.begin(); j != this->Tests.end();
- ++j) {
- j->second.erase(test);
+ for (auto& t : this->Tests) {
+ t.second.erase(test);
}
this->TestFinishMap[test] = true;
this->TestRunningMap[test] = false;
@@ -451,16 +438,15 @@ void cmCTestMultiProcessHandler::UpdateCostData()
}
// Add all tests not previously listed in the file
- for (PropertiesMap::iterator i = temp.begin(); i != temp.end(); ++i) {
- fout << i->second->Name << " " << i->second->PreviousRuns << " "
- << i->second->Cost << "\n";
+ for (auto const& i : temp) {
+ fout << i.second->Name << " " << i.second->PreviousRuns << " "
+ << i.second->Cost << "\n";
}
// Write list of failed tests
fout << "---\n";
- for (std::vector<std::string>::iterator i = this->Failed->begin();
- i != this->Failed->end(); ++i) {
- fout << *i << "\n";
+ for (std::string const& f : *this->Failed) {
+ fout << f << "\n";
}
fout.close();
cmSystemTools::RenameFile(tmpout.c_str(), fname.c_str());
@@ -505,7 +491,7 @@ void cmCTestMultiProcessHandler::ReadCostData()
}
// Next part of the file is the failed tests
while (std::getline(fin, line)) {
- if (line != "") {
+ if (!line.empty()) {
this->LastTestsFailed.push_back(line);
}
}
@@ -517,10 +503,9 @@ int cmCTestMultiProcessHandler::SearchByName(std::string const& name)
{
int index = -1;
- for (PropertiesMap::iterator i = this->Properties.begin();
- i != this->Properties.end(); ++i) {
- if (i->second->Name == name) {
- index = i->first;
+ for (auto const& p : this->Properties) {
+ if (p.second->Name == name) {
+ index = p.first;
}
}
return index;
@@ -545,16 +530,15 @@ void cmCTestMultiProcessHandler::CreateParallelTestCostList()
// In parallel test runs add previously failed tests to the front
// of the cost list and queue other tests for further sorting
- for (TestMap::const_iterator i = this->Tests.begin(); i != this->Tests.end();
- ++i) {
+ for (auto const& t : this->Tests) {
if (std::find(this->LastTestsFailed.begin(), this->LastTestsFailed.end(),
- this->Properties[i->first]->Name) !=
+ this->Properties[t.first]->Name) !=
this->LastTestsFailed.end()) {
// If the test failed last time, it should be run first.
- this->SortedTests.push_back(i->first);
- alreadySortedTests.insert(i->first);
+ this->SortedTests.push_back(t.first);
+ alreadySortedTests.insert(t.first);
} else {
- topLevel.insert(i->first);
+ topLevel.insert(t.first);
}
}
@@ -566,15 +550,13 @@ void cmCTestMultiProcessHandler::CreateParallelTestCostList()
priorityStack.push_back(TestSet());
TestSet& currentSet = priorityStack.back();
- for (TestSet::const_iterator i = previousSet.begin();
- i != previousSet.end(); ++i) {
- TestSet const& dependencies = this->Tests[*i];
+ for (auto const& i : previousSet) {
+ TestSet const& dependencies = this->Tests[i];
currentSet.insert(dependencies.begin(), dependencies.end());
}
- for (TestSet::const_iterator i = currentSet.begin(); i != currentSet.end();
- ++i) {
- previousSet.erase(*i);
+ for (auto const& i : currentSet) {
+ previousSet.erase(i);
}
}
@@ -594,11 +576,10 @@ void cmCTestMultiProcessHandler::CreateParallelTestCostList()
std::stable_sort(sortedCopy.begin(), sortedCopy.end(), comp);
- for (TestList::const_iterator j = sortedCopy.begin();
- j != sortedCopy.end(); ++j) {
- if (alreadySortedTests.find(*j) == alreadySortedTests.end()) {
- this->SortedTests.push_back(*j);
- alreadySortedTests.insert(*j);
+ for (auto const& j : sortedCopy) {
+ if (alreadySortedTests.find(j) == alreadySortedTests.end()) {
+ this->SortedTests.push_back(j);
+ alreadySortedTests.insert(j);
}
}
}
@@ -608,10 +589,9 @@ void cmCTestMultiProcessHandler::GetAllTestDependencies(int test,
TestList& dependencies)
{
TestSet const& dependencySet = this->Tests[test];
- for (TestSet::const_iterator i = dependencySet.begin();
- i != dependencySet.end(); ++i) {
- GetAllTestDependencies(*i, dependencies);
- dependencies.push_back(*i);
+ for (int i : dependencySet) {
+ GetAllTestDependencies(i, dependencies);
+ dependencies.push_back(i);
}
}
@@ -619,9 +599,8 @@ void cmCTestMultiProcessHandler::CreateSerialTestCostList()
{
TestList presortedList;
- for (TestMap::iterator i = this->Tests.begin(); i != this->Tests.end();
- ++i) {
- presortedList.push_back(i->first);
+ for (auto const& i : this->Tests) {
+ presortedList.push_back(i.first);
}
TestComparator comp(this);
@@ -629,10 +608,7 @@ void cmCTestMultiProcessHandler::CreateSerialTestCostList()
TestSet alreadySortedTests;
- for (TestList::const_iterator i = presortedList.begin();
- i != presortedList.end(); ++i) {
- int test = *i;
-
+ for (int test : presortedList) {
if (alreadySortedTests.find(test) != alreadySortedTests.end()) {
continue;
}
@@ -640,10 +616,7 @@ void cmCTestMultiProcessHandler::CreateSerialTestCostList()
TestList dependencies;
GetAllTestDependencies(test, dependencies);
- for (TestList::const_iterator j = dependencies.begin();
- j != dependencies.end(); ++j) {
- int testDependency = *j;
-
+ for (int testDependency : dependencies) {
if (alreadySortedTests.find(testDependency) ==
alreadySortedTests.end()) {
alreadySortedTests.insert(testDependency);
@@ -679,10 +652,9 @@ void cmCTestMultiProcessHandler::PrintTestList()
this->TestHandler->SetMaxIndex(this->FindMaxIndex());
int count = 0;
- for (PropertiesMap::iterator it = this->Properties.begin();
- it != this->Properties.end(); ++it) {
+ for (auto& it : this->Properties) {
count++;
- cmCTestTestHandler::cmCTestTestProperties& p = *it->second;
+ cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
cmWorkingDirectory workdir(p.Directory);
@@ -696,9 +668,8 @@ void cmCTestMultiProcessHandler::PrintTestList()
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Labels:",
this->Quiet);
}
- for (std::vector<std::string>::iterator label = p.Labels.begin();
- label != p.Labels.end(); ++label) {
- cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " " << *label,
+ for (std::string const& label : p.Labels) {
+ cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " " << label,
this->Quiet);
}
if (!p.Labels.empty()) // print the labels
@@ -737,9 +708,8 @@ void cmCTestMultiProcessHandler::PrintTestList()
void cmCTestMultiProcessHandler::PrintLabels()
{
std::set<std::string> allLabels;
- for (PropertiesMap::iterator it = this->Properties.begin();
- it != this->Properties.end(); ++it) {
- cmCTestTestHandler::cmCTestTestProperties& p = *it->second;
+ for (auto& it : this->Properties) {
+ cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
allLabels.insert(p.Labels.begin(), p.Labels.end());
}
@@ -750,10 +720,9 @@ void cmCTestMultiProcessHandler::PrintLabels()
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
"No Labels Exist" << std::endl, this->Quiet);
}
- for (std::set<std::string>::iterator label = allLabels.begin();
- label != allLabels.end(); ++label) {
- cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
- " " << *label << std::endl, this->Quiet);
+ for (std::string const& label : allLabels) {
+ cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " " << label << std::endl,
+ this->Quiet);
}
}
@@ -794,10 +763,9 @@ void cmCTestMultiProcessHandler::RemoveTest(int index)
int cmCTestMultiProcessHandler::FindMaxIndex()
{
int max = 0;
- cmCTestMultiProcessHandler::TestMap::iterator i = this->Tests.begin();
- for (; i != this->Tests.end(); ++i) {
- if (i->first > max) {
- max = i->first;
+ for (auto const& i : this->Tests) {
+ if (i.first > max) {
+ max = i.first;
}
}
return max;
@@ -809,10 +777,9 @@ bool cmCTestMultiProcessHandler::CheckCycles()
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Checking test dependency graph..." << std::endl,
this->Quiet);
- for (TestMap::iterator it = this->Tests.begin(); it != this->Tests.end();
- ++it) {
+ for (auto const& it : this->Tests) {
// DFS from each element to itself
- int root = it->first;
+ int root = it.first;
std::set<int> visited;
std::stack<int> s;
s.push(root);
@@ -820,9 +787,8 @@ bool cmCTestMultiProcessHandler::CheckCycles()
int test = s.top();
s.pop();
if (visited.insert(test).second) {
- for (TestSet::iterator d = this->Tests[test].begin();
- d != this->Tests[test].end(); ++d) {
- if (*d == root) {
+ for (auto const& d : this->Tests[test]) {
+ if (d == root) {
// cycle exists
cmCTestLog(
this->CTest, ERROR_MESSAGE,
@@ -832,7 +798,7 @@ bool cmCTestMultiProcessHandler::CheckCycles()
<< "\".\nPlease fix the cycle and run ctest again.\n");
return false;
}
- s.push(*d);
+ s.push(d);
}
}
}
diff --git a/Source/CTest/cmCTestP4.cxx b/Source/CTest/cmCTestP4.cxx
index c80221634..fdf893243 100644
--- a/Source/CTest/cmCTestP4.cxx
+++ b/Source/CTest/cmCTestP4.cxx
@@ -37,7 +37,7 @@ private:
std::string& Rev;
cmsys::RegularExpression RegexIdentify;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexIdentify.find(this->Line)) {
this->Rev = this->RegexIdentify.match(1);
@@ -61,7 +61,7 @@ private:
cmsys::RegularExpression RegexIdentify;
cmCTestP4* P4;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexIdentify.find(this->Line)) {
P4->ChangeLists.push_back(this->RegexIdentify.match(1));
@@ -84,7 +84,7 @@ private:
cmsys::RegularExpression RegexUser;
cmCTestP4* P4;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexUser.find(this->Line)) {
User NewUser;
@@ -127,7 +127,7 @@ private:
std::string CurrentPath;
cmsys::RegularExpression RegexDiff;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (!this->Line.empty() && this->Line[0] == '=' &&
this->RegexDiff.find(this->Line)) {
@@ -155,7 +155,7 @@ cmCTestP4::User cmCTestP4::GetUserData(const std::string& username)
p4_users.push_back("-m");
p4_users.push_back("1");
p4_users.push_back(username.c_str());
- p4_users.push_back(CM_NULLPTR);
+ p4_users.push_back(nullptr);
UserParser out(this, "users-out> ");
OutputLogger err(this->Log, "users-err> ");
@@ -217,7 +217,7 @@ private:
SectionType Section;
Revision Rev;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->Line.empty()) {
this->NextSection();
@@ -332,9 +332,8 @@ void cmCTestP4::SetP4Options(std::vector<char const*>& CommandOptions)
}
CommandOptions.clear();
- for (std::vector<std::string>::iterator i = P4Options.begin();
- i != P4Options.end(); ++i) {
- CommandOptions.push_back(i->c_str());
+ for (std::string const& o : P4Options) {
+ CommandOptions.push_back(o.c_str());
}
}
@@ -350,7 +349,7 @@ std::string cmCTestP4::GetWorkingRevision()
std::string source = this->SourceDirectory + "/...#have";
p4_identify.push_back(source.c_str());
- p4_identify.push_back(CM_NULLPTR);
+ p4_identify.push_back(nullptr);
std::string rev;
IdentifyParser out(this, "p4_changes-out> ", rev);
@@ -411,7 +410,7 @@ bool cmCTestP4::LoadRevisions()
p4_changes.push_back("changes");
p4_changes.push_back(range.c_str());
- p4_changes.push_back(CM_NULLPTR);
+ p4_changes.push_back(nullptr);
ChangesParser out(this, "p4_changes-out> ");
OutputLogger err(this->Log, "p4_changes-err> ");
@@ -431,7 +430,7 @@ bool cmCTestP4::LoadRevisions()
p4_describe.push_back("describe");
p4_describe.push_back("-s");
p4_describe.push_back(i->c_str());
- p4_describe.push_back(CM_NULLPTR);
+ p4_describe.push_back(nullptr);
DescribeParser outDescribe(this, "p4_describe-out> ");
OutputLogger errDescribe(this->Log, "p4_describe-err> ");
@@ -451,7 +450,7 @@ bool cmCTestP4::LoadModifications()
p4_diff.push_back("-dn");
std::string source = this->SourceDirectory + "/...";
p4_diff.push_back(source.c_str());
- p4_diff.push_back(CM_NULLPTR);
+ p4_diff.push_back(nullptr);
DiffParser out(this, "p4_diff-out> ");
OutputLogger err(this->Log, "p4_diff-err> ");
@@ -465,11 +464,11 @@ bool cmCTestP4::UpdateCustom(const std::string& custom)
cmSystemTools::ExpandListArgument(custom, p4_custom_command, true);
std::vector<char const*> p4_custom;
- for (std::vector<std::string>::const_iterator i = p4_custom_command.begin();
- i != p4_custom_command.end(); ++i) {
- p4_custom.push_back(i->c_str());
+ p4_custom.reserve(p4_custom_command.size() + 1);
+ for (std::string const& i : p4_custom_command) {
+ p4_custom.push_back(i.c_str());
}
- p4_custom.push_back(CM_NULLPTR);
+ p4_custom.push_back(nullptr);
OutputLogger custom_out(this->Log, "p4_customsync-out> ");
OutputLogger custom_err(this->Log, "p4_customsync-err> ");
@@ -502,9 +501,8 @@ bool cmCTestP4::UpdateImpl()
opts = this->CTest->GetCTestConfiguration("P4UpdateOptions");
}
std::vector<std::string> args = cmSystemTools::ParseArguments(opts.c_str());
- for (std::vector<std::string>::const_iterator ai = args.begin();
- ai != args.end(); ++ai) {
- p4_sync.push_back(ai->c_str());
+ for (std::string const& arg : args) {
+ p4_sync.push_back(arg.c_str());
}
std::string source = this->SourceDirectory + "/...";
@@ -520,7 +518,7 @@ bool cmCTestP4::UpdateImpl()
}
p4_sync.push_back(source.c_str());
- p4_sync.push_back(CM_NULLPTR);
+ p4_sync.push_back(nullptr);
OutputLogger out(this->Log, "p4_sync-out> ");
OutputLogger err(this->Log, "p4_sync-err> ");
diff --git a/Source/CTest/cmCTestP4.h b/Source/CTest/cmCTestP4.h
index e234efbfb..b14edf7e9 100644
--- a/Source/CTest/cmCTestP4.h
+++ b/Source/CTest/cmCTestP4.h
@@ -3,7 +3,7 @@
#ifndef cmCTestP4_h
#define cmCTestP4_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestGlobalVC.h"
@@ -24,7 +24,7 @@ public:
/** Construct with a CTest instance and update log stream. */
cmCTestP4(cmCTest* ctest, std::ostream& log);
- ~cmCTestP4() CM_OVERRIDE;
+ ~cmCTestP4() override;
private:
std::vector<std::string> ChangeLists;
@@ -51,13 +51,13 @@ private:
void SetP4Options(std::vector<char const*>& options);
std::string GetWorkingRevision();
- bool NoteOldRevision() CM_OVERRIDE;
- bool NoteNewRevision() CM_OVERRIDE;
- bool UpdateImpl() CM_OVERRIDE;
+ bool NoteOldRevision() override;
+ bool NoteNewRevision() override;
+ bool UpdateImpl() override;
bool UpdateCustom(const std::string& custom);
- bool LoadRevisions() CM_OVERRIDE;
- bool LoadModifications() CM_OVERRIDE;
+ bool LoadRevisions() override;
+ bool LoadModifications() override;
class ChangesParser;
class DescribeParser;
diff --git a/Source/CTest/cmCTestReadCustomFilesCommand.cxx b/Source/CTest/cmCTestReadCustomFilesCommand.cxx
index b21be872f..ed14d0688 100644
--- a/Source/CTest/cmCTestReadCustomFilesCommand.cxx
+++ b/Source/CTest/cmCTestReadCustomFilesCommand.cxx
@@ -14,9 +14,8 @@ bool cmCTestReadCustomFilesCommand::InitialPass(
return false;
}
- std::vector<std::string>::const_iterator dit;
- for (dit = args.begin(); dit != args.end(); ++dit) {
- this->CTest->ReadCustomConfigurationFileTree(dit->c_str(), this->Makefile);
+ for (std::string const& arg : args) {
+ this->CTest->ReadCustomConfigurationFileTree(arg.c_str(), this->Makefile);
}
return true;
diff --git a/Source/CTest/cmCTestReadCustomFilesCommand.h b/Source/CTest/cmCTestReadCustomFilesCommand.h
index 5989fa0fc..ba25c516c 100644
--- a/Source/CTest/cmCTestReadCustomFilesCommand.h
+++ b/Source/CTest/cmCTestReadCustomFilesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestReadCustomFilesCommand_h
#define cmCTestReadCustomFilesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestCommand.h"
@@ -27,7 +27,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestReadCustomFilesCommand* ni = new cmCTestReadCustomFilesCommand;
ni->CTest = this->CTest;
@@ -39,7 +39,7 @@ public:
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/CTest/cmCTestRunScriptCommand.h b/Source/CTest/cmCTestRunScriptCommand.h
index 9bd09659d..9d8b4b587 100644
--- a/Source/CTest/cmCTestRunScriptCommand.h
+++ b/Source/CTest/cmCTestRunScriptCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestRunScriptCommand_h
#define cmCTestRunScriptCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestCommand.h"
@@ -27,7 +27,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestRunScriptCommand* ni = new cmCTestRunScriptCommand;
ni->CTest = this->CTest;
@@ -40,7 +40,7 @@ public:
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/CTest/cmCTestRunTest.cxx b/Source/CTest/cmCTestRunTest.cxx
index 0c4269e3d..abdb6433f 100644
--- a/Source/CTest/cmCTestRunTest.cxx
+++ b/Source/CTest/cmCTestRunTest.cxx
@@ -9,7 +9,6 @@
#include "cmSystemTools.h"
#include "cmWorkingDirectory.h"
-#include "cmConfigure.h"
#include "cm_curl.h"
#include "cm_zlib.h"
#include "cmsys/Base64.h"
@@ -25,14 +24,14 @@ cmCTestRunTest::cmCTestRunTest(cmCTestTestHandler* handler)
{
this->CTest = handler->CTest;
this->TestHandler = handler;
- this->TestProcess = CM_NULLPTR;
+ this->TestProcess = nullptr;
this->TestResult.ExecutionTime = 0;
this->TestResult.ReturnValue = 0;
this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
this->TestResult.TestCount = 0;
- this->TestResult.Properties = CM_NULLPTR;
- this->ProcessOutput = "";
- this->CompressedOutput = "";
+ this->TestResult.Properties = nullptr;
+ this->ProcessOutput.clear();
+ this->CompressedOutput.clear();
this->CompressionRatio = 2;
this->StopTimePassed = false;
this->NumberOfRunsLeft = 1; // default to 1 run of the test
@@ -65,12 +64,8 @@ bool cmCTestRunTest::CheckOutput()
// Check for TIMEOUT_AFTER_MATCH property.
if (!this->TestProperties->TimeoutRegularExpressions.empty()) {
- std::vector<
- std::pair<cmsys::RegularExpression, std::string> >::iterator regIt;
- for (regIt = this->TestProperties->TimeoutRegularExpressions.begin();
- regIt != this->TestProperties->TimeoutRegularExpressions.end();
- ++regIt) {
- if (regIt->first.find(this->ProcessOutput.c_str())) {
+ for (auto& reg : this->TestProperties->TimeoutRegularExpressions) {
+ if (reg.first.find(this->ProcessOutput.c_str())) {
cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->GetIndex()
<< ": "
<< "Test timeout changed to "
@@ -164,18 +159,14 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
int res =
started ? this->TestProcess->GetProcessStatus() : cmsysProcess_State_Error;
int retVal = this->TestProcess->GetExitValue();
- std::vector<std::pair<cmsys::RegularExpression, std::string> >::iterator
- passIt;
bool forceFail = false;
bool skipped = false;
bool outputTestErrorsToConsole = false;
if (!this->TestProperties->RequiredRegularExpressions.empty() &&
this->FailedDependencies.empty()) {
bool found = false;
- for (passIt = this->TestProperties->RequiredRegularExpressions.begin();
- passIt != this->TestProperties->RequiredRegularExpressions.end();
- ++passIt) {
- if (passIt->first.find(this->ProcessOutput.c_str())) {
+ for (auto& pass : this->TestProperties->RequiredRegularExpressions) {
+ if (pass.first.find(this->ProcessOutput.c_str())) {
found = true;
reason = "Required regular expression found.";
break;
@@ -186,23 +177,19 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
forceFail = true;
}
reason += "Regex=[";
- for (passIt = this->TestProperties->RequiredRegularExpressions.begin();
- passIt != this->TestProperties->RequiredRegularExpressions.end();
- ++passIt) {
- reason += passIt->second;
+ for (auto& pass : this->TestProperties->RequiredRegularExpressions) {
+ reason += pass.second;
reason += "\n";
}
reason += "]";
}
if (!this->TestProperties->ErrorRegularExpressions.empty() &&
this->FailedDependencies.empty()) {
- for (passIt = this->TestProperties->ErrorRegularExpressions.begin();
- passIt != this->TestProperties->ErrorRegularExpressions.end();
- ++passIt) {
- if (passIt->first.find(this->ProcessOutput.c_str())) {
+ for (auto& pass : this->TestProperties->ErrorRegularExpressions) {
+ if (pass.first.find(this->ProcessOutput.c_str())) {
reason = "Error regular expression found in output.";
reason += " Regex=[";
- reason += passIt->second;
+ reason += pass.second;
reason += "]";
forceFail = true;
break;
@@ -237,6 +224,8 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
} else if (res == cmsysProcess_State_Exception) {
outputTestErrorsToConsole = this->CTest->OutputTestOutputOnTestFailure;
cmCTestLog(this->CTest, HANDLER_OUTPUT, "***Exception: ");
+ this->TestResult.ExceptionStatus =
+ this->TestProcess->GetExitExceptionString();
switch (this->TestProcess->GetExitException()) {
case cmsysProcess_Exception_Fault:
cmCTestLog(this->CTest, HANDLER_OUTPUT, "SegFault");
@@ -255,7 +244,8 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
this->TestResult.Status = cmCTestTestHandler::NUMERICAL;
break;
default:
- cmCTestLog(this->CTest, HANDLER_OUTPUT, "Other");
+ cmCTestLog(this->CTest, HANDLER_OUTPUT,
+ this->TestResult.ExceptionStatus);
this->TestResult.Status = cmCTestTestHandler::OTHER_FAULT;
}
} else if ("Disabled" == this->TestResult.CompletionStatus) {
@@ -436,7 +426,7 @@ bool cmCTestRunTest::StartTest(size_t total)
this->TestResult.Path = this->TestProperties->Directory;
this->TestProcess = new cmProcess;
this->TestResult.Output = "Disabled";
- this->TestResult.FullCommandLine = "";
+ this->TestResult.FullCommandLine.clear();
return false;
}
@@ -455,15 +445,13 @@ bool cmCTestRunTest::StartTest(size_t total)
if (!this->FailedDependencies.empty()) {
this->TestProcess = new cmProcess;
std::string msg = "Failed test dependencies:";
- for (std::set<std::string>::const_iterator it =
- this->FailedDependencies.begin();
- it != this->FailedDependencies.end(); ++it) {
- msg += " " + *it;
+ for (std::string const& failedDep : this->FailedDependencies) {
+ msg += " " + failedDep;
}
*this->TestHandler->LogFile << msg << std::endl;
cmCTestLog(this->CTest, HANDLER_OUTPUT, msg << std::endl);
this->TestResult.Output = msg;
- this->TestResult.FullCommandLine = "";
+ this->TestResult.FullCommandLine.clear();
this->TestResult.CompletionStatus = "Fixture dependency failed";
this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
return false;
@@ -483,18 +471,14 @@ bool cmCTestRunTest::StartTest(size_t total)
*this->TestHandler->LogFile << msg << std::endl;
cmCTestLog(this->CTest, ERROR_MESSAGE, msg << std::endl);
this->TestResult.Output = msg;
- this->TestResult.FullCommandLine = "";
+ this->TestResult.FullCommandLine.clear();
this->TestResult.CompletionStatus = "Missing Configuration";
this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
return false;
}
// Check if all required files exist
- for (std::vector<std::string>::iterator i =
- this->TestProperties->RequiredFiles.begin();
- i != this->TestProperties->RequiredFiles.end(); ++i) {
- std::string file = *i;
-
+ for (std::string const& file : this->TestProperties->RequiredFiles) {
if (!cmSystemTools::FileExists(file.c_str())) {
// Required file was not found
this->TestProcess = new cmProcess;
@@ -503,14 +487,14 @@ bool cmCTestRunTest::StartTest(size_t total)
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Unable to find required file: " << file << std::endl);
this->TestResult.Output = "Unable to find required file: " + file;
- this->TestResult.FullCommandLine = "";
+ this->TestResult.FullCommandLine.clear();
this->TestResult.CompletionStatus = "Required Files Missing";
this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
return false;
}
}
// log and return if we did not find the executable
- if (this->ActualCommand == "") {
+ if (this->ActualCommand.empty()) {
// if the command was not found create a TestResult object
// that has that information
this->TestProcess = new cmProcess;
@@ -519,7 +503,7 @@ bool cmCTestRunTest::StartTest(size_t total)
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Unable to find executable: " << args[1] << std::endl);
this->TestResult.Output = "Unable to find executable: " + args[1];
- this->TestResult.FullCommandLine = "";
+ this->TestResult.FullCommandLine.clear();
this->TestResult.CompletionStatus = "Unable to find executable";
this->TestResult.Status = cmCTestTestHandler::NOT_RUN;
return false;
@@ -558,10 +542,9 @@ void cmCTestRunTest::ComputeArguments()
// Prepends memcheck args to our command string
this->TestHandler->GenerateTestCommand(this->Arguments, this->Index);
- for (std::vector<std::string>::iterator i = this->Arguments.begin();
- i != this->Arguments.end(); ++i) {
+ for (std::string const& arg : this->Arguments) {
testCommand += " \"";
- testCommand += *i;
+ testCommand += arg;
testCommand += "\"";
}
@@ -585,10 +568,8 @@ void cmCTestRunTest::ComputeArguments()
<< ": "
<< "Environment variables: " << std::endl);
}
- for (std::vector<std::string>::const_iterator e =
- this->TestProperties->Environment.begin();
- e != this->TestProperties->Environment.end(); ++e) {
- cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->Index << ": " << *e
+ for (std::string const& env : this->TestProperties->Environment) {
+ cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, this->Index << ": " << env
<< std::endl);
}
}
@@ -614,11 +595,11 @@ double cmCTestRunTest::ResolveTimeout()
{
double timeout = this->TestProperties->Timeout;
- if (this->CTest->GetStopTime() == "") {
+ if (this->CTest->GetStopTime().empty()) {
return timeout;
}
struct tm* lctime;
- time_t current_time = time(CM_NULLPTR);
+ time_t current_time = time(nullptr);
lctime = gmtime(&current_time);
int gm_hour = lctime->tm_hour;
time_t gm_time = mktime(lctime);
@@ -762,9 +743,8 @@ void cmCTestRunTest::WriteLogOutputTop(size_t completed, size_t total)
<< std::endl;
*this->TestHandler->LogFile << "Command: \"" << this->ActualCommand << "\"";
- for (std::vector<std::string>::iterator i = this->Arguments.begin();
- i != this->Arguments.end(); ++i) {
- *this->TestHandler->LogFile << " \"" << *i << "\"";
+ for (std::string const& arg : this->Arguments) {
+ *this->TestHandler->LogFile << " \"" << arg << "\"";
}
*this->TestHandler->LogFile
<< std::endl
diff --git a/Source/CTest/cmCTestSVN.cxx b/Source/CTest/cmCTestSVN.cxx
index f60f78c21..ce9622492 100644
--- a/Source/CTest/cmCTestSVN.cxx
+++ b/Source/CTest/cmCTestSVN.cxx
@@ -59,7 +59,7 @@ private:
cmsys::RegularExpression RegexRev;
cmsys::RegularExpression RegexURL;
cmsys::RegularExpression RegexRoot;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexRev.find(this->Line)) {
this->Rev = this->RegexRev.match(1);
@@ -103,10 +103,7 @@ bool cmCTestSVN::NoteOldRevision()
return false;
}
- std::vector<SVNInfo>::iterator itbeg = this->Repositories.begin();
- std::vector<SVNInfo>::iterator itend = this->Repositories.end();
- for (; itbeg != itend; itbeg++) {
- SVNInfo& svninfo = *itbeg;
+ for (SVNInfo& svninfo : this->Repositories) {
svninfo.OldRevision = this->LoadInfo(svninfo);
this->Log << "Revision for repository '" << svninfo.LocalPath
<< "' before update: " << svninfo.OldRevision << "\n";
@@ -127,10 +124,7 @@ bool cmCTestSVN::NoteNewRevision()
return false;
}
- std::vector<SVNInfo>::iterator itbeg = this->Repositories.begin();
- std::vector<SVNInfo>::iterator itend = this->Repositories.end();
- for (; itbeg != itend; itbeg++) {
- SVNInfo& svninfo = *itbeg;
+ for (SVNInfo& svninfo : this->Repositories) {
svninfo.NewRevision = this->LoadInfo(svninfo);
this->Log << "Revision for repository '" << svninfo.LocalPath
<< "' after update: " << svninfo.NewRevision << "\n";
@@ -205,7 +199,7 @@ private:
cmCTestSVN* SVN;
cmsys::RegularExpression RegexUpdate;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexUpdate.find(this->Line)) {
this->DoPath(this->RegexUpdate.match(1)[0],
@@ -257,9 +251,8 @@ bool cmCTestSVN::UpdateImpl()
std::vector<char const*> svn_update;
svn_update.push_back("update");
- for (std::vector<std::string>::const_iterator ai = args.begin();
- ai != args.end(); ++ai) {
- svn_update.push_back(ai->c_str());
+ for (std::string const& arg : args) {
+ svn_update.push_back(arg.c_str());
}
UpdateParser out(this, "up-out> ");
@@ -285,12 +278,11 @@ bool cmCTestSVN::RunSVNCommand(std::vector<char const*> const& parameters,
std::vector<std::string> parsedUserOptions =
cmSystemTools::ParseArguments(userOptions.c_str());
- for (std::vector<std::string>::iterator i = parsedUserOptions.begin();
- i != parsedUserOptions.end(); ++i) {
- args.push_back(i->c_str());
+ for (std::string const& opt : parsedUserOptions) {
+ args.push_back(opt.c_str());
}
- args.push_back(CM_NULLPTR);
+ args.push_back(nullptr);
if (strcmp(parameters[0], "update") == 0) {
return RunUpdateCommand(&args[0], out, err);
@@ -309,7 +301,7 @@ public:
{
this->InitializeParser();
}
- ~LogParser() CM_OVERRIDE { this->CleanupParser(); }
+ ~LogParser() override { this->CleanupParser(); }
private:
cmCTestSVN* SVN;
cmCTestSVN::SVNInfo& SVNRepo;
@@ -321,14 +313,14 @@ private:
Change CurChange;
std::vector<char> CData;
- bool ProcessChunk(const char* data, int length) CM_OVERRIDE
+ bool ProcessChunk(const char* data, int length) override
{
this->OutputLogger::ProcessChunk(data, length);
this->ParseChunk(data, length);
return true;
}
- void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
+ void StartElement(const std::string& name, const char** atts) override
{
this->CData.clear();
if (name == "logentry") {
@@ -346,12 +338,12 @@ private:
}
}
- void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
+ void CharacterDataHandler(const char* data, int length) override
{
this->CData.insert(this->CData.end(), data, data + length);
}
- void EndElement(const std::string& name) CM_OVERRIDE
+ void EndElement(const std::string& name) override
{
if (name == "logentry") {
this->SVN->DoRevisionSVN(this->Rev, this->Changes);
@@ -370,7 +362,7 @@ private:
this->CData.clear();
}
- void ReportError(int /*line*/, int /*column*/, const char* msg) CM_OVERRIDE
+ void ReportError(int /*line*/, int /*column*/, const char* msg) override
{
this->SVN->Log << "Error parsing svn log xml: " << msg << "\n";
}
@@ -380,10 +372,7 @@ bool cmCTestSVN::LoadRevisions()
{
bool result = true;
// Get revisions for all the external repositories
- std::vector<SVNInfo>::iterator itbeg = this->Repositories.begin();
- std::vector<SVNInfo>::iterator itend = this->Repositories.end();
- for (; itbeg != itend; itbeg++) {
- SVNInfo& svninfo = *itbeg;
+ for (SVNInfo& svninfo : this->Repositories) {
result = this->LoadRevisions(svninfo) && result;
}
return result;
@@ -421,7 +410,7 @@ void cmCTestSVN::DoRevisionSVN(Revision const& revision,
// Ignore changes in the old revision for external repositories
if (revision.Rev == revision.SVNInfo->OldRevision &&
- revision.SVNInfo->LocalPath != "") {
+ !revision.SVNInfo->LocalPath.empty()) {
return;
}
@@ -441,7 +430,7 @@ public:
private:
cmCTestSVN* SVN;
cmsys::RegularExpression RegexStatus;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexStatus.find(this->Line)) {
this->DoPath(this->RegexStatus.match(1)[0],
@@ -507,7 +496,7 @@ public:
private:
cmCTestSVN* SVN;
cmsys::RegularExpression RegexExternal;
- bool ProcessLine() CM_OVERRIDE
+ bool ProcessLine() override
{
if (this->RegexExternal.find(this->Line)) {
this->DoPath(this->RegexExternal.match(1));
diff --git a/Source/CTest/cmCTestSVN.h b/Source/CTest/cmCTestSVN.h
index 46b077835..dbc7fdef6 100644
--- a/Source/CTest/cmCTestSVN.h
+++ b/Source/CTest/cmCTestSVN.h
@@ -3,7 +3,7 @@
#ifndef cmCTestSVN_h
#define cmCTestSVN_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestGlobalVC.h"
@@ -24,14 +24,14 @@ public:
/** Construct with a CTest instance and update log stream. */
cmCTestSVN(cmCTest* ctest, std::ostream& log);
- ~cmCTestSVN() CM_OVERRIDE;
+ ~cmCTestSVN() override;
private:
// Implement cmCTestVC internal API.
- void CleanupImpl() CM_OVERRIDE;
- bool NoteOldRevision() CM_OVERRIDE;
- bool NoteNewRevision() CM_OVERRIDE;
- bool UpdateImpl() CM_OVERRIDE;
+ void CleanupImpl() override;
+ bool NoteOldRevision() override;
+ bool NoteNewRevision() override;
+ bool UpdateImpl() override;
bool RunSVNCommand(std::vector<char const*> const& parameters,
OutputParser* out, OutputParser* err);
@@ -77,8 +77,8 @@ private:
std::string LoadInfo(SVNInfo& svninfo);
bool LoadRepositories();
- bool LoadModifications() CM_OVERRIDE;
- bool LoadRevisions() CM_OVERRIDE;
+ bool LoadModifications() override;
+ bool LoadRevisions() override;
bool LoadRevisions(SVNInfo& svninfo);
void GuessBase(SVNInfo& svninfo, std::vector<Change> const& changes);
@@ -86,7 +86,7 @@ private:
void DoRevisionSVN(Revision const& revision,
std::vector<Change> const& changes);
- void WriteXMLGlobal(cmXMLWriter& xml) CM_OVERRIDE;
+ void WriteXMLGlobal(cmXMLWriter& xml) override;
class ExternalParser;
// Parsing helper classes.
diff --git a/Source/CTest/cmCTestScriptHandler.cxx b/Source/CTest/cmCTestScriptHandler.cxx
index 1d29dfac2..fdd9622af 100644
--- a/Source/CTest/cmCTestScriptHandler.cxx
+++ b/Source/CTest/cmCTestScriptHandler.cxx
@@ -52,9 +52,9 @@ class cmCTestScriptFunctionBlocker : public cmFunctionBlocker
{
public:
cmCTestScriptFunctionBlocker() {}
- ~cmCTestScriptFunctionBlocker() CM_OVERRIDE {}
+ ~cmCTestScriptFunctionBlocker() override {}
bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf,
- cmExecutionStatus& /*status*/) CM_OVERRIDE;
+ cmExecutionStatus& /*status*/) override;
// virtual bool ShouldRemove(const cmListFileFunction& lff, cmMakefile &mf);
// virtual void ScopeEnded(cmMakefile &mf);
@@ -75,9 +75,9 @@ cmCTestScriptHandler::cmCTestScriptHandler()
this->Backup = false;
this->EmptyBinDir = false;
this->EmptyBinDirOnce = false;
- this->Makefile = CM_NULLPTR;
- this->CMake = CM_NULLPTR;
- this->GlobalGenerator = CM_NULLPTR;
+ this->Makefile = nullptr;
+ this->CMake = nullptr;
+ this->GlobalGenerator = nullptr;
this->ScriptStartTime = 0;
@@ -93,18 +93,18 @@ void cmCTestScriptHandler::Initialize()
this->EmptyBinDir = false;
this->EmptyBinDirOnce = false;
- this->SourceDir = "";
- this->BinaryDir = "";
- this->BackupSourceDir = "";
- this->BackupBinaryDir = "";
- this->CTestRoot = "";
- this->CVSCheckOut = "";
- this->CTestCmd = "";
- this->UpdateCmd = "";
- this->CTestEnv = "";
- this->InitialCache = "";
- this->CMakeCmd = "";
- this->CMOutFile = "";
+ this->SourceDir.clear();
+ this->BinaryDir.clear();
+ this->BackupSourceDir.clear();
+ this->BackupBinaryDir.clear();
+ this->CTestRoot.clear();
+ this->CVSCheckOut.clear();
+ this->CTestCmd.clear();
+ this->UpdateCmd.clear();
+ this->CTestEnv.clear();
+ this->InitialCache.clear();
+ this->CMakeCmd.clear();
+ this->CMOutFile.clear();
this->ExtraUpdates.clear();
this->MinimumInterval = 20 * 60;
@@ -114,10 +114,10 @@ void cmCTestScriptHandler::Initialize()
this->ScriptStartTime = 0;
delete this->Makefile;
- this->Makefile = CM_NULLPTR;
+ this->Makefile = nullptr;
delete this->GlobalGenerator;
- this->GlobalGenerator = CM_NULLPTR;
+ this->GlobalGenerator = nullptr;
delete this->CMake;
}
@@ -193,7 +193,7 @@ int cmCTestScriptHandler::ExecuteScript(const std::string& total_script_arg)
for (size_t i = 1; i < initArgs.size(); ++i) {
argv.push_back(initArgs[i].c_str());
}
- argv.push_back(CM_NULLPTR);
+ argv.push_back(nullptr);
// Now create process object
cmsysProcess* cp = cmsysProcess_New();
@@ -219,7 +219,7 @@ int cmCTestScriptHandler::ExecuteScript(const std::string& total_script_arg)
}
// Properly handle output of the build command
- cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ cmsysProcess_WaitForExit(cp, nullptr);
int result = cmsysProcess_GetState(cp);
int retVal = 0;
bool failed = false;
@@ -245,10 +245,9 @@ int cmCTestScriptHandler::ExecuteScript(const std::string& total_script_arg)
std::ostringstream message;
message << "Error running command: [";
message << result << "] ";
- for (std::vector<const char*>::iterator i = argv.begin(); i != argv.end();
- ++i) {
- if (*i) {
- message << *i << " ";
+ for (const char* arg : argv) {
+ if (arg) {
+ message << arg << " ";
}
}
cmCTestLog(this->CTest, ERROR_MESSAGE, message.str() << argv[0]
@@ -377,9 +376,8 @@ int cmCTestScriptHandler::ReadInScript(const std::string& total_script_arg)
// Add definitions of variables passed in on the command line:
const std::map<std::string, std::string>& defs =
this->CTest->GetDefinitions();
- for (std::map<std::string, std::string>::const_iterator it = defs.begin();
- it != defs.end(); ++it) {
- this->Makefile->AddDefinition(it->first, it->second.c_str());
+ for (auto const& d : defs) {
+ this->Makefile->AddDefinition(d.first, d.second.c_str());
}
// finally read in the script
@@ -394,7 +392,7 @@ int cmCTestScriptHandler::ReadInScript(const std::string& total_script_arg)
return 0;
}
-// extract variabels from the script to set ivars
+// extract variables from the script to set ivars
int cmCTestScriptHandler::ExtractVariables()
{
// Temporary variables
@@ -595,7 +593,7 @@ int cmCTestScriptHandler::CheckOutSourceDir()
if (!cmSystemTools::FileExists(this->SourceDir.c_str()) &&
!this->CVSCheckOut.empty()) {
// we must now checkout the src dir
- output = "";
+ output.clear();
cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Run cvs: " << this->CVSCheckOut << std::endl);
res = cmSystemTools::RunSingleCommand(
@@ -654,15 +652,14 @@ int cmCTestScriptHandler::PerformExtraUpdates()
// do an initial cvs update as required
command = this->UpdateCmd;
- std::vector<std::string>::iterator it;
- for (it = this->ExtraUpdates.begin(); it != this->ExtraUpdates.end(); ++it) {
+ for (std::string const& eu : this->ExtraUpdates) {
std::vector<std::string> cvsArgs;
- cmSystemTools::ExpandListArgument(*it, cvsArgs);
+ cmSystemTools::ExpandListArgument(eu, cvsArgs);
if (cvsArgs.size() == 2) {
std::string fullCommand = command;
fullCommand += " update ";
fullCommand += cvsArgs[1];
- output = "";
+ output.clear();
retVal = 0;
cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Run Update: " << fullCommand << std::endl);
@@ -670,7 +667,7 @@ int cmCTestScriptHandler::PerformExtraUpdates()
fullCommand.c_str(), &output, &output, &retVal, cvsArgs[0].c_str(),
this->HandlerVerbose, 0 /*this->TimeOut*/);
if (!res || retVal != 0) {
- cmSystemTools::Error("Unable to perform extra updates:\n", it->c_str(),
+ cmSystemTools::Error("Unable to perform extra updates:\n", eu.c_str(),
"\nWith output:\n", output.c_str());
return 0;
}
@@ -765,7 +762,7 @@ int cmCTestScriptHandler::RunConfigurationDashboard()
command = this->CMakeCmd;
command += " \"";
command += this->SourceDir;
- output = "";
+ output.clear();
command += "\"";
retVal = 0;
cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
@@ -803,9 +800,9 @@ int cmCTestScriptHandler::RunConfigurationDashboard()
std::vector<std::string> ctestCommands;
cmSystemTools::ExpandListArgument(this->CTestCmd, ctestCommands);
// for each variable/argument do a putenv
- for (unsigned i = 0; i < ctestCommands.size(); ++i) {
- command = ctestCommands[i];
- output = "";
+ for (std::string const& ctestCommand : ctestCommands) {
+ command = ctestCommand;
+ output.clear();
retVal = 0;
cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Run ctest command: " << command << std::endl);
@@ -852,7 +849,7 @@ bool cmCTestScriptHandler::WriteInitialCache(const char* directory,
return false;
}
- if (text != CM_NULLPTR) {
+ if (text != nullptr) {
fout.write(text, strlen(text));
}
diff --git a/Source/CTest/cmCTestScriptHandler.h b/Source/CTest/cmCTestScriptHandler.h
index 667870260..b6cd97b73 100644
--- a/Source/CTest/cmCTestScriptHandler.h
+++ b/Source/CTest/cmCTestScriptHandler.h
@@ -3,7 +3,7 @@
#ifndef cmCTestScriptHandler_h
#define cmCTestScriptHandler_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestGenericHandler.h"
@@ -65,7 +65,7 @@ public:
/**
* Run a dashboard using a specified confiuration script
*/
- int ProcessHandler() CM_OVERRIDE;
+ int ProcessHandler() override;
/*
* Run a script
@@ -98,9 +98,9 @@ public:
double GetRemainingTimeAllowed();
cmCTestScriptHandler();
- ~cmCTestScriptHandler() CM_OVERRIDE;
+ ~cmCTestScriptHandler() override;
- void Initialize() CM_OVERRIDE;
+ void Initialize() override;
void CreateCMake();
cmake* GetCMake() { return this->CMake; }
diff --git a/Source/CTest/cmCTestSleepCommand.h b/Source/CTest/cmCTestSleepCommand.h
index f0b5f1eeb..5cd185a81 100644
--- a/Source/CTest/cmCTestSleepCommand.h
+++ b/Source/CTest/cmCTestSleepCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestSleepCommand_h
#define cmCTestSleepCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestCommand.h"
@@ -27,7 +27,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestSleepCommand* ni = new cmCTestSleepCommand;
ni->CTest = this->CTest;
@@ -40,7 +40,7 @@ public:
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/CTest/cmCTestStartCommand.cxx b/Source/CTest/cmCTestStartCommand.cxx
index 01a874b45..4f0d87b1b 100644
--- a/Source/CTest/cmCTestStartCommand.cxx
+++ b/Source/CTest/cmCTestStartCommand.cxx
@@ -29,12 +29,12 @@ bool cmCTestStartCommand::InitialPass(std::vector<std::string> const& args,
size_t cnt = 0;
const char* smodel = args[cnt].c_str();
- const char* src_dir = CM_NULLPTR;
- const char* bld_dir = CM_NULLPTR;
+ const char* src_dir = nullptr;
+ const char* bld_dir = nullptr;
cnt++;
- this->CTest->SetSpecificTrack(CM_NULLPTR);
+ this->CTest->SetSpecificTrack(nullptr);
if (cnt < args.size() - 1) {
if (args[cnt] == "TRACK") {
cnt++;
diff --git a/Source/CTest/cmCTestStartCommand.h b/Source/CTest/cmCTestStartCommand.h
index b4943f92d..542f27c13 100644
--- a/Source/CTest/cmCTestStartCommand.h
+++ b/Source/CTest/cmCTestStartCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestStartCommand_h
#define cmCTestStartCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestCommand.h"
@@ -27,7 +27,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestStartCommand* ni = new cmCTestStartCommand;
ni->CTest = this->CTest;
@@ -42,7 +42,7 @@ public:
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
/**
* Will this invocation of ctest_start create a new TAG file?
diff --git a/Source/CTest/cmCTestSubmitCommand.cxx b/Source/CTest/cmCTestSubmitCommand.cxx
index 409eb51fc..1794ca64b 100644
--- a/Source/CTest/cmCTestSubmitCommand.cxx
+++ b/Source/CTest/cmCTestSubmitCommand.cxx
@@ -86,7 +86,7 @@ cmCTestGenericHandler* cmCTestSubmitCommand::InitializeHandler()
extraFiles.end());
if (!this->CTest->SubmitExtraFiles(newExtraFiles)) {
this->SetError("problem submitting extra files.");
- return CM_NULLPTR;
+ return nullptr;
}
}
@@ -94,7 +94,7 @@ cmCTestGenericHandler* cmCTestSubmitCommand::InitializeHandler()
this->CTest->GetInitializedHandler("submit");
if (!handler) {
this->SetError("internal CTest error. Cannot instantiate submit handler");
- return CM_NULLPTR;
+ return nullptr;
}
// If no FILES or PARTS given, *all* PARTS are submitted by default.
diff --git a/Source/CTest/cmCTestSubmitCommand.h b/Source/CTest/cmCTestSubmitCommand.h
index cf65cdc8d..c4b84ce9f 100644
--- a/Source/CTest/cmCTestSubmitCommand.h
+++ b/Source/CTest/cmCTestSubmitCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestSubmitCommand_h
#define cmCTestSubmitCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTest.h"
#include "cmCTestHandlerCommand.h"
@@ -38,7 +38,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestSubmitCommand* ni = new cmCTestSubmitCommand;
ni->CTest = this->CTest;
@@ -47,20 +47,20 @@ public:
}
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
/**
* The name of the command as specified in CMakeList.txt.
*/
- std::string GetName() const CM_OVERRIDE { return "ctest_submit"; }
+ std::string GetName() const override { return "ctest_submit"; }
typedef cmCTestHandlerCommand Superclass;
protected:
- cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
+ cmCTestGenericHandler* InitializeHandler() override;
- bool CheckArgumentKeyword(std::string const& arg) CM_OVERRIDE;
- bool CheckArgumentValue(std::string const& arg) CM_OVERRIDE;
+ bool CheckArgumentKeyword(std::string const& arg) override;
+ bool CheckArgumentValue(std::string const& arg) override;
enum
{
diff --git a/Source/CTest/cmCTestSubmitHandler.cxx b/Source/CTest/cmCTestSubmitHandler.cxx
index 8d62fa156..e51e16843 100644
--- a/Source/CTest/cmCTestSubmitHandler.cxx
+++ b/Source/CTest/cmCTestSubmitHandler.cxx
@@ -13,6 +13,7 @@
#include "cmCTest.h"
#include "cmCTestCurl.h"
#include "cmCTestScriptHandler.h"
+#include "cmCryptoHash.h"
#include "cmCurl.h"
#include "cmGeneratedFileStream.h"
#include "cmProcessOutput.h"
@@ -37,7 +38,7 @@ class cmCTestSubmitHandler::ResponseParser : public cmXMLParser
{
public:
ResponseParser() { this->Status = STATUS_OK; }
- ~ResponseParser() CM_OVERRIDE {}
+ ~ResponseParser() override {}
public:
enum StatusType
@@ -65,17 +66,17 @@ private:
}
void StartElement(const std::string& /*name*/,
- const char** /*atts*/) CM_OVERRIDE
+ const char** /*atts*/) override
{
this->CurrentValue.clear();
}
- void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
+ void CharacterDataHandler(const char* data, int length) override
{
this->CurrentValue.insert(this->CurrentValue.end(), data, data + length);
}
- void EndElement(const std::string& name) CM_OVERRIDE
+ void EndElement(const std::string& name) override
{
if (name == "status") {
std::string status = cmSystemTools::UpperCase(this->GetCurrentValue());
@@ -99,7 +100,7 @@ private:
static size_t cmCTestSubmitHandlerWriteMemoryCallback(void* ptr, size_t size,
size_t nmemb, void* data)
{
- int realsize = (int)(size * nmemb);
+ int realsize = static_cast<int>(size * nmemb);
cmCTestSubmitHandlerVectorOfChar* vec =
static_cast<cmCTestSubmitHandlerVectorOfChar*>(data);
@@ -139,12 +140,12 @@ void cmCTestSubmitHandler::Initialize()
this->HasWarnings = false;
this->HasErrors = false;
this->Superclass::Initialize();
- this->HTTPProxy = "";
+ this->HTTPProxy.clear();
this->HTTPProxyType = 0;
- this->HTTPProxyAuth = "";
- this->FTPProxy = "";
+ this->HTTPProxyAuth.clear();
+ this->FTPProxy.clear();
this->FTPProxyType = 0;
- this->LogFile = CM_NULLPTR;
+ this->LogFile = nullptr;
this->Files.clear();
}
@@ -161,8 +162,7 @@ bool cmCTestSubmitHandler::SubmitUsingFTP(const std::string& localprefix,
/* In windows, this will init the winsock stuff */
::curl_global_init(CURL_GLOBAL_ALL);
- cmCTest::SetOfStrings::const_iterator file;
- for (file = files.begin(); file != files.end(); ++file) {
+ for (std::string const& file : files) {
/* get a curl handle */
curl = curl_easy_init();
if (curl) {
@@ -191,12 +191,12 @@ bool cmCTestSubmitHandler::SubmitUsingFTP(const std::string& localprefix,
::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
- std::string local_file = *file;
+ std::string local_file = file;
if (!cmSystemTools::FileExists(local_file.c_str())) {
- local_file = localprefix + "/" + *file;
+ local_file = localprefix + "/" + file;
}
std::string upload_as =
- url + "/" + remoteprefix + cmSystemTools::GetFilenameName(*file);
+ url + "/" + remoteprefix + cmSystemTools::GetFilenameName(file);
if (!cmSystemTools::FileExists(local_file.c_str())) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
@@ -238,8 +238,8 @@ bool cmCTestSubmitHandler::SubmitUsingFTP(const std::string& localprefix,
/* we pass our 'chunk' struct to the callback function */
cmCTestSubmitHandlerVectorOfChar chunk;
cmCTestSubmitHandlerVectorOfChar chunkDebug;
- ::curl_easy_setopt(curl, CURLOPT_FILE, (void*)&chunk);
- ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void*)&chunkDebug);
+ ::curl_easy_setopt(curl, CURLOPT_FILE, &chunk);
+ ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
// Now run off and do what you've been told!
res = ::curl_easy_perform(curl);
@@ -303,15 +303,14 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
char error_buffer[1024];
// Set Content-Type to satisfy fussy modsecurity rules.
struct curl_slist* headers =
- ::curl_slist_append(CM_NULLPTR, "Content-Type: text/xml");
+ ::curl_slist_append(nullptr, "Content-Type: text/xml");
// Add any additional headers that the user specified.
- for (std::vector<std::string>::const_iterator h = this->HttpHeaders.begin();
- h != this->HttpHeaders.end(); ++h) {
+ for (std::string const& h : this->HttpHeaders) {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
- " Add HTTP Header: \"" << *h << "\"" << std::endl,
+ " Add HTTP Header: \"" << h << "\"" << std::endl,
this->Quiet);
- headers = ::curl_slist_append(headers, h->c_str());
+ headers = ::curl_slist_append(headers, h.c_str());
}
/* In windows, this will init the winsock stuff */
@@ -322,18 +321,15 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
cmSystemTools::ExpandListArgument(curlopt, args);
bool verifyPeerOff = false;
bool verifyHostOff = false;
- for (std::vector<std::string>::iterator i = args.begin(); i != args.end();
- ++i) {
- if (*i == "CURLOPT_SSL_VERIFYPEER_OFF") {
+ for (std::string const& arg : args) {
+ if (arg == "CURLOPT_SSL_VERIFYPEER_OFF") {
verifyPeerOff = true;
}
- if (*i == "CURLOPT_SSL_VERIFYHOST_OFF") {
+ if (arg == "CURLOPT_SSL_VERIFYHOST_OFF") {
verifyHostOff = true;
}
}
- std::string::size_type kk;
- cmCTest::SetOfStrings::const_iterator file;
- for (file = files.begin(); file != files.end(); ++file) {
+ for (std::string const& file : files) {
/* get a curl handle */
curl = curl_easy_init();
if (curl) {
@@ -388,19 +384,18 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
- std::string local_file = *file;
+ std::string local_file = file;
if (!cmSystemTools::FileExists(local_file.c_str())) {
- local_file = localprefix + "/" + *file;
+ local_file = localprefix + "/" + file;
}
std::string remote_file =
- remoteprefix + cmSystemTools::GetFilenameName(*file);
+ remoteprefix + cmSystemTools::GetFilenameName(file);
*this->LogFile << "\tUpload file: " << local_file << " to "
<< remote_file << std::endl;
std::string ofile;
- for (kk = 0; kk < remote_file.size(); kk++) {
- char c = remote_file[kk];
+ for (char c : remote_file) {
char hexCh[4] = { 0, 0, 0, 0 };
hexCh[0] = c;
switch (c) {
@@ -412,7 +407,7 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
case ' ':
case '=':
case '%':
- sprintf(hexCh, "%%%02X", (int)c);
+ sprintf(hexCh, "%%%02X", static_cast<int>(c));
ofile.append(hexCh);
break;
default:
@@ -428,10 +423,8 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
if (cmSystemTools::IsOn(this->GetOption("InternalTest"))) {
upload_as += "bad_md5sum";
} else {
- char md5[33];
- cmSystemTools::ComputeFileMD5(local_file, md5);
- md5[32] = 0;
- upload_as += md5;
+ upload_as +=
+ cmSystemTools::ComputeFileHash(local_file, cmCryptoHash::AlgoMD5);
}
if (!cmSystemTools::FileExists(local_file.c_str())) {
@@ -472,8 +465,8 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
/* we pass our 'chunk' struct to the callback function */
cmCTestSubmitHandlerVectorOfChar chunk;
cmCTestSubmitHandlerVectorOfChar chunkDebug;
- ::curl_easy_setopt(curl, CURLOPT_FILE, (void*)&chunk);
- ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void*)&chunkDebug);
+ ::curl_easy_setopt(curl, CURLOPT_FILE, &chunk);
+ ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
// Now run off and do what you've been told!
res = ::curl_easy_perform(curl);
@@ -496,18 +489,18 @@ bool cmCTestSubmitHandler::SubmitUsingHTTP(const std::string& localprefix,
// If curl failed for any reason, or checksum fails, wait and retry
//
if (res != CURLE_OK || this->HasErrors) {
- std::string retryDelay = this->GetOption("RetryDelay") == CM_NULLPTR
+ std::string retryDelay = this->GetOption("RetryDelay") == nullptr
? ""
: this->GetOption("RetryDelay");
- std::string retryCount = this->GetOption("RetryCount") == CM_NULLPTR
+ std::string retryCount = this->GetOption("RetryCount") == nullptr
? ""
: this->GetOption("RetryCount");
- int delay = retryDelay == ""
+ int delay = retryDelay.empty()
? atoi(this->CTest->GetCTestConfiguration("CTestSubmitRetryDelay")
.c_str())
: atoi(retryDelay.c_str());
- int count = retryCount == ""
+ int count = retryCount.empty()
? atoi(this->CTest->GetCTestConfiguration("CTestSubmitRetryCount")
.c_str())
: atoi(retryCount.c_str());
@@ -630,8 +623,7 @@ bool cmCTestSubmitHandler::TriggerUsingHTTP(const std::set<std::string>& files,
/* In windows, this will init the winsock stuff */
::curl_global_init(CURL_GLOBAL_ALL);
- cmCTest::SetOfStrings::const_iterator file;
- for (file = files.begin(); file != files.end(); ++file) {
+ for (std::string const& file : files) {
/* get a curl handle */
curl = curl_easy_init();
if (curl) {
@@ -668,14 +660,12 @@ bool cmCTestSubmitHandler::TriggerUsingHTTP(const std::set<std::string>& files,
/* we pass our 'chunk' struct to the callback function */
cmCTestSubmitHandlerVectorOfChar chunk;
cmCTestSubmitHandlerVectorOfChar chunkDebug;
- ::curl_easy_setopt(curl, CURLOPT_FILE, (void*)&chunk);
- ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void*)&chunkDebug);
+ ::curl_easy_setopt(curl, CURLOPT_FILE, &chunk);
+ ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
- std::string rfile = remoteprefix + cmSystemTools::GetFilenameName(*file);
+ std::string rfile = remoteprefix + cmSystemTools::GetFilenameName(file);
std::string ofile;
- std::string::iterator kk;
- for (kk = rfile.begin(); kk < rfile.end(); ++kk) {
- char c = *kk;
+ for (char c : rfile) {
char hexCh[4] = { 0, 0, 0, 0 };
hexCh[0] = c;
switch (c) {
@@ -687,7 +677,7 @@ bool cmCTestSubmitHandler::TriggerUsingHTTP(const std::set<std::string>& files,
case ' ':
case '=':
case '%':
- sprintf(hexCh, "%%%02X", (int)c);
+ sprintf(hexCh, "%%%02X", static_cast<int>(c));
ofile.append(hexCh);
break;
default:
@@ -765,7 +755,7 @@ bool cmCTestSubmitHandler::SubmitUsingSCP(const std::string& scp_command,
argv.push_back(scp_command.c_str()); // Scp command
argv.push_back(scp_command.c_str()); // Dummy string for file
argv.push_back(scp_command.c_str()); // Dummy string for remote url
- argv.push_back(CM_NULLPTR);
+ argv.push_back(nullptr);
cmsysProcess* cp = cmsysProcess_New();
cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);
@@ -773,16 +763,15 @@ bool cmCTestSubmitHandler::SubmitUsingSCP(const std::string& scp_command,
int problems = 0;
- cmCTest::SetOfStrings::const_iterator file;
- for (file = files.begin(); file != files.end(); ++file) {
+ for (std::string const& file : files) {
int retVal;
std::string lfname = localprefix;
cmSystemTools::ConvertToUnixSlashes(lfname);
- lfname += "/" + *file;
+ lfname += "/" + file;
lfname = cmSystemTools::ConvertToOutputPath(lfname.c_str());
argv[1] = lfname.c_str();
- std::string rfname = url + "/" + remoteprefix + *file;
+ std::string rfname = url + "/" + remoteprefix + file;
argv[2] = rfname.c_str();
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "Execute \""
<< argv[0] << "\" \"" << argv[1] << "\" \"" << argv[2]
@@ -798,7 +787,7 @@ bool cmCTestSubmitHandler::SubmitUsingSCP(const std::string& scp_command,
cmProcessOutput processOutput;
std::string strdata;
- while (cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
+ while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
processOutput.DecodeText(data, length, strdata);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
cmCTestLogWrite(strdata.c_str(), strdata.size()),
@@ -811,7 +800,7 @@ bool cmCTestSubmitHandler::SubmitUsingSCP(const std::string& scp_command,
this->Quiet);
}
- cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ cmsysProcess_WaitForExit(cp, nullptr);
int result = cmsysProcess_GetState(cp);
@@ -865,12 +854,11 @@ bool cmCTestSubmitHandler::SubmitUsingCP(const std::string& localprefix,
return false;
}
- cmCTest::SetOfStrings::const_iterator file;
- for (file = files.begin(); file != files.end(); ++file) {
+ for (std::string const& file : files) {
std::string lfname = localprefix;
cmSystemTools::ConvertToUnixSlashes(lfname);
- lfname += "/" + *file;
- std::string rfname = destination + "/" + remoteprefix + *file;
+ lfname += "/" + file;
+ std::string rfname = destination + "/" + remoteprefix + file;
cmSystemTools::CopyFileAlways(lfname, rfname);
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " Copy file: "
<< lfname << " to " << rfname << std::endl,
@@ -903,13 +891,12 @@ bool cmCTestSubmitHandler::SubmitUsingXMLRPC(
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " Submitting to: "
<< realURL << " (" << remoteprefix << ")" << std::endl,
this->Quiet);
- cmCTest::SetOfStrings::const_iterator file;
- for (file = files.begin(); file != files.end(); ++file) {
+ for (std::string const& file : files) {
xmlrpc_value* result;
- std::string local_file = *file;
+ std::string local_file = file;
if (!cmSystemTools::FileExists(local_file.c_str())) {
- local_file = localprefix + "/" + *file;
+ local_file = localprefix + "/" + file;
}
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
" Submit file: " << local_file << std::endl,
@@ -949,8 +936,9 @@ bool cmCTestSubmitHandler::SubmitUsingXMLRPC(
char remoteCommand[] = "Submit.put";
char* pRealURL = const_cast<char*>(realURL.c_str());
- result = xmlrpc_client_call(&env, pRealURL, remoteCommand, "(6)",
- fileBuffer, (xmlrpc_int32)fileSize);
+ result =
+ xmlrpc_client_call(&env, pRealURL, remoteCommand, "(6)", fileBuffer,
+ static_cast<xmlrpc_int32>(fileSize));
delete[] fileBuffer;
@@ -1037,30 +1025,29 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file,
bool internalTest = cmSystemTools::IsOn(this->GetOption("InternalTest"));
// Get RETRY_COUNT and RETRY_DELAY values if they were set.
- std::string retryDelayString = this->GetOption("RetryDelay") == CM_NULLPTR
+ std::string retryDelayString = this->GetOption("RetryDelay") == nullptr
? ""
: this->GetOption("RetryDelay");
- std::string retryCountString = this->GetOption("RetryCount") == CM_NULLPTR
+ std::string retryCountString = this->GetOption("RetryCount") == nullptr
? ""
: this->GetOption("RetryCount");
unsigned long retryDelay = 0;
- if (retryDelayString != "") {
+ if (!retryDelayString.empty()) {
if (!cmSystemTools::StringToULong(retryDelayString.c_str(), &retryDelay)) {
cmCTestLog(this->CTest, WARNING, "Invalid value for 'RETRY_DELAY' : "
<< retryDelayString << std::endl);
}
}
unsigned long retryCount = 0;
- if (retryCountString != "") {
+ if (!retryCountString.empty()) {
if (!cmSystemTools::StringToULong(retryCountString.c_str(), &retryCount)) {
cmCTestLog(this->CTest, WARNING, "Invalid value for 'RETRY_DELAY' : "
<< retryCountString << std::endl);
}
}
- char md5sum[33];
- md5sum[32] = 0;
- cmSystemTools::ComputeFileMD5(file, md5sum);
+ std::string md5sum =
+ cmSystemTools::ComputeFileHash(file, cmCryptoHash::AlgoMD5);
// 1. request the buildid and check to see if the file
// has already been uploaded
// TODO I added support for subproject. You would need to add
@@ -1084,8 +1071,8 @@ int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file,
<< "site=" << curl.Escape(this->CTest->GetCTestConfiguration("Site"))
<< "&"
<< "track=" << curl.Escape(this->CTest->GetTestModelString()) << "&"
- << "starttime=" << (int)cmSystemTools::GetTime() << "&"
- << "endtime=" << (int)cmSystemTools::GetTime() << "&"
+ << "starttime=" << static_cast<int>(cmSystemTools::GetTime()) << "&"
+ << "endtime=" << static_cast<int>(cmSystemTools::GetTime()) << "&"
<< "datafilesmd5[0]=" << md5sum << "&"
<< "type=" << curl.Escape(typeString);
std::string fields = str.str();
@@ -1324,13 +1311,11 @@ int cmCTestSubmitHandler::ProcessHandler()
cmCTestOptionalLog(this->CTest, DEBUG,
"Globbing for: " << gpath << std::endl, this->Quiet);
if (cmSystemTools::SimpleGlob(gpath, gfiles, 1)) {
- size_t cc;
- for (cc = 0; cc < gfiles.size(); cc++) {
- gfiles[cc] = gfiles[cc].substr(glen);
+ for (std::string& gfile : gfiles) {
+ gfile = gfile.substr(glen);
cmCTestOptionalLog(this->CTest, DEBUG,
- "Glob file: " << gfiles[cc] << std::endl,
- this->Quiet);
- this->CTest->AddSubmitFile(cmCTest::PartCoverage, gfiles[cc].c_str());
+ "Glob file: " << gfile << std::endl, this->Quiet);
+ this->CTest->AddSubmitFile(cmCTest::PartCoverage, gfile.c_str());
}
} else {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Problem globbing" << std::endl);
@@ -1357,9 +1342,8 @@ int cmCTestSubmitHandler::ProcessHandler()
if (ofs) {
ofs << "Upload files:" << std::endl;
int cnt = 0;
- cmCTest::SetOfStrings::iterator it;
- for (it = files.begin(); it != files.end(); ++it) {
- ofs << cnt << "\t" << *it << std::endl;
+ for (std::string const& file : files) {
+ ofs << cnt << "\t" << file << std::endl;
cnt++;
}
}
@@ -1377,7 +1361,7 @@ int cmCTestSubmitHandler::ProcessHandler()
std::string dropMethod(this->CTest->GetCTestConfiguration("DropMethod"));
- if (dropMethod == "" || dropMethod == "ftp") {
+ if (dropMethod.empty() || dropMethod == "ftp") {
ofs << "Using drop method: FTP" << std::endl;
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
" Using FTP submit method" << std::endl
diff --git a/Source/CTest/cmCTestSubmitHandler.h b/Source/CTest/cmCTestSubmitHandler.h
index 2923f4f3d..b4d0e7772 100644
--- a/Source/CTest/cmCTestSubmitHandler.h
+++ b/Source/CTest/cmCTestSubmitHandler.h
@@ -3,7 +3,7 @@
#ifndef cmCTestSubmitHandler_h
#define cmCTestSubmitHandler_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTest.h"
#include "cmCTestGenericHandler.h"
@@ -25,14 +25,14 @@ public:
typedef cmCTestGenericHandler Superclass;
cmCTestSubmitHandler();
- ~cmCTestSubmitHandler() CM_OVERRIDE { this->LogFile = CM_NULLPTR; }
+ ~cmCTestSubmitHandler() override { this->LogFile = nullptr; }
/*
* The main entry point for this class
*/
- int ProcessHandler() CM_OVERRIDE;
+ int ProcessHandler() override;
- void Initialize() CM_OVERRIDE;
+ void Initialize() override;
/** Specify a set of parts (by name) to submit. */
void SelectParts(std::set<cmCTest::Part> const& parts);
diff --git a/Source/CTest/cmCTestTestCommand.cxx b/Source/CTest/cmCTestTestCommand.cxx
index 075b1403a..febd39e76 100644
--- a/Source/CTest/cmCTestTestCommand.cxx
+++ b/Source/CTest/cmCTestTestCommand.cxx
@@ -27,7 +27,7 @@ cmCTestTestCommand::cmCTestTestCommand()
this->Arguments[ctt_SCHEDULE_RANDOM] = "SCHEDULE_RANDOM";
this->Arguments[ctt_STOP_TIME] = "STOP_TIME";
this->Arguments[ctt_TEST_LOAD] = "TEST_LOAD";
- this->Arguments[ctt_LAST] = CM_NULLPTR;
+ this->Arguments[ctt_LAST] = nullptr;
this->Last = ctt_LAST;
}
@@ -124,6 +124,12 @@ cmCTestGenericHandler* cmCTestTestCommand::InitializeHandler()
}
handler->SetTestLoad(testLoad);
+ if (const char* labelsForSubprojects =
+ this->Makefile->GetDefinition("CTEST_LABELS_FOR_SUBPROJECTS")) {
+ this->CTest->SetCTestConfiguration("LabelsForSubprojects",
+ labelsForSubprojects, this->Quiet);
+ }
+
handler->SetQuiet(this->Quiet);
return handler;
}
diff --git a/Source/CTest/cmCTestTestCommand.h b/Source/CTest/cmCTestTestCommand.h
index be7e7831f..11c0db955 100644
--- a/Source/CTest/cmCTestTestCommand.h
+++ b/Source/CTest/cmCTestTestCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestTestCommand_h
#define cmCTestTestCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestHandlerCommand.h"
@@ -25,7 +25,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestTestCommand* ni = new cmCTestTestCommand;
ni->CTest = this->CTest;
@@ -36,11 +36,11 @@ public:
/**
* The name of the command as specified in CMakeList.txt.
*/
- std::string GetName() const CM_OVERRIDE { return "ctest_test"; }
+ std::string GetName() const override { return "ctest_test"; }
protected:
virtual cmCTestGenericHandler* InitializeActualHandler();
- cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
+ cmCTestGenericHandler* InitializeHandler() override;
enum
{
diff --git a/Source/CTest/cmCTestTestHandler.cxx b/Source/CTest/cmCTestTestHandler.cxx
index 674be6052..c7ed92725 100644
--- a/Source/CTest/cmCTestTestHandler.cxx
+++ b/Source/CTest/cmCTestTestHandler.cxx
@@ -1,15 +1,14 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCTestTestHandler.h"
-
-#include "cmsys/Base64.h"
-#include "cmsys/Directory.hxx"
-#include "cmsys/FStream.hxx"
-#include "cmsys/RegularExpression.hxx"
#include <algorithm>
+#include <cmsys/Base64.h>
+#include <cmsys/Directory.hxx>
+#include <cmsys/RegularExpression.hxx>
#include <functional>
#include <iomanip>
#include <iterator>
+#include <memory> // IWYU pragma: keep
#include <set>
#include <sstream>
#include <stdio.h>
@@ -30,9 +29,9 @@
#include "cmSystemTools.h"
#include "cmWorkingDirectory.h"
#include "cmXMLWriter.h"
-#include "cm_auto_ptr.hxx"
#include "cm_utf8.h"
#include "cmake.h"
+#include "cmsys/FStream.hxx"
class cmExecutionStatus;
@@ -42,7 +41,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestSubdirCommand* c = new cmCTestSubdirCommand;
c->TestHandler = this->TestHandler;
@@ -54,7 +53,7 @@ public:
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& /*unused*/) CM_OVERRIDE;
+ cmExecutionStatus& /*unused*/) override;
cmCTestTestHandler* TestHandler;
};
@@ -66,17 +65,16 @@ bool cmCTestSubdirCommand::InitialPass(std::vector<std::string> const& args,
this->SetError("called with incorrect number of arguments");
return false;
}
- std::vector<std::string>::const_iterator it;
std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
- for (it = args.begin(); it != args.end(); ++it) {
+ for (std::string const& arg : args) {
std::string fname;
- if (cmSystemTools::FileIsFullPath(it->c_str())) {
- fname = *it;
+ if (cmSystemTools::FileIsFullPath(arg.c_str())) {
+ fname = arg;
} else {
fname = cwd;
fname += "/";
- fname += *it;
+ fname += arg;
}
if (!cmSystemTools::FileIsDirectory(fname)) {
@@ -117,7 +115,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestAddSubdirectoryCommand* c = new cmCTestAddSubdirectoryCommand;
c->TestHandler = this->TestHandler;
@@ -129,7 +127,7 @@ public:
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& /*unused*/) CM_OVERRIDE;
+ cmExecutionStatus& /*unused*/) override;
cmCTestTestHandler* TestHandler;
};
@@ -182,7 +180,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestAddTestCommand* c = new cmCTestAddTestCommand;
c->TestHandler = this->TestHandler;
@@ -194,7 +192,7 @@ public:
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& /*args*/,
- cmExecutionStatus& /*unused*/) CM_OVERRIDE;
+ cmExecutionStatus& /*unused*/) override;
cmCTestTestHandler* TestHandler;
};
@@ -215,7 +213,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestSetTestsPropertiesCommand* c = new cmCTestSetTestsPropertiesCommand;
c->TestHandler = this->TestHandler;
@@ -227,7 +225,7 @@ public:
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& /*args*/,
- cmExecutionStatus& /*unused*/) CM_OVERRIDE;
+ cmExecutionStatus& /*unused*/) override;
cmCTestTestHandler* TestHandler;
};
@@ -238,6 +236,36 @@ bool cmCTestSetTestsPropertiesCommand::InitialPass(
return this->TestHandler->SetTestsProperties(args);
}
+class cmCTestSetDirectoryPropertiesCommand : public cmCommand
+{
+public:
+ /**
+ * This is a virtual constructor for the command.
+ */
+ cmCommand* Clone() override
+ {
+ cmCTestSetDirectoryPropertiesCommand* c =
+ new cmCTestSetDirectoryPropertiesCommand;
+ c->TestHandler = this->TestHandler;
+ return c;
+ }
+
+ /**
+ * This is called when the command is first encountered in
+ * the CMakeLists.txt file.
+ */
+ bool InitialPass(std::vector<std::string> const& /*unused*/,
+ cmExecutionStatus& /*unused*/) override;
+
+ cmCTestTestHandler* TestHandler;
+};
+
+bool cmCTestSetDirectoryPropertiesCommand::InitialPass(
+ std::vector<std::string> const& args, cmExecutionStatus&)
+{
+ return this->TestHandler->SetDirectoryProperties(args);
+}
+
// get the next number in a string with numbers separated by ,
// pos is the start of the search and pos2 is the end of the search
// pos becomes pos2 after a call to GetNextNumber.
@@ -305,7 +333,7 @@ cmCTestTestHandler::cmCTestTestHandler()
this->MemCheck = false;
- this->LogFile = CM_NULLPTR;
+ this->LogFile = nullptr;
// regex to detect <DartMeasurement>...</DartMeasurement>
this->DartStuff.compile("(<DartMeasurement.*/DartMeasurement[a-zA-Z]*>)");
@@ -323,8 +351,8 @@ void cmCTestTestHandler::Initialize()
this->TestResults.clear();
this->CustomTestsIgnore.clear();
- this->StartTest = "";
- this->EndTest = "";
+ this->StartTest.clear();
+ this->EndTest.clear();
this->CustomPreTest.clear();
this->CustomPostTest.clear();
@@ -340,13 +368,13 @@ void cmCTestTestHandler::Initialize()
this->UseExcludeRegExpFirst = false;
this->IncludeLabelRegularExpression = "";
this->ExcludeLabelRegularExpression = "";
- this->IncludeRegExp = "";
- this->ExcludeRegExp = "";
+ this->IncludeRegExp.clear();
+ this->ExcludeRegExp.clear();
this->ExcludeFixtureRegExp.clear();
this->ExcludeFixtureSetupRegExp.clear();
this->ExcludeFixtureCleanupRegExp.clear();
- TestsToRunString = "";
+ TestsToRunString.clear();
this->UseUnion = false;
this->TestList.clear();
}
@@ -476,10 +504,9 @@ int cmCTestTestHandler::ProcessHandler()
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl
<< "The following tests passed:" << std::endl,
this->Quiet);
- for (std::vector<std::string>::iterator j = passed.begin();
- j != passed.end(); ++j) {
+ for (std::string const& j : passed) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
- "\t" << *j << std::endl, this->Quiet);
+ "\t" << j << std::endl, this->Quiet);
}
}
@@ -489,11 +516,10 @@ int cmCTestTestHandler::ProcessHandler()
SetOfTests resultsSet(this->TestResults.begin(), this->TestResults.end());
std::vector<cmCTestTestHandler::cmCTestTestResult> disabledTests;
- for (SetOfTests::iterator ftit = resultsSet.begin();
- ftit != resultsSet.end(); ++ftit) {
- if (cmHasLiteralPrefix(ftit->CompletionStatus, "SKIP_RETURN_CODE=") ||
- ftit->CompletionStatus == "Disabled") {
- disabledTests.push_back(*ftit);
+ for (cmCTestTestResult const& ft : resultsSet) {
+ if (cmHasLiteralPrefix(ft.CompletionStatus, "SKIP_RETURN_CODE=") ||
+ ft.CompletionStatus == "Disabled") {
+ disabledTests.push_back(ft);
}
}
@@ -506,11 +532,15 @@ int cmCTestTestHandler::ProcessHandler()
<< static_cast<int>(percent + .5f) << "% tests passed, "
<< failed.size() << " tests failed out of " << total
<< std::endl);
+ if ((!this->CTest->GetLabelsForSubprojects().empty() &&
+ this->CTest->GetSubprojectSummary())) {
+ this->PrintLabelOrSubprojectSummary(true);
+ }
if (this->CTest->GetLabelSummary()) {
- this->PrintLabelSummary();
+ this->PrintLabelOrSubprojectSummary(false);
}
char realBuf[1024];
- sprintf(realBuf, "%6.2f sec", (double)(clock_finish - clock_start));
+ sprintf(realBuf, "%6.2f sec", clock_finish - clock_start);
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
"\nTotal Test time (real) = " << realBuf << "\n",
this->Quiet);
@@ -522,17 +552,15 @@ int cmCTestTestHandler::ProcessHandler()
this->StartLogFile("TestsDisabled", ofs);
const char* disabled_reason;
- for (std::vector<cmCTestTestHandler::cmCTestTestResult>::iterator dtit =
- disabledTests.begin();
- dtit != disabledTests.end(); ++dtit) {
- ofs << dtit->TestCount << ":" << dtit->Name << std::endl;
- if (dtit->CompletionStatus == "Disabled") {
+ for (cmCTestTestResult const& dt : disabledTests) {
+ ofs << dt.TestCount << ":" << dt.Name << std::endl;
+ if (dt.CompletionStatus == "Disabled") {
disabled_reason = "Disabled";
} else {
disabled_reason = "Skipped";
}
cmCTestLog(this->CTest, HANDLER_OUTPUT, "\t"
- << std::setw(3) << dtit->TestCount << " - " << dtit->Name
+ << std::setw(3) << dt.TestCount << " - " << dt.Name
<< " (" << disabled_reason << ")" << std::endl);
}
}
@@ -543,16 +571,14 @@ int cmCTestTestHandler::ProcessHandler()
<< "The following tests FAILED:" << std::endl);
this->StartLogFile("TestsFailed", ofs);
- for (SetOfTests::iterator ftit = resultsSet.begin();
- ftit != resultsSet.end(); ++ftit) {
- if (ftit->Status != cmCTestTestHandler::COMPLETED &&
- !cmHasLiteralPrefix(ftit->CompletionStatus, "SKIP_RETURN_CODE=") &&
- ftit->CompletionStatus != "Disabled") {
- ofs << ftit->TestCount << ":" << ftit->Name << std::endl;
- cmCTestLog(
- this->CTest, HANDLER_OUTPUT, "\t"
- << std::setw(3) << ftit->TestCount << " - " << ftit->Name << " ("
- << this->GetTestStatus(ftit->Status) << ")" << std::endl);
+ for (cmCTestTestResult const& ft : resultsSet) {
+ if (ft.Status != cmCTestTestHandler::COMPLETED &&
+ !cmHasLiteralPrefix(ft.CompletionStatus, "SKIP_RETURN_CODE=") &&
+ ft.CompletionStatus != "Disabled") {
+ ofs << ft.TestCount << ":" << ft.Name << std::endl;
+ cmCTestLog(this->CTest, HANDLER_OUTPUT, "\t"
+ << std::setw(3) << ft.TestCount << " - " << ft.Name
+ << " (" << this->GetTestStatus(ft) << ")" << std::endl);
}
}
}
@@ -566,7 +592,7 @@ int cmCTestTestHandler::ProcessHandler()
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot create "
<< (this->MemCheck ? "memory check" : "testing")
<< " XML file" << std::endl);
- this->LogFile = CM_NULLPTR;
+ this->LogFile = nullptr;
return 1;
}
cmXMLWriter xml(xmlfile);
@@ -574,88 +600,98 @@ int cmCTestTestHandler::ProcessHandler()
}
if (!this->PostProcessHandler()) {
- this->LogFile = CM_NULLPTR;
+ this->LogFile = nullptr;
return -1;
}
if (!failed.empty()) {
- this->LogFile = CM_NULLPTR;
+ this->LogFile = nullptr;
return -1;
}
- this->LogFile = CM_NULLPTR;
+ this->LogFile = nullptr;
return 0;
}
-void cmCTestTestHandler::PrintLabelSummary()
+void cmCTestTestHandler::PrintLabelOrSubprojectSummary(bool doSubProject)
{
- cmCTestTestHandler::ListOfTests::iterator it = this->TestList.begin();
+ // collect subproject labels
+ std::vector<std::string> subprojects =
+ this->CTest->GetLabelsForSubprojects();
std::map<std::string, double> labelTimes;
std::map<std::string, int> labelCounts;
std::set<std::string> labels;
- // initialize maps
std::string::size_type maxlen = 0;
- for (; it != this->TestList.end(); ++it) {
- cmCTestTestProperties& p = *it;
- if (!p.Labels.empty()) {
- for (std::vector<std::string>::iterator l = p.Labels.begin();
- l != p.Labels.end(); ++l) {
- if ((*l).size() > maxlen) {
- maxlen = (*l).size();
+ // initialize maps
+ for (cmCTestTestProperties& p : this->TestList) {
+ for (std::string const& l : p.Labels) {
+ // first check to see if the current label is a subproject label
+ bool isSubprojectLabel = false;
+ std::vector<std::string>::iterator subproject =
+ std::find(subprojects.begin(), subprojects.end(), l);
+ if (subproject != subprojects.end()) {
+ isSubprojectLabel = true;
+ }
+ // if we are doing sub projects and this label is one, then use it
+ // if we are not doing sub projects and the label is not one use it
+ if ((doSubProject && isSubprojectLabel) ||
+ (!doSubProject && !isSubprojectLabel)) {
+ if (l.size() > maxlen) {
+ maxlen = l.size();
}
- labels.insert(*l);
- labelTimes[*l] = 0;
- labelCounts[*l] = 0;
+ labels.insert(l);
+ labelTimes[l] = 0;
+ labelCounts[l] = 0;
}
}
}
- cmCTestTestHandler::TestResultsVector::iterator ri =
- this->TestResults.begin();
// fill maps
- for (; ri != this->TestResults.end(); ++ri) {
- cmCTestTestResult& result = *ri;
+ for (cmCTestTestResult& result : this->TestResults) {
cmCTestTestProperties& p = *result.Properties;
- if (!p.Labels.empty()) {
- for (std::vector<std::string>::iterator l = p.Labels.begin();
- l != p.Labels.end(); ++l) {
- labelTimes[*l] += result.ExecutionTime;
- ++labelCounts[*l];
+ for (std::string const& l : p.Labels) {
+ // only use labels found in labels
+ if (labels.find(l) != labels.end()) {
+ labelTimes[l] += result.ExecutionTime * result.Properties->Processors;
+ ++labelCounts[l];
}
}
}
+ // if no labels are found return and print nothing
+ if (labels.empty()) {
+ return;
+ }
// now print times
- if (!labels.empty()) {
+ if (doSubProject) {
+ cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
+ "\nSubproject Time Summary:", this->Quiet);
+ } else {
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\nLabel Time Summary:",
this->Quiet);
}
- for (std::set<std::string>::const_iterator i = labels.begin();
- i != labels.end(); ++i) {
- std::string label = *i;
+ for (std::string const& i : labels) {
+ std::string label = i;
label.resize(maxlen + 3, ' ');
char buf[1024];
- sprintf(buf, "%6.2f sec", labelTimes[*i]);
+ sprintf(buf, "%6.2f sec*proc", labelTimes[i]);
std::ostringstream labelCountStr;
- labelCountStr << "(" << labelCounts[*i] << " test";
- if (labelCounts[*i] > 1) {
+ labelCountStr << "(" << labelCounts[i] << " test";
+ if (labelCounts[i] > 1) {
labelCountStr << "s";
}
labelCountStr << ")";
-
cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\n"
<< label << " = " << buf << " "
<< labelCountStr.str(),
this->Quiet);
if (this->LogFile) {
- *this->LogFile << "\n" << *i << " = " << buf << "\n";
+ *this->LogFile << "\n" << i << " = " << buf << "\n";
}
}
- if (!labels.empty()) {
- if (this->LogFile) {
- *this->LogFile << "\n";
- }
- cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\n", this->Quiet);
+ if (this->LogFile) {
+ *this->LogFile << "\n";
}
+ cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "\n", this->Quiet);
}
void cmCTestTestHandler::CheckLabelFilterInclude(cmCTestTestProperties& it)
@@ -673,9 +709,8 @@ void cmCTestTestHandler::CheckLabelFilterInclude(cmCTestTestProperties& it)
// check to see if the label regular expression matches
bool found = false; // assume it does not match
// loop over all labels and look for match
- for (std::vector<std::string>::iterator l = it.Labels.begin();
- l != it.Labels.end(); ++l) {
- if (this->IncludeLabelRegularExpression.find(*l)) {
+ for (std::string const& l : it.Labels) {
+ if (this->IncludeLabelRegularExpression.find(l)) {
found = true;
}
}
@@ -699,9 +734,8 @@ void cmCTestTestHandler::CheckLabelFilterExclude(cmCTestTestProperties& it)
// check to see if the label regular expression matches
bool found = false; // assume it does not match
// loop over all labels and look for match
- for (std::vector<std::string>::iterator l = it.Labels.begin();
- l != it.Labels.end(); ++l) {
- if (this->ExcludeLabelRegularExpression.find(*l)) {
+ for (std::string const& l : it.Labels) {
+ if (this->ExcludeLabelRegularExpression.find(l)) {
found = true;
}
}
@@ -730,16 +764,15 @@ void cmCTestTestHandler::ComputeTestList()
cmCTestTestHandler::ListOfTests::size_type tmsize = this->TestList.size();
// how many tests are in based on RegExp?
int inREcnt = 0;
- cmCTestTestHandler::ListOfTests::iterator it;
- for (it = this->TestList.begin(); it != this->TestList.end(); it++) {
- this->CheckLabelFilter(*it);
- if (it->IsInBasedOnREOptions) {
+ for (cmCTestTestProperties& tp : this->TestList) {
+ this->CheckLabelFilter(tp);
+ if (tp.IsInBasedOnREOptions) {
inREcnt++;
}
}
// expand the test list based on the union flag
if (this->UseUnion) {
- this->ExpandTestsToRunInformation((int)tmsize);
+ this->ExpandTestsToRunInformation(static_cast<int>(tmsize));
} else {
this->ExpandTestsToRunInformation(inREcnt);
}
@@ -748,9 +781,9 @@ void cmCTestTestHandler::ComputeTestList()
inREcnt = 0;
std::string last_directory;
ListOfTests finalList;
- for (it = this->TestList.begin(); it != this->TestList.end(); it++) {
+ for (cmCTestTestProperties& tp : this->TestList) {
cnt++;
- if (it->IsInBasedOnREOptions) {
+ if (tp.IsInBasedOnREOptions) {
inREcnt++;
}
@@ -759,7 +792,7 @@ void cmCTestTestHandler::ComputeTestList()
if ((!this->TestsToRun.empty() &&
std::find(this->TestsToRun.begin(), this->TestsToRun.end(), cnt) ==
this->TestsToRun.end()) &&
- !it->IsInBasedOnREOptions) {
+ !tp.IsInBasedOnREOptions) {
continue;
}
} else {
@@ -767,12 +800,12 @@ void cmCTestTestHandler::ComputeTestList()
if ((!this->TestsToRun.empty() &&
std::find(this->TestsToRun.begin(), this->TestsToRun.end(),
inREcnt) == this->TestsToRun.end()) ||
- !it->IsInBasedOnREOptions) {
+ !tp.IsInBasedOnREOptions) {
continue;
}
}
- it->Index = cnt; // save the index into the test list for this test
- finalList.push_back(*it);
+ tp.Index = cnt; // save the index into the test list for this test
+ finalList.push_back(tp);
}
UpdateForFixtures(finalList);
@@ -789,10 +822,9 @@ void cmCTestTestHandler::ComputeTestListForRerunFailed()
{
this->ExpandTestsToRunInformationForRerunFailed();
- cmCTestTestHandler::ListOfTests::iterator it;
ListOfTests finalList;
int cnt = 0;
- for (it = this->TestList.begin(); it != this->TestList.end(); it++) {
+ for (cmCTestTestProperties& tp : this->TestList) {
cnt++;
// if this test is not in our list of tests to run, then skip it.
@@ -802,8 +834,8 @@ void cmCTestTestHandler::ComputeTestListForRerunFailed()
continue;
}
- it->Index = cnt;
- finalList.push_back(*it);
+ tp.Index = cnt;
+ finalList.push_back(tp);
}
UpdateForFixtures(finalList);
@@ -857,24 +889,18 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
it != this->TestList.end(); ++it) {
const cmCTestTestProperties& p = *it;
- const std::set<std::string>& setups = p.FixturesSetup;
- for (std::set<std::string>::const_iterator depsIt = setups.begin();
- depsIt != setups.end(); ++depsIt) {
- fixtureSetups.insert(std::make_pair(*depsIt, it));
+ for (std::string const& deps : p.FixturesSetup) {
+ fixtureSetups.insert(std::make_pair(deps, it));
}
- const std::set<std::string>& cleanups = p.FixturesCleanup;
- for (std::set<std::string>::const_iterator depsIt = cleanups.begin();
- depsIt != cleanups.end(); ++depsIt) {
- fixtureCleanups.insert(std::make_pair(*depsIt, it));
+ for (std::string const& deps : p.FixturesCleanup) {
+ fixtureCleanups.insert(std::make_pair(deps, it));
}
}
// Prepare fast lookup of tests already included in our list of tests
std::set<std::string> addedTests;
- for (ListOfTests::const_iterator it = tests.begin(); it != tests.end();
- ++it) {
- const cmCTestTestProperties& p = *it;
+ for (cmCTestTestProperties const& p : tests) {
addedTests.insert(p.Name);
}
@@ -882,8 +908,8 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
// tests array for tests which require that fixture and tests which are
// setups for that fixture. They are needed at the end to populate
// dependencies of the cleanup tests in our final list of tests.
- std::map<std::string, std::vector<size_t> > fixtureRequirements;
- std::map<std::string, std::vector<size_t> > setupFixturesAdded;
+ std::map<std::string, std::vector<size_t>> fixtureRequirements;
+ std::map<std::string, std::vector<size_t>> setupFixturesAdded;
// Use integer index for iteration because we append to
// the tests vector as we go
@@ -908,10 +934,7 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
// Must copy the set of fixtures required because we may invalidate
// the tests array by appending to it
std::set<std::string> fixtures = tests[i].FixturesRequired;
- for (std::set<std::string>::const_iterator fixturesIt = fixtures.begin();
- fixturesIt != fixtures.end(); ++fixturesIt) {
-
- const std::string& requiredFixtureName = *fixturesIt;
+ for (std::string const& requiredFixtureName : fixtures) {
if (requiredFixtureName.empty()) {
continue;
}
@@ -1010,11 +1033,7 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
}
// 2. Record all setup fixtures included in the final list of tests
- for (std::set<std::string>::const_iterator fixturesIt =
- tests[i].FixturesSetup.begin();
- fixturesIt != tests[i].FixturesSetup.end(); ++fixturesIt) {
-
- const std::string& setupFixtureName = *fixturesIt;
+ for (std::string const& setupFixtureName : tests[i].FixturesSetup) {
if (setupFixtureName.empty()) {
continue;
}
@@ -1028,23 +1047,18 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
// setup tests for that fixture. The latter is required to handle the
// pathological case where setup and cleanup tests are in the test set
// but no other test has that fixture as a requirement.
- for (ListOfTests::iterator tIt = tests.begin(); tIt != tests.end(); ++tIt) {
- cmCTestTestProperties& p = *tIt;
+ for (cmCTestTestProperties& p : tests) {
const std::set<std::string>& cleanups = p.FixturesCleanup;
- for (std::set<std::string>::const_iterator fIt = cleanups.begin();
- fIt != cleanups.end(); ++fIt) {
- const std::string& fixture = *fIt;
-
+ for (std::string const& fixture : cleanups) {
// This cleanup test could be part of the original test list that was
// passed in. It is then possible that no other test requires the
// fIt fixture, so we have to check for this.
- std::map<std::string, std::vector<size_t> >::const_iterator cIt =
+ std::map<std::string, std::vector<size_t>>::const_iterator cIt =
fixtureRequirements.find(fixture);
if (cIt != fixtureRequirements.end()) {
const std::vector<size_t>& indices = cIt->second;
- for (std::vector<size_t>::const_iterator indexIt = indices.begin();
- indexIt != indices.end(); ++indexIt) {
- const std::string& reqTestName = tests[*indexIt].Name;
+ for (size_t index : indices) {
+ const std::string& reqTestName = tests[index].Name;
if (std::find(p.Depends.begin(), p.Depends.end(), reqTestName) ==
p.Depends.end()) {
p.Depends.push_back(reqTestName);
@@ -1057,9 +1071,8 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
cIt = setupFixturesAdded.find(fixture);
if (cIt != setupFixturesAdded.end()) {
const std::vector<size_t>& indices = cIt->second;
- for (std::vector<size_t>::const_iterator indexIt = indices.begin();
- indexIt != indices.end(); ++indexIt) {
- const std::string& setupTestName = tests[*indexIt].Name;
+ for (size_t index : indices) {
+ const std::string& setupTestName = tests[index].Name;
if (std::find(p.Depends.begin(), p.Depends.end(), setupTestName) ==
p.Depends.end()) {
p.Depends.push_back(setupTestName);
@@ -1078,9 +1091,7 @@ void cmCTestTestHandler::UpdateForFixtures(ListOfTests& tests) const
void cmCTestTestHandler::UpdateMaxTestNameWidth()
{
std::string::size_type max = this->CTest->GetMaxTestNameWidth();
- for (cmCTestTestHandler::ListOfTests::iterator it = this->TestList.begin();
- it != this->TestList.end(); it++) {
- cmCTestTestProperties& p = *it;
+ for (cmCTestTestProperties& p : this->TestList) {
if (max < p.Name.size()) {
max = p.Name.size();
}
@@ -1215,12 +1226,10 @@ void cmCTestTestHandler::ProcessDirectory(std::vector<std::string>& passed,
bool randomSchedule = this->CTest->GetScheduleType() == "Random";
if (randomSchedule) {
- srand((unsigned)time(CM_NULLPTR));
+ srand(static_cast<unsigned>(time(nullptr)));
}
- for (ListOfTests::iterator it = this->TestList.begin();
- it != this->TestList.end(); ++it) {
- cmCTestTestProperties& p = *it;
+ for (cmCTestTestProperties& p : this->TestList) {
cmCTestMultiProcessHandler::TestSet depends;
if (randomSchedule) {
@@ -1232,19 +1241,17 @@ void cmCTestTestHandler::ProcessDirectory(std::vector<std::string>& passed,
}
if (!p.Depends.empty()) {
- for (std::vector<std::string>::iterator i = p.Depends.begin();
- i != p.Depends.end(); ++i) {
- for (ListOfTests::iterator it2 = this->TestList.begin();
- it2 != this->TestList.end(); ++it2) {
- if (it2->Name == *i) {
- depends.insert(it2->Index);
+ for (std::string const& i : p.Depends) {
+ for (cmCTestTestProperties const& it2 : this->TestList) {
+ if (it2.Name == i) {
+ depends.insert(it2.Index);
break; // break out of test loop as name can only match 1
}
}
}
}
- tests[it->Index] = depends;
- properties[it->Index] = &*it;
+ tests[p.Index] = depends;
+ properties[p.Index] = &p;
}
parallel->SetTests(tests, properties);
parallel->SetPassFailVectors(&passed, &failed);
@@ -1277,83 +1284,85 @@ void cmCTestTestHandler::GenerateDartOutput(cmXMLWriter& xml)
}
this->CTest->StartXML(xml, this->AppendXML);
+ this->CTest->GenerateSubprojectsOutput(xml);
xml.StartElement("Testing");
xml.Element("StartDateTime", this->StartTest);
xml.Element("StartTestTime", this->StartTestTime);
xml.StartElement("TestList");
- cmCTestTestHandler::TestResultsVector::size_type cc;
- for (cc = 0; cc < this->TestResults.size(); cc++) {
- cmCTestTestResult* result = &this->TestResults[cc];
- std::string testPath = result->Path + "/" + result->Name;
+ for (cmCTestTestResult const& result : this->TestResults) {
+ std::string testPath = result.Path + "/" + result.Name;
xml.Element("Test", this->CTest->GetShortPathToFile(testPath.c_str()));
}
xml.EndElement(); // TestList
- for (cc = 0; cc < this->TestResults.size(); cc++) {
- cmCTestTestResult* result = &this->TestResults[cc];
+ for (cmCTestTestResult& result : this->TestResults) {
this->WriteTestResultHeader(xml, result);
xml.StartElement("Results");
- if (result->Status != cmCTestTestHandler::NOT_RUN) {
- if (result->Status != cmCTestTestHandler::COMPLETED ||
- result->ReturnValue) {
+ if (result.Status != cmCTestTestHandler::NOT_RUN) {
+ if (result.Status != cmCTestTestHandler::COMPLETED ||
+ result.ReturnValue) {
xml.StartElement("NamedMeasurement");
xml.Attribute("type", "text/string");
xml.Attribute("name", "Exit Code");
- xml.Element("Value", this->GetTestStatus(result->Status));
+ xml.Element("Value", this->GetTestStatus(result));
xml.EndElement(); // NamedMeasurement
xml.StartElement("NamedMeasurement");
xml.Attribute("type", "text/string");
xml.Attribute("name", "Exit Value");
- xml.Element("Value", result->ReturnValue);
+ xml.Element("Value", result.ReturnValue);
xml.EndElement(); // NamedMeasurement
}
- this->GenerateRegressionImages(xml, result->DartString);
+ this->GenerateRegressionImages(xml, result.DartString);
xml.StartElement("NamedMeasurement");
xml.Attribute("type", "numeric/double");
xml.Attribute("name", "Execution Time");
- xml.Element("Value", result->ExecutionTime);
+ xml.Element("Value", result.ExecutionTime);
xml.EndElement(); // NamedMeasurement
- if (!result->Reason.empty()) {
+ if (!result.Reason.empty()) {
const char* reasonType = "Pass Reason";
- if (result->Status != cmCTestTestHandler::COMPLETED) {
+ if (result.Status != cmCTestTestHandler::COMPLETED) {
reasonType = "Fail Reason";
}
xml.StartElement("NamedMeasurement");
xml.Attribute("type", "text/string");
xml.Attribute("name", reasonType);
- xml.Element("Value", result->Reason);
+ xml.Element("Value", result.Reason);
xml.EndElement(); // NamedMeasurement
}
}
xml.StartElement("NamedMeasurement");
+ xml.Attribute("type", "numeric/double");
+ xml.Attribute("name", "Processors");
+ xml.Element("Value", result.Properties->Processors);
+ xml.EndElement(); // NamedMeasurement
+
+ xml.StartElement("NamedMeasurement");
xml.Attribute("type", "text/string");
xml.Attribute("name", "Completion Status");
- xml.Element("Value", result->CompletionStatus);
+ xml.Element("Value", result.CompletionStatus);
xml.EndElement(); // NamedMeasurement
xml.StartElement("NamedMeasurement");
xml.Attribute("type", "text/string");
xml.Attribute("name", "Command Line");
- xml.Element("Value", result->FullCommandLine);
+ xml.Element("Value", result.FullCommandLine);
xml.EndElement(); // NamedMeasurement
- std::map<std::string, std::string>::iterator measureIt;
- for (measureIt = result->Properties->Measurements.begin();
- measureIt != result->Properties->Measurements.end(); ++measureIt) {
+ for (auto const& measure : result.Properties->Measurements) {
xml.StartElement("NamedMeasurement");
xml.Attribute("type", "text/string");
- xml.Attribute("name", measureIt->first);
- xml.Element("Value", measureIt->second);
+ xml.Attribute("name", measure.first);
+ xml.Element("Value", measure.second);
xml.EndElement(); // NamedMeasurement
}
xml.StartElement("Measurement");
xml.StartElement("Value");
- if (result->CompressOutput) {
+ if (result.CompressOutput) {
xml.Attribute("encoding", "base64");
xml.Attribute("compression", "gzip");
}
- xml.Content(result->Output);
+ xml.Content(result.Output);
xml.EndElement(); // Value
xml.EndElement(); // Measurement
xml.EndElement(); // Results
@@ -1371,32 +1380,31 @@ void cmCTestTestHandler::GenerateDartOutput(cmXMLWriter& xml)
}
void cmCTestTestHandler::WriteTestResultHeader(cmXMLWriter& xml,
- cmCTestTestResult* result)
+ cmCTestTestResult const& result)
{
xml.StartElement("Test");
- if (result->Status == cmCTestTestHandler::COMPLETED) {
+ if (result.Status == cmCTestTestHandler::COMPLETED) {
xml.Attribute("Status", "passed");
- } else if (result->Status == cmCTestTestHandler::NOT_RUN) {
+ } else if (result.Status == cmCTestTestHandler::NOT_RUN) {
xml.Attribute("Status", "notrun");
} else {
xml.Attribute("Status", "failed");
}
- std::string testPath = result->Path + "/" + result->Name;
- xml.Element("Name", result->Name);
- xml.Element("Path", this->CTest->GetShortPathToFile(result->Path.c_str()));
+ std::string testPath = result.Path + "/" + result.Name;
+ xml.Element("Name", result.Name);
+ xml.Element("Path", this->CTest->GetShortPathToFile(result.Path.c_str()));
xml.Element("FullName", this->CTest->GetShortPathToFile(testPath.c_str()));
- xml.Element("FullCommandLine", result->FullCommandLine);
+ xml.Element("FullCommandLine", result.FullCommandLine);
}
void cmCTestTestHandler::WriteTestResultFooter(cmXMLWriter& xml,
- cmCTestTestResult* result)
+ cmCTestTestResult const& result)
{
- if (!result->Properties->Labels.empty()) {
+ if (!result.Properties->Labels.empty()) {
xml.StartElement("Labels");
- std::vector<std::string> const& labels = result->Properties->Labels;
- for (std::vector<std::string>::const_iterator li = labels.begin();
- li != labels.end(); ++li) {
- xml.Element("Label", *li);
+ std::vector<std::string> const& labels = result.Properties->Labels;
+ for (std::string const& label : labels) {
+ xml.Element("Label", label);
}
xml.EndElement(); // Labels
}
@@ -1405,20 +1413,18 @@ void cmCTestTestHandler::WriteTestResultFooter(cmXMLWriter& xml,
}
void cmCTestTestHandler::AttachFiles(cmXMLWriter& xml,
- cmCTestTestResult* result)
+ cmCTestTestResult& result)
{
- if (result->Status != cmCTestTestHandler::COMPLETED &&
- !result->Properties->AttachOnFail.empty()) {
- result->Properties->AttachedFiles.insert(
- result->Properties->AttachedFiles.end(),
- result->Properties->AttachOnFail.begin(),
- result->Properties->AttachOnFail.end());
- }
- for (std::vector<std::string>::const_iterator file =
- result->Properties->AttachedFiles.begin();
- file != result->Properties->AttachedFiles.end(); ++file) {
- const std::string& base64 = this->CTest->Base64GzipEncodeFile(*file);
- std::string fname = cmSystemTools::GetFilenameName(*file);
+ if (result.Status != cmCTestTestHandler::COMPLETED &&
+ !result.Properties->AttachOnFail.empty()) {
+ result.Properties->AttachedFiles.insert(
+ result.Properties->AttachedFiles.end(),
+ result.Properties->AttachOnFail.begin(),
+ result.Properties->AttachOnFail.end());
+ }
+ for (std::string const& file : result.Properties->AttachedFiles) {
+ const std::string& base64 = this->CTest->Base64GzipEncodeFile(file);
+ std::string const fname = cmSystemTools::GetFilenameName(file);
xml.StartElement("NamedMeasurement");
xml.Attribute("name", "Attached File");
xml.Attribute("encoding", "base64");
@@ -1432,18 +1438,16 @@ void cmCTestTestHandler::AttachFiles(cmXMLWriter& xml,
int cmCTestTestHandler::ExecuteCommands(std::vector<std::string>& vec)
{
- std::vector<std::string>::iterator it;
- for (it = vec.begin(); it != vec.end(); ++it) {
+ for (std::string const& it : vec) {
int retVal = 0;
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
- "Run command: " << *it << std::endl, this->Quiet);
- if (!cmSystemTools::RunSingleCommand(it->c_str(), CM_NULLPTR, CM_NULLPTR,
- &retVal, CM_NULLPTR,
- cmSystemTools::OUTPUT_MERGE
+ "Run command: " << it << std::endl, this->Quiet);
+ if (!cmSystemTools::RunSingleCommand(it.c_str(), nullptr, nullptr, &retVal,
+ nullptr, cmSystemTools::OUTPUT_MERGE
/*this->Verbose*/) ||
retVal != 0) {
cmCTestLog(this->CTest, ERROR_MESSAGE,
- "Problem running command: " << *it << std::endl);
+ "Problem running command: " << it << std::endl);
return 0;
}
}
@@ -1554,11 +1558,9 @@ std::string cmCTestTestHandler::FindExecutable(
// if extraPaths are provided and we were not passed a full path, try them,
// try any extra paths
if (filepath.empty()) {
- for (unsigned int i = 0; i < extraPaths.size(); ++i) {
- std::string filepathExtra =
- cmSystemTools::GetFilenamePath(extraPaths[i]);
- std::string filenameExtra =
- cmSystemTools::GetFilenameName(extraPaths[i]);
+ for (std::string const& extraPath : extraPaths) {
+ std::string filepathExtra = cmSystemTools::GetFilenamePath(extraPath);
+ std::string filenameExtra = cmSystemTools::GetFilenameName(extraPath);
cmCTestTestHandler::AddConfigurations(ctest, attempted, attemptedConfigs,
filepathExtra, filenameExtra);
}
@@ -1593,9 +1595,9 @@ std::string cmCTestTestHandler::FindExecutable(
// if everything else failed, check the users path, but only if a full path
// wasn't specified
if (fullPath.empty() && filepath.empty()) {
- std::string path = cmSystemTools::FindProgram(filename.c_str());
- if (path != "") {
- resultingConfig = "";
+ std::string const path = cmSystemTools::FindProgram(filename.c_str());
+ if (!path.empty()) {
+ resultingConfig.clear();
return path;
}
}
@@ -1603,9 +1605,8 @@ std::string cmCTestTestHandler::FindExecutable(
cmCTestLog(ctest, HANDLER_OUTPUT, "Could not find executable "
<< testCommand << "\n"
<< "Looked in the following places:\n");
- for (std::vector<std::string>::iterator i = failed.begin();
- i != failed.end(); ++i) {
- cmCTestLog(ctest, HANDLER_OUTPUT, *i << "\n");
+ for (std::string const& f : failed) {
+ cmCTestLog(ctest, HANDLER_OUTPUT, f << "\n");
}
}
@@ -1635,9 +1636,9 @@ void cmCTestTestHandler::GetListOfTests()
cm.SetHomeOutputDirectory("");
cm.GetCurrentSnapshot().SetDefaultDefinitions();
cmGlobalGenerator gg(&cm);
- CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
- mf->AddDefinition("CTEST_CONFIGURATION_TYPE",
- this->CTest->GetConfigType().c_str());
+ cmMakefile mf(&gg, cm.GetCurrentSnapshot());
+ mf.AddDefinition("CTEST_CONFIGURATION_TYPE",
+ this->CTest->GetConfigType().c_str());
// Add handler for ADD_TEST
cmCTestAddTestCommand* newCom1 = new cmCTestAddTestCommand;
@@ -1660,6 +1661,12 @@ void cmCTestTestHandler::GetListOfTests()
newCom4->TestHandler = this;
cm.GetState()->AddBuiltinCommand("set_tests_properties", newCom4);
+ // Add handler for SET_DIRECTORY_PROPERTIES
+ cmCTestSetDirectoryPropertiesCommand* newCom5 =
+ new cmCTestSetDirectoryPropertiesCommand;
+ newCom5->TestHandler = this;
+ cm.GetState()->AddBuiltinCommand("set_directory_properties", newCom5);
+
const char* testFilename;
if (cmSystemTools::FileExists("CTestTestfile.cmake")) {
// does the CTestTestfile.cmake exist ?
@@ -1671,7 +1678,7 @@ void cmCTestTestHandler::GetListOfTests()
return;
}
- if (!mf->ReadListFile(testFilename)) {
+ if (!mf.ReadListFile(testFilename)) {
return;
}
if (cmSystemTools::GetErrorOccuredFlag()) {
@@ -1693,17 +1700,20 @@ void cmCTestTestHandler::UseExcludeRegExp()
this->UseExcludeRegExpFirst = !this->UseIncludeRegExpFlag;
}
-const char* cmCTestTestHandler::GetTestStatus(int status)
+const char* cmCTestTestHandler::GetTestStatus(cmCTestTestResult const& result)
{
static const char* statuses[] = { "Not Run", "Timeout", "SEGFAULT",
"ILLEGAL", "INTERRUPT", "NUMERICAL",
"OTHER_FAULT", "Failed", "BAD_COMMAND",
"Completed" };
-
+ int status = result.Status;
if (status < cmCTestTestHandler::NOT_RUN ||
status > cmCTestTestHandler::COMPLETED) {
return "No Status";
}
+ if (status == cmCTestTestHandler::OTHER_FAULT) {
+ return result.ExceptionStatus.c_str();
+ }
return statuses[status];
}
@@ -1792,7 +1802,7 @@ void cmCTestTestHandler::ExpandTestsToRunInformationForRerunFailed()
if (fileNameSubstring != pattern) {
continue;
}
- if (logName == "") {
+ if (logName.empty()) {
logName = fileName;
} else {
// if multiple matching logs were found we use the most recently
@@ -2086,116 +2096,117 @@ bool cmCTestTestHandler::SetTestsProperties(
break;
}
std::string val = *it;
- std::vector<std::string>::const_iterator tit;
- for (tit = tests.begin(); tit != tests.end(); ++tit) {
- cmCTestTestHandler::ListOfTests::iterator rtit;
- for (rtit = this->TestList.begin(); rtit != this->TestList.end();
- ++rtit) {
- if (*tit == rtit->Name) {
+ for (std::string const& t : tests) {
+ for (cmCTestTestProperties& rt : this->TestList) {
+ if (t == rt.Name) {
if (key == "WILL_FAIL") {
- rtit->WillFail = cmSystemTools::IsOn(val.c_str());
+ rt.WillFail = cmSystemTools::IsOn(val.c_str());
}
if (key == "DISABLED") {
- rtit->Disabled = cmSystemTools::IsOn(val.c_str());
+ rt.Disabled = cmSystemTools::IsOn(val.c_str());
}
if (key == "ATTACHED_FILES") {
- cmSystemTools::ExpandListArgument(val, rtit->AttachedFiles);
+ cmSystemTools::ExpandListArgument(val, rt.AttachedFiles);
}
if (key == "ATTACHED_FILES_ON_FAIL") {
- cmSystemTools::ExpandListArgument(val, rtit->AttachOnFail);
+ cmSystemTools::ExpandListArgument(val, rt.AttachOnFail);
}
if (key == "RESOURCE_LOCK") {
std::vector<std::string> lval;
cmSystemTools::ExpandListArgument(val, lval);
- rtit->LockedResources.insert(lval.begin(), lval.end());
+ rt.LockedResources.insert(lval.begin(), lval.end());
}
if (key == "FIXTURES_SETUP") {
std::vector<std::string> lval;
cmSystemTools::ExpandListArgument(val, lval);
- rtit->FixturesSetup.insert(lval.begin(), lval.end());
+ rt.FixturesSetup.insert(lval.begin(), lval.end());
}
if (key == "FIXTURES_CLEANUP") {
std::vector<std::string> lval;
cmSystemTools::ExpandListArgument(val, lval);
- rtit->FixturesCleanup.insert(lval.begin(), lval.end());
+ rt.FixturesCleanup.insert(lval.begin(), lval.end());
}
if (key == "FIXTURES_REQUIRED") {
std::vector<std::string> lval;
cmSystemTools::ExpandListArgument(val, lval);
- rtit->FixturesRequired.insert(lval.begin(), lval.end());
+ rt.FixturesRequired.insert(lval.begin(), lval.end());
}
if (key == "TIMEOUT") {
- rtit->Timeout = atof(val.c_str());
- rtit->ExplicitTimeout = true;
+ rt.Timeout = atof(val.c_str());
+ rt.ExplicitTimeout = true;
}
if (key == "COST") {
- rtit->Cost = static_cast<float>(atof(val.c_str()));
+ rt.Cost = static_cast<float>(atof(val.c_str()));
}
if (key == "REQUIRED_FILES") {
- cmSystemTools::ExpandListArgument(val, rtit->RequiredFiles);
+ cmSystemTools::ExpandListArgument(val, rt.RequiredFiles);
}
if (key == "RUN_SERIAL") {
- rtit->RunSerial = cmSystemTools::IsOn(val.c_str());
+ rt.RunSerial = cmSystemTools::IsOn(val.c_str());
}
if (key == "FAIL_REGULAR_EXPRESSION") {
std::vector<std::string> lval;
cmSystemTools::ExpandListArgument(val, lval);
- std::vector<std::string>::iterator crit;
- for (crit = lval.begin(); crit != lval.end(); ++crit) {
- rtit->ErrorRegularExpressions.push_back(
+ for (std::string const& cr : lval) {
+ rt.ErrorRegularExpressions.push_back(
std::pair<cmsys::RegularExpression, std::string>(
- cmsys::RegularExpression(crit->c_str()),
- std::string(*crit)));
+ cmsys::RegularExpression(cr.c_str()), std::string(cr)));
}
}
if (key == "PROCESSORS") {
- rtit->Processors = atoi(val.c_str());
- if (rtit->Processors < 1) {
- rtit->Processors = 1;
+ rt.Processors = atoi(val.c_str());
+ if (rt.Processors < 1) {
+ rt.Processors = 1;
}
}
if (key == "SKIP_RETURN_CODE") {
- rtit->SkipReturnCode = atoi(val.c_str());
- if (rtit->SkipReturnCode < 0 || rtit->SkipReturnCode > 255) {
- rtit->SkipReturnCode = -1;
+ rt.SkipReturnCode = atoi(val.c_str());
+ if (rt.SkipReturnCode < 0 || rt.SkipReturnCode > 255) {
+ rt.SkipReturnCode = -1;
}
}
if (key == "DEPENDS") {
- cmSystemTools::ExpandListArgument(val, rtit->Depends);
+ cmSystemTools::ExpandListArgument(val, rt.Depends);
}
if (key == "ENVIRONMENT") {
- cmSystemTools::ExpandListArgument(val, rtit->Environment);
+ cmSystemTools::ExpandListArgument(val, rt.Environment);
}
if (key == "LABELS") {
- cmSystemTools::ExpandListArgument(val, rtit->Labels);
+ std::vector<std::string> Labels;
+ cmSystemTools::ExpandListArgument(val, Labels);
+ rt.Labels.insert(rt.Labels.end(), Labels.begin(), Labels.end());
+ // sort the array
+ std::sort(rt.Labels.begin(), rt.Labels.end());
+ // remove duplicates
+ std::vector<std::string>::iterator new_end =
+ std::unique(rt.Labels.begin(), rt.Labels.end());
+ rt.Labels.erase(new_end, rt.Labels.end());
}
if (key == "MEASUREMENT") {
size_t pos = val.find_first_of('=');
if (pos != std::string::npos) {
std::string mKey = val.substr(0, pos);
const char* mVal = val.c_str() + pos + 1;
- rtit->Measurements[mKey] = mVal;
+ rt.Measurements[mKey] = mVal;
} else {
- rtit->Measurements[val] = "1";
+ rt.Measurements[val] = "1";
}
}
if (key == "PASS_REGULAR_EXPRESSION") {
std::vector<std::string> lval;
cmSystemTools::ExpandListArgument(val, lval);
- std::vector<std::string>::iterator crit;
- for (crit = lval.begin(); crit != lval.end(); ++crit) {
- rtit->RequiredRegularExpressions.push_back(
+ for (std::string const& cr : lval) {
+ rt.RequiredRegularExpressions.push_back(
std::pair<cmsys::RegularExpression, std::string>(
- cmsys::RegularExpression(crit->c_str()),
- std::string(*crit)));
+ cmsys::RegularExpression(cr.c_str()), std::string(cr)));
}
}
if (key == "WORKING_DIRECTORY") {
- rtit->Directory = val;
+ rt.Directory = val;
}
if (key == "TIMEOUT_AFTER_MATCH") {
std::vector<std::string> propArgs;
@@ -2205,15 +2216,13 @@ bool cmCTestTestHandler::SetTestsProperties(
"TIMEOUT_AFTER_MATCH expects two arguments, found "
<< propArgs.size() << std::endl);
} else {
- rtit->AlternateTimeout = atof(propArgs[0].c_str());
+ rt.AlternateTimeout = atof(propArgs[0].c_str());
std::vector<std::string> lval;
cmSystemTools::ExpandListArgument(propArgs[1], lval);
- std::vector<std::string>::iterator crit;
- for (crit = lval.begin(); crit != lval.end(); ++crit) {
- rtit->TimeoutRegularExpressions.push_back(
+ for (std::string const& cr : lval) {
+ rt.TimeoutRegularExpressions.push_back(
std::pair<cmsys::RegularExpression, std::string>(
- cmsys::RegularExpression(crit->c_str()),
- std::string(*crit)));
+ cmsys::RegularExpression(cr.c_str()), std::string(cr)));
}
}
}
@@ -2224,6 +2233,53 @@ bool cmCTestTestHandler::SetTestsProperties(
return true;
}
+bool cmCTestTestHandler::SetDirectoryProperties(
+ const std::vector<std::string>& args)
+{
+ std::vector<std::string>::const_iterator it;
+ std::vector<std::string> tests;
+ bool found = false;
+ for (it = args.begin(); it != args.end(); ++it) {
+ if (*it == "PROPERTIES") {
+ found = true;
+ break;
+ }
+ tests.push_back(*it);
+ }
+
+ if (!found) {
+ return false;
+ }
+ ++it; // skip PROPERTIES
+ for (; it != args.end(); ++it) {
+ std::string key = *it;
+ ++it;
+ if (it == args.end()) {
+ break;
+ }
+ std::string val = *it;
+ for (cmCTestTestProperties& rt : this->TestList) {
+ std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
+ if (cwd == rt.Directory) {
+ if (key == "LABELS") {
+ std::vector<std::string> DirectoryLabels;
+ cmSystemTools::ExpandListArgument(val, DirectoryLabels);
+ rt.Labels.insert(rt.Labels.end(), DirectoryLabels.begin(),
+ DirectoryLabels.end());
+
+ // sort the array
+ std::sort(rt.Labels.begin(), rt.Labels.end());
+ // remove duplicates
+ std::vector<std::string>::iterator new_end =
+ std::unique(rt.Labels.begin(), rt.Labels.end());
+ rt.Labels.erase(new_end, rt.Labels.end());
+ }
+ }
+ }
+ }
+ return true;
+}
+
bool cmCTestTestHandler::AddTest(const std::vector<std::string>& args)
{
const std::string& testname = args[0];
diff --git a/Source/CTest/cmCTestTestHandler.h b/Source/CTest/cmCTestTestHandler.h
index 0edcb143a..394d20ed0 100644
--- a/Source/CTest/cmCTestTestHandler.h
+++ b/Source/CTest/cmCTestTestHandler.h
@@ -3,7 +3,7 @@
#ifndef cmCTestTestHandler_h
#define cmCTestTestHandler_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestGenericHandler.h"
@@ -36,7 +36,7 @@ public:
/**
* The main entry point for this class
*/
- int ProcessHandler() CM_OVERRIDE;
+ int ProcessHandler() override;
/**
* When both -R and -I are used should te resulting test list be the
@@ -54,7 +54,7 @@ public:
/**
* This method is called when reading CTest custom file
*/
- void PopulateCustomVectors(cmMakefile* mf) CM_OVERRIDE;
+ void PopulateCustomVectors(cmMakefile* mf) override;
///! Control the use of the regular expresisons, call these methods to turn
/// them on
@@ -90,7 +90,12 @@ public:
*/
bool SetTestsProperties(const std::vector<std::string>& args);
- void Initialize() CM_OVERRIDE;
+ /**
+ * Set directory properties
+ */
+ bool SetDirectoryProperties(const std::vector<std::string>& args);
+
+ void Initialize() override;
// NOTE: This struct is Saved/Restored
// in cmCTestTestHandler, if you add to this class
@@ -105,11 +110,11 @@ public:
std::vector<std::string> Depends;
std::vector<std::string> AttachedFiles;
std::vector<std::string> AttachOnFail;
- std::vector<std::pair<cmsys::RegularExpression, std::string> >
+ std::vector<std::pair<cmsys::RegularExpression, std::string>>
ErrorRegularExpressions;
- std::vector<std::pair<cmsys::RegularExpression, std::string> >
+ std::vector<std::pair<cmsys::RegularExpression, std::string>>
RequiredRegularExpressions;
- std::vector<std::pair<cmsys::RegularExpression, std::string> >
+ std::vector<std::pair<cmsys::RegularExpression, std::string>>
TimeoutRegularExpressions;
std::map<std::string, std::string> Measurements;
bool IsInBasedOnREOptions;
@@ -144,6 +149,7 @@ public:
double ExecutionTime;
int ReturnValue;
int Status;
+ std::string ExceptionStatus;
bool CompressOutput;
std::string CompletionStatus;
std::string Output;
@@ -182,10 +188,12 @@ protected:
virtual void GenerateTestCommand(std::vector<std::string>& args, int test);
int ExecuteCommands(std::vector<std::string>& vec);
- void WriteTestResultHeader(cmXMLWriter& xml, cmCTestTestResult* result);
- void WriteTestResultFooter(cmXMLWriter& xml, cmCTestTestResult* result);
+ void WriteTestResultHeader(cmXMLWriter& xml,
+ cmCTestTestResult const& result);
+ void WriteTestResultFooter(cmXMLWriter& xml,
+ cmCTestTestResult const& result);
// Write attached test files into the xml
- void AttachFiles(cmXMLWriter& xml, cmCTestTestResult* result);
+ void AttachFiles(cmXMLWriter& xml, cmCTestTestResult& result);
//! Clean test output to specified length
bool CleanTestOutput(std::string& output, size_t length);
@@ -226,7 +234,8 @@ private:
*/
virtual void GenerateDartOutput(cmXMLWriter& xml);
- void PrintLabelSummary();
+ void PrintLabelOrSubprojectSummary(bool isSubProject);
+
/**
* Run the tests for a directory and any subdirectories
*/
@@ -262,7 +271,7 @@ private:
*/
std::string FindTheExecutable(const char* exe);
- const char* GetTestStatus(int status);
+ const char* GetTestStatus(cmCTestTestResult const&);
void ExpandTestsToRunInformation(size_t numPossibleTests);
void ExpandTestsToRunInformationForRerunFailed();
diff --git a/Source/CTest/cmCTestUpdateCommand.cxx b/Source/CTest/cmCTestUpdateCommand.cxx
index 8c037545f..3d800f8b3 100644
--- a/Source/CTest/cmCTestUpdateCommand.cxx
+++ b/Source/CTest/cmCTestUpdateCommand.cxx
@@ -78,12 +78,12 @@ cmCTestGenericHandler* cmCTestUpdateCommand::InitializeHandler()
this->CTest->GetInitializedHandler("update");
if (!handler) {
this->SetError("internal CTest error. Cannot instantiate update handler");
- return CM_NULLPTR;
+ return nullptr;
}
handler->SetCommand(this);
if (source_dir.empty()) {
this->SetError("source directory not specified. Please use SOURCE tag");
- return CM_NULLPTR;
+ return nullptr;
}
handler->SetOption("SourceDirectory", source_dir.c_str());
handler->SetQuiet(this->Quiet);
diff --git a/Source/CTest/cmCTestUpdateCommand.h b/Source/CTest/cmCTestUpdateCommand.h
index 3b8f0a641..3b2f3e102 100644
--- a/Source/CTest/cmCTestUpdateCommand.h
+++ b/Source/CTest/cmCTestUpdateCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestUpdateCommand_h
#define cmCTestUpdateCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestHandlerCommand.h"
@@ -25,7 +25,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestUpdateCommand* ni = new cmCTestUpdateCommand;
ni->CTest = this->CTest;
@@ -36,10 +36,10 @@ public:
/**
* The name of the command as specified in CMakeList.txt.
*/
- std::string GetName() const CM_OVERRIDE { return "ctest_update"; }
+ std::string GetName() const override { return "ctest_update"; }
protected:
- cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
+ cmCTestGenericHandler* InitializeHandler() override;
};
#endif
diff --git a/Source/CTest/cmCTestUpdateHandler.cxx b/Source/CTest/cmCTestUpdateHandler.cxx
index e08a9b7bd..786ed5e47 100644
--- a/Source/CTest/cmCTestUpdateHandler.cxx
+++ b/Source/CTest/cmCTestUpdateHandler.cxx
@@ -2,6 +2,7 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCTestUpdateHandler.h"
+#include "cmAlgorithms.h"
#include "cmCLocaleEnvironmentScope.h"
#include "cmCTest.h"
#include "cmCTestBZR.h"
@@ -16,7 +17,7 @@
#include "cmVersion.h"
#include "cmXMLWriter.h"
-#include "cm_auto_ptr.hxx"
+#include <memory> // IWYU pragma: keep
#include <sstream>
static const char* cmCTestUpdateHandlerUpdateStrings[] = {
@@ -39,7 +40,7 @@ cmCTestUpdateHandler::cmCTestUpdateHandler()
void cmCTestUpdateHandler::Initialize()
{
this->Superclass::Initialize();
- this->UpdateCommand = "";
+ this->UpdateCommand.clear();
this->UpdateType = e_CVS;
}
@@ -134,28 +135,28 @@ int cmCTestUpdateHandler::ProcessHandler()
, this->Quiet);
// Create an object to interact with the VCS tool.
- CM_AUTO_PTR<cmCTestVC> vc;
+ std::unique_ptr<cmCTestVC> vc;
switch (this->UpdateType) {
case e_CVS:
- vc.reset(new cmCTestCVS(this->CTest, ofs));
+ vc = cm::make_unique<cmCTestCVS>(this->CTest, ofs);
break;
case e_SVN:
- vc.reset(new cmCTestSVN(this->CTest, ofs));
+ vc = cm::make_unique<cmCTestSVN>(this->CTest, ofs);
break;
case e_BZR:
- vc.reset(new cmCTestBZR(this->CTest, ofs));
+ vc = cm::make_unique<cmCTestBZR>(this->CTest, ofs);
break;
case e_GIT:
- vc.reset(new cmCTestGIT(this->CTest, ofs));
+ vc = cm::make_unique<cmCTestGIT>(this->CTest, ofs);
break;
case e_HG:
- vc.reset(new cmCTestHG(this->CTest, ofs));
+ vc = cm::make_unique<cmCTestHG>(this->CTest, ofs);
break;
case e_P4:
- vc.reset(new cmCTestP4(this->CTest, ofs));
+ vc = cm::make_unique<cmCTestP4>(this->CTest, ofs);
break;
default:
- vc.reset(new cmCTestVC(this->CTest, ofs));
+ vc = cm::make_unique<cmCTestVC>(this->CTest, ofs);
break;
}
vc->SetCommandLineTool(this->UpdateCommand);
@@ -309,7 +310,7 @@ bool cmCTestUpdateHandler::SelectVCS()
// If no update command was specified, lookup one for this VCS tool.
if (this->UpdateCommand.empty()) {
- const char* key = CM_NULLPTR;
+ const char* key = nullptr;
switch (this->UpdateType) {
case e_CVS:
key = "CVSCommand";
diff --git a/Source/CTest/cmCTestUpdateHandler.h b/Source/CTest/cmCTestUpdateHandler.h
index 0cd284421..0f51d3f3e 100644
--- a/Source/CTest/cmCTestUpdateHandler.h
+++ b/Source/CTest/cmCTestUpdateHandler.h
@@ -3,7 +3,7 @@
#ifndef cmCTestUpdateHandler_h
#define cmCTestUpdateHandler_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTestGenericHandler.h"
@@ -23,7 +23,7 @@ public:
/*
* The main entry point for this class
*/
- int ProcessHandler() CM_OVERRIDE;
+ int ProcessHandler() override;
cmCTestUpdateHandler();
@@ -42,7 +42,7 @@ public:
/**
* Initialize handler
*/
- void Initialize() CM_OVERRIDE;
+ void Initialize() override;
private:
// Some structures needed for update
diff --git a/Source/CTest/cmCTestUploadCommand.cxx b/Source/CTest/cmCTestUploadCommand.cxx
index 717117a5f..d85f35f6f 100644
--- a/Source/CTest/cmCTestUploadCommand.cxx
+++ b/Source/CTest/cmCTestUploadCommand.cxx
@@ -18,7 +18,7 @@ cmCTestGenericHandler* cmCTestUploadCommand::InitializeHandler()
this->CTest->GetInitializedHandler("upload");
if (!handler) {
this->SetError("internal CTest error. Cannot instantiate upload handler");
- return CM_NULLPTR;
+ return nullptr;
}
static_cast<cmCTestUploadHandler*>(handler)->SetFiles(this->Files);
diff --git a/Source/CTest/cmCTestUploadCommand.h b/Source/CTest/cmCTestUploadCommand.h
index 6e721796a..61bf1cc58 100644
--- a/Source/CTest/cmCTestUploadCommand.h
+++ b/Source/CTest/cmCTestUploadCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCTestUploadCommand_h
#define cmCTestUploadCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTest.h"
#include "cmCTestHandlerCommand.h"
@@ -27,7 +27,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmCTestUploadCommand* ni = new cmCTestUploadCommand;
ni->CTest = this->CTest;
@@ -38,15 +38,15 @@ public:
/**
* The name of the command as specified in CMakeList.txt.
*/
- std::string GetName() const CM_OVERRIDE { return "ctest_upload"; }
+ std::string GetName() const override { return "ctest_upload"; }
typedef cmCTestHandlerCommand Superclass;
protected:
- cmCTestGenericHandler* InitializeHandler() CM_OVERRIDE;
+ cmCTestGenericHandler* InitializeHandler() override;
- bool CheckArgumentKeyword(std::string const& arg) CM_OVERRIDE;
- bool CheckArgumentValue(std::string const& arg) CM_OVERRIDE;
+ bool CheckArgumentKeyword(std::string const& arg) override;
+ bool CheckArgumentValue(std::string const& arg) override;
enum
{
diff --git a/Source/CTest/cmCTestUploadHandler.cxx b/Source/CTest/cmCTestUploadHandler.cxx
index 05a39840d..59a5de484 100644
--- a/Source/CTest/cmCTestUploadHandler.cxx
+++ b/Source/CTest/cmCTestUploadHandler.cxx
@@ -7,7 +7,6 @@
#include "cmXMLWriter.h"
#include <ostream>
-#include <set>
#include <string>
cmCTestUploadHandler::cmCTestUploadHandler()
@@ -37,7 +36,6 @@ int cmCTestUploadHandler::ProcessHandler()
}
std::string buildname =
cmCTest::SafeBuildIdField(this->CTest->GetCTestConfiguration("BuildName"));
- cmCTest::SetOfStrings::const_iterator it;
cmXMLWriter xml(ofs);
xml.StartDocument();
@@ -55,14 +53,14 @@ int cmCTestUploadHandler::ProcessHandler()
this->CTest->AddSiteProperties(xml);
xml.StartElement("Upload");
- for (it = this->Files.begin(); it != this->Files.end(); it++) {
+ for (std::string const& file : this->Files) {
cmCTestOptionalLog(this->CTest, OUTPUT,
- "\tUpload file: " << *it << std::endl, this->Quiet);
+ "\tUpload file: " << file << std::endl, this->Quiet);
xml.StartElement("File");
- xml.Attribute("filename", *it);
+ xml.Attribute("filename", file);
xml.StartElement("Content");
xml.Attribute("encoding", "base64");
- xml.Content(this->CTest->Base64EncodeFile(*it));
+ xml.Content(this->CTest->Base64EncodeFile(file));
xml.EndElement(); // Content
xml.EndElement(); // File
}
diff --git a/Source/CTest/cmCTestUploadHandler.h b/Source/CTest/cmCTestUploadHandler.h
index 1e8d3c801..ff5057418 100644
--- a/Source/CTest/cmCTestUploadHandler.h
+++ b/Source/CTest/cmCTestUploadHandler.h
@@ -3,7 +3,7 @@
#ifndef cmCTestUploadHandler_h
#define cmCTestUploadHandler_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCTest.h"
#include "cmCTestGenericHandler.h"
@@ -20,14 +20,14 @@ public:
typedef cmCTestGenericHandler Superclass;
cmCTestUploadHandler();
- ~cmCTestUploadHandler() CM_OVERRIDE {}
+ ~cmCTestUploadHandler() override {}
/*
* The main entry point for this class
*/
- int ProcessHandler() CM_OVERRIDE;
+ int ProcessHandler() override;
- void Initialize() CM_OVERRIDE;
+ void Initialize() override;
/** Specify a set of files to submit. */
void SetFiles(cmCTest::SetOfStrings const& files);
diff --git a/Source/CTest/cmCTestVC.cxx b/Source/CTest/cmCTestVC.cxx
index fb2742e08..fd7f37ac8 100644
--- a/Source/CTest/cmCTestVC.cxx
+++ b/Source/CTest/cmCTestVC.cxx
@@ -56,11 +56,11 @@ bool cmCTestVC::InitialCheckout(const char* command)
// Construct the initial checkout command line.
std::vector<std::string> args = cmSystemTools::ParseArguments(command);
std::vector<char const*> vc_co;
- for (std::vector<std::string>::const_iterator ai = args.begin();
- ai != args.end(); ++ai) {
- vc_co.push_back(ai->c_str());
+ vc_co.reserve(args.size() + 1);
+ for (std::string const& arg : args) {
+ vc_co.push_back(arg.c_str());
}
- vc_co.push_back(CM_NULLPTR);
+ vc_co.push_back(nullptr);
// Run the initial checkout command and log its output.
this->Log << "--- Begin Initial Checkout ---\n";
@@ -113,7 +113,7 @@ bool cmCTestVC::RunUpdateCommand(char const* const* cmd, OutputParser* out,
}
// Run the command.
- return this->RunChild(cmd, out, err, CM_NULLPTR, encoding);
+ return this->RunChild(cmd, out, err, nullptr, encoding);
}
std::string cmCTestVC::GetNightlyTime()
diff --git a/Source/CTest/cmCTestVC.h b/Source/CTest/cmCTestVC.h
index 6400bcda3..69a3bf023 100644
--- a/Source/CTest/cmCTestVC.h
+++ b/Source/CTest/cmCTestVC.h
@@ -3,7 +3,7 @@
#ifndef cmCTestVC_h
#define cmCTestVC_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <string>
@@ -100,8 +100,8 @@ protected:
Revision const* PriorRev;
File()
: Status(PathUpdated)
- , Rev(CM_NULLPTR)
- , PriorRev(CM_NULLPTR)
+ , Rev(nullptr)
+ , PriorRev(nullptr)
{
}
File(PathStatus status, Revision const* rev, Revision const* priorRev)
@@ -117,12 +117,12 @@ protected:
/** Run a command line and send output to given parsers. */
bool RunChild(char const* const* cmd, OutputParser* out, OutputParser* err,
- const char* workDir = CM_NULLPTR,
+ const char* workDir = nullptr,
Encoding encoding = cmProcessOutput::Auto);
/** Run VC update command line and send output to given parsers. */
bool RunUpdateCommand(char const* const* cmd, OutputParser* out,
- OutputParser* err = CM_NULLPTR,
+ OutputParser* err = nullptr,
Encoding encoding = cmProcessOutput::Auto);
/** Write xml element for one file. */
diff --git a/Source/CTest/cmParseBlanketJSCoverage.cxx b/Source/CTest/cmParseBlanketJSCoverage.cxx
index 83a7b75eb..308e6f7a3 100644
--- a/Source/CTest/cmParseBlanketJSCoverage.cxx
+++ b/Source/CTest/cmParseBlanketJSCoverage.cxx
@@ -112,17 +112,15 @@ cmParseBlanketJSCoverage::cmParseBlanketJSCoverage(
bool cmParseBlanketJSCoverage::LoadCoverageData(std::vector<std::string> files)
{
- size_t i = 0;
- std::string path;
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Found " << files.size() << " Files" << std::endl,
this->Coverage.Quiet);
- for (i = 0; i < files.size(); i++) {
+ for (std::string const& file : files) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
- "Reading JSON File " << files[i] << std::endl,
+ "Reading JSON File " << file << std::endl,
this->Coverage.Quiet);
- if (!this->ReadJSONFile(files[i])) {
+ if (!this->ReadJSONFile(file)) {
return false;
}
}
diff --git a/Source/CTest/cmParseCacheCoverage.cxx b/Source/CTest/cmParseCacheCoverage.cxx
index 629010cf1..4cd6588be 100644
--- a/Source/CTest/cmParseCacheCoverage.cxx
+++ b/Source/CTest/cmParseCacheCoverage.cxx
@@ -53,10 +53,8 @@ void cmParseCacheCoverage::RemoveUnCoveredFiles()
while (ci != this->Coverage.TotalCoverage.end()) {
cmCTestCoverageHandlerContainer::SingleFileCoverageVector& v = ci->second;
bool nothing = true;
- for (cmCTestCoverageHandlerContainer::SingleFileCoverageVector::iterator
- i = v.begin();
- i != v.end(); ++i) {
- if (*i > 0) {
+ for (int i : v) {
+ if (i > 0) {
nothing = false;
break;
}
@@ -148,7 +146,7 @@ bool cmParseCacheCoverage::ReadCMCovFile(const char* file)
cmCTestLog(this->CTest, ERROR_MESSAGE,
"Could not find mumps file for routine: " << routine
<< "\n");
- filepath = "";
+ filepath.clear();
continue; // move to next line
}
}
@@ -156,8 +154,8 @@ bool cmParseCacheCoverage::ReadCMCovFile(const char* file)
else {
// Totals in arg 0 marks the end of a routine
if (separateLine[0].substr(0, 6) == "Totals") {
- routine = ""; // at the end of this routine
- filepath = "";
+ routine.clear(); // at the end of this routine
+ filepath.clear();
continue; // move to next line
}
}
diff --git a/Source/CTest/cmParseCacheCoverage.h b/Source/CTest/cmParseCacheCoverage.h
index 005d27258..081f5fa13 100644
--- a/Source/CTest/cmParseCacheCoverage.h
+++ b/Source/CTest/cmParseCacheCoverage.h
@@ -3,7 +3,7 @@
#ifndef cmParseCacheCoverage_h
#define cmParseCacheCoverage_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmParseMumpsCoverage.h"
@@ -26,7 +26,7 @@ public:
protected:
// implement virtual from parent
- bool LoadCoverageData(const char* dir) CM_OVERRIDE;
+ bool LoadCoverageData(const char* dir) override;
// remove files with no coverage
void RemoveUnCoveredFiles();
// Read a single mcov file
diff --git a/Source/CTest/cmParseCoberturaCoverage.cxx b/Source/CTest/cmParseCoberturaCoverage.cxx
index ba55cd7b2..61ce7d48e 100644
--- a/Source/CTest/cmParseCoberturaCoverage.cxx
+++ b/Source/CTest/cmParseCoberturaCoverage.cxx
@@ -5,7 +5,6 @@
#include "cmSystemTools.h"
#include "cmXMLParser.h"
-#include "cmConfigure.h"
#include "cmsys/FStream.hxx"
#include <stdlib.h>
#include <string.h>
@@ -22,13 +21,13 @@ public:
this->SkipThisClass = false;
this->FilePaths.push_back(this->Coverage.SourceDir);
this->FilePaths.push_back(this->Coverage.BinaryDir);
- this->CurFileName = "";
+ this->CurFileName.clear();
}
- ~XMLParser() CM_OVERRIDE {}
+ ~XMLParser() override {}
protected:
- void EndElement(const std::string& name) CM_OVERRIDE
+ void EndElement(const std::string& name) override
{
if (name == "source") {
this->InSource = false;
@@ -39,7 +38,7 @@ protected:
}
}
- void CharacterDataHandler(const char* data, int length) CM_OVERRIDE
+ void CharacterDataHandler(const char* data, int length) override
{
std::string tmp;
tmp.insert(0, data, length);
@@ -51,7 +50,7 @@ protected:
}
}
- void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
+ void StartElement(const std::string& name, const char** atts) override
{
std::string FoundSource;
std::string finalpath;
@@ -68,22 +67,22 @@ protected:
<< std::endl,
this->Coverage.Quiet);
std::string filename = atts[tagCount + 1];
- this->CurFileName = "";
+ this->CurFileName.clear();
// Check if this is an absolute path that falls within our
// source or binary directories.
- for (size_t i = 0; i < FilePaths.size(); i++) {
- if (filename.find(FilePaths[i]) == 0) {
+ for (std::string const& filePath : FilePaths) {
+ if (filename.find(filePath) == 0) {
this->CurFileName = filename;
break;
}
}
- if (this->CurFileName == "") {
+ if (this->CurFileName.empty()) {
// Check if this is a path that is relative to our source or
// binary directories.
- for (size_t i = 0; i < FilePaths.size(); i++) {
- finalpath = FilePaths[i] + "/" + filename;
+ for (std::string const& filePath : FilePaths) {
+ finalpath = filePath + "/" + filename;
if (cmSystemTools::FileExists(finalpath.c_str())) {
this->CurFileName = finalpath;
break;
@@ -92,7 +91,7 @@ protected:
}
cmsys::ifstream fin(this->CurFileName.c_str());
- if (this->CurFileName == "" || !fin) {
+ if (this->CurFileName.empty() || !fin) {
this->CurFileName =
this->Coverage.BinaryDir + "/" + atts[tagCount + 1];
fin.open(this->CurFileName.c_str());
diff --git a/Source/CTest/cmParseDelphiCoverage.cxx b/Source/CTest/cmParseDelphiCoverage.cxx
index 4b781a6db..6d82cb2e7 100644
--- a/Source/CTest/cmParseDelphiCoverage.cxx
+++ b/Source/CTest/cmParseDelphiCoverage.cxx
@@ -71,7 +71,8 @@ public:
}
}
// Based up what was found, add a line to the coverageVector
- if (!beginSet.empty() && line != "" && !blockComFlag && !lineComFlag) {
+ if (!beginSet.empty() && !line.empty() && !blockComFlag &&
+ !lineComFlag) {
coverageVector.push_back(0);
} else {
coverageVector.push_back(-1);
diff --git a/Source/CTest/cmParseGTMCoverage.cxx b/Source/CTest/cmParseGTMCoverage.cxx
index e4ee699c4..9948eded2 100644
--- a/Source/CTest/cmParseGTMCoverage.cxx
+++ b/Source/CTest/cmParseGTMCoverage.cxx
@@ -182,7 +182,7 @@ bool cmParseGTMCoverage::ParseMCOVLine(std::string const& line,
// save the argument into the argument vector
args.push_back(arg);
// start on a new argument
- arg = "";
+ arg.clear();
// if we are at the end of the ), then finish while loop
if (cur == ')') {
done = true;
@@ -233,8 +233,8 @@ bool cmParseGTMCoverage::ParseMCOVLine(std::string const& line,
// To avoid double counting of line 0 of each entry point,
// Don't count the lines that do not give an explicit line
// number.
- routine = "";
- function = "";
+ routine.clear();
+ function.clear();
} else {
// this is the format for this line
// ^COVERAGE("%RSEL","SRC",count)
diff --git a/Source/CTest/cmParseGTMCoverage.h b/Source/CTest/cmParseGTMCoverage.h
index c4949d416..13afbbc26 100644
--- a/Source/CTest/cmParseGTMCoverage.h
+++ b/Source/CTest/cmParseGTMCoverage.h
@@ -3,7 +3,7 @@
#ifndef cmParseGTMCoverage_h
#define cmParseGTMCoverage_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmParseMumpsCoverage.h"
@@ -25,7 +25,7 @@ public:
protected:
// implement virtual from parent
- bool LoadCoverageData(const char* dir) CM_OVERRIDE;
+ bool LoadCoverageData(const char* dir) override;
// Read a single mcov file
bool ReadMCovFile(const char* f);
// find out what line in a mumps file (filepath) the given entry point
diff --git a/Source/CTest/cmParseJacocoCoverage.cxx b/Source/CTest/cmParseJacocoCoverage.cxx
index d15864a79..7acb5ca3f 100644
--- a/Source/CTest/cmParseJacocoCoverage.cxx
+++ b/Source/CTest/cmParseJacocoCoverage.cxx
@@ -1,7 +1,5 @@
#include "cmParseJacocoCoverage.h"
-#include "cmConfigure.h"
-
#include "cmCTest.h"
#include "cmCTestCoverageHandler.h"
#include "cmSystemTools.h"
@@ -20,25 +18,25 @@ public:
: CTest(ctest)
, Coverage(cont)
{
- this->FilePath = "";
- this->PackagePath = "";
- this->PackageName = "";
+ this->FilePath.clear();
+ this->PackagePath.clear();
+ this->PackageName.clear();
}
- ~XMLParser() CM_OVERRIDE {}
+ ~XMLParser() override {}
protected:
- void EndElement(const std::string& /*name*/) CM_OVERRIDE {}
+ void EndElement(const std::string& /*name*/) override {}
- void StartElement(const std::string& name, const char** atts) CM_OVERRIDE
+ void StartElement(const std::string& name, const char** atts) override
{
if (name == "package") {
this->PackageName = atts[1];
- this->PackagePath = "";
+ this->PackagePath.clear();
} else if (name == "sourcefile") {
std::string fileName = atts[1];
- if (this->PackagePath == "") {
+ if (this->PackagePath.empty()) {
if (!this->FindPackagePath(fileName)) {
cmCTestLog(this->CTest, ERROR_MESSAGE, "Cannot find file: "
<< this->PackageName << "/" << fileName << std::endl);
@@ -121,9 +119,8 @@ protected:
}
// Check if any of the locations found match our package.
- for (std::vector<std::string>::const_iterator fi = files.begin();
- fi != files.end(); ++fi) {
- std::string dir = cmsys::SystemTools::GetParentDirectory(*fi);
+ for (std::string const& f : files) {
+ std::string dir = cmsys::SystemTools::GetParentDirectory(f);
if (cmsys::SystemTools::StringEndsWith(dir, this->PackageName.c_str())) {
cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
"Found package directory for " << fileName << ": "
diff --git a/Source/CTest/cmParseMumpsCoverage.cxx b/Source/CTest/cmParseMumpsCoverage.cxx
index eb29f55c0..1419743fc 100644
--- a/Source/CTest/cmParseMumpsCoverage.cxx
+++ b/Source/CTest/cmParseMumpsCoverage.cxx
@@ -4,13 +4,11 @@
#include "cmCTestCoverageHandler.h"
#include "cmSystemTools.h"
-#include "cmConfigure.h"
#include "cmsys/FStream.hxx"
#include "cmsys/Glob.hxx"
#include <map>
#include <string>
#include <utility>
-#include <vector>
cmParseMumpsCoverage::cmParseMumpsCoverage(
cmCTestCoverageHandlerContainer& cont, cmCTest* ctest)
@@ -113,14 +111,12 @@ bool cmParseMumpsCoverage::LoadPackages(const char* d)
std::string pat = d;
pat += "/*.m";
glob.FindFiles(pat);
- std::vector<std::string>& files = glob.GetFiles();
- std::vector<std::string>::iterator fileIt;
- for (fileIt = files.begin(); fileIt != files.end(); ++fileIt) {
- std::string name = cmSystemTools::GetFilenameName(*fileIt);
- this->RoutineToDirectory[name.substr(0, name.size() - 2)] = *fileIt;
+ for (std::string& file : glob.GetFiles()) {
+ std::string name = cmSystemTools::GetFilenameName(file);
+ this->RoutineToDirectory[name.substr(0, name.size() - 2)] = file;
// initialze each file, this is left out until CDash is fixed
// to handle large numbers of files
- this->InitializeMumpsFile(*fileIt);
+ this->InitializeMumpsFile(file);
}
return true;
}
@@ -135,8 +131,8 @@ bool cmParseMumpsCoverage::FindMumpsFile(std::string const& routine,
return true;
}
// try some alternate names
- const char* tryname[] = { "GUX", "GTM", "ONT", CM_NULLPTR };
- for (int k = 0; tryname[k] != CM_NULLPTR; k++) {
+ const char* tryname[] = { "GUX", "GTM", "ONT", nullptr };
+ for (int k = 0; tryname[k] != nullptr; k++) {
std::string routine2 = routine + tryname[k];
i = this->RoutineToDirectory.find(routine2);
if (i != this->RoutineToDirectory.end()) {
diff --git a/Source/CTest/cmProcess.cxx b/Source/CTest/cmProcess.cxx
index f4ec6da29..f3c191b8a 100644
--- a/Source/CTest/cmProcess.cxx
+++ b/Source/CTest/cmProcess.cxx
@@ -2,14 +2,13 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmProcess.h"
-#include "cmConfigure.h"
#include "cmProcessOutput.h"
#include "cmSystemTools.h"
#include <iostream>
cmProcess::cmProcess()
{
- this->Process = CM_NULLPTR;
+ this->Process = nullptr;
this->Timeout = 0;
this->TotalTime = 0;
this->ExitValue = 0;
@@ -41,11 +40,10 @@ bool cmProcess::StartProcess()
// put the command as arg0
this->ProcessArgs.push_back(this->Command.c_str());
// now put the command arguments in
- for (std::vector<std::string>::iterator i = this->Arguments.begin();
- i != this->Arguments.end(); ++i) {
- this->ProcessArgs.push_back(i->c_str());
+ for (std::string const& arg : this->Arguments) {
+ this->ProcessArgs.push_back(arg.c_str());
}
- this->ProcessArgs.push_back(CM_NULLPTR); // null terminate the list
+ this->ProcessArgs.push_back(nullptr); // null terminate the list
this->Process = cmsysProcess_New();
cmsysProcess_SetCommand(this->Process, &*this->ProcessArgs.begin());
if (!this->WorkingDirectory.empty()) {
@@ -240,3 +238,8 @@ int cmProcess::GetExitException()
{
return cmsysProcess_GetExitException(this->Process);
}
+
+std::string cmProcess::GetExitExceptionString()
+{
+ return cmsysProcess_GetExceptionString(this->Process);
+}
diff --git a/Source/CTest/cmProcess.h b/Source/CTest/cmProcess.h
index 86e905aca..dfb02fe0d 100644
--- a/Source/CTest/cmProcess.h
+++ b/Source/CTest/cmProcess.h
@@ -38,6 +38,7 @@ public:
int GetExitValue() { return this->ExitValue; }
double GetTotalTime() { return this->TotalTime; }
int GetExitException();
+ std::string GetExitExceptionString();
/**
* Read one line of output but block for no more than timeout.
* Returns:
diff --git a/Source/Checks/cm_cxx_attribute_fallthrough.cxx b/Source/Checks/cm_cxx_attribute_fallthrough.cxx
index df43625a4..50605b70a 100644
--- a/Source/Checks/cm_cxx_attribute_fallthrough.cxx
+++ b/Source/Checks/cm_cxx_attribute_fallthrough.cxx
@@ -1,4 +1,4 @@
-int main(int argc, char* argv[])
+int main(int argc, char* [])
{
int i = 3;
switch (argc) {
diff --git a/Source/Checks/cm_cxx_auto_ptr.cxx b/Source/Checks/cm_cxx_auto_ptr.cxx
deleted file mode 100644
index d3100fdc8..000000000
--- a/Source/Checks/cm_cxx_auto_ptr.cxx
+++ /dev/null
@@ -1,18 +0,0 @@
-#include <memory>
-
-std::auto_ptr<int> get_auto_ptr()
-{
- std::auto_ptr<int> ptr;
- ptr = std::auto_ptr<int>(new int(0));
- return ptr;
-}
-
-int use_auto_ptr(std::auto_ptr<int> ptr)
-{
- return *ptr;
-}
-
-int main()
-{
- return use_auto_ptr(get_auto_ptr());
-}
diff --git a/Source/Checks/cm_cxx_eq_delete.cxx b/Source/Checks/cm_cxx_eq_delete.cxx
deleted file mode 100644
index 809e4cfcf..000000000
--- a/Source/Checks/cm_cxx_eq_delete.cxx
+++ /dev/null
@@ -1,14 +0,0 @@
-struct Foo
-{
- Foo() {}
- ~Foo() {}
- Foo(Foo const&) = delete;
- Foo& operator=(Foo const&) = delete;
- int test() const { return 0; }
-};
-
-int main()
-{
- Foo const foo;
- return foo.test();
-}
diff --git a/Source/Checks/cm_cxx_fallthrough.cxx b/Source/Checks/cm_cxx_fallthrough.cxx
index 7b35a5f29..2825bed1e 100644
--- a/Source/Checks/cm_cxx_fallthrough.cxx
+++ b/Source/Checks/cm_cxx_fallthrough.cxx
@@ -1,4 +1,4 @@
-int main(int argc, char* argv[])
+int main(int argc, char* [])
{
int i = 3;
switch (argc) {
diff --git a/Source/Checks/cm_cxx_features.cmake b/Source/Checks/cm_cxx_features.cmake
index 3b0802579..a30a5e690 100644
--- a/Source/Checks/cm_cxx_features.cmake
+++ b/Source/Checks/cm_cxx_features.cmake
@@ -14,8 +14,11 @@ function(cm_check_cxx_feature name)
CMAKE_FLAGS ${maybe_cxx_standard}
OUTPUT_VARIABLE OUTPUT
)
+ set(check_output "${OUTPUT}")
# Filter out MSBuild output that looks like a warning.
- string(REGEX REPLACE " +0 Warning\\(s\\)" "" check_output "${OUTPUT}")
+ string(REGEX REPLACE " +0 Warning\\(s\\)" "" check_output "${check_output}")
+ # Filter out warnings caused by user flags.
+ string(REGEX REPLACE "[^\n]*warning:[^\n]*-Winvalid-command-line-argument[^\n]*" "" check_output "${check_output}")
# If using the feature causes warnings, treat it as broken/unavailable.
if(check_output MATCHES "[Ww]arning")
set(CMake_HAVE_CXX_${FEATURE} OFF CACHE INTERNAL "TRY_COMPILE" FORCE)
@@ -38,8 +41,6 @@ function(cm_check_cxx_feature name)
endif()
endfunction()
-cm_check_cxx_feature(auto_ptr)
-cm_check_cxx_feature(eq_delete)
cm_check_cxx_feature(fallthrough)
if(NOT CMake_HAVE_CXX_FALLTHROUGH)
cm_check_cxx_feature(gnu_fallthrough)
@@ -51,8 +52,4 @@ cm_check_cxx_feature(make_unique)
if(CMake_HAVE_CXX_MAKE_UNIQUE)
set(CMake_HAVE_CXX_UNIQUE_PTR 1)
endif()
-cm_check_cxx_feature(nullptr)
-cm_check_cxx_feature(override)
cm_check_cxx_feature(unique_ptr)
-cm_check_cxx_feature(unordered_map)
-cm_check_cxx_feature(unordered_set)
diff --git a/Source/Checks/cm_cxx_gnu_fallthrough.cxx b/Source/Checks/cm_cxx_gnu_fallthrough.cxx
index 602109405..ebc15f431 100644
--- a/Source/Checks/cm_cxx_gnu_fallthrough.cxx
+++ b/Source/Checks/cm_cxx_gnu_fallthrough.cxx
@@ -1,4 +1,4 @@
-int main(int argc, char* argv[])
+int main(int argc, char* [])
{
int i = 3;
switch (argc) {
diff --git a/Source/Checks/cm_cxx_nullptr.cxx b/Source/Checks/cm_cxx_nullptr.cxx
deleted file mode 100644
index 500684aee..000000000
--- a/Source/Checks/cm_cxx_nullptr.cxx
+++ /dev/null
@@ -1,14 +0,0 @@
-int test(int)
-{
- return -1;
-}
-
-int test(int*)
-{
- return 0;
-}
-
-int main()
-{
- return test(nullptr);
-}
diff --git a/Source/Checks/cm_cxx_override.cxx b/Source/Checks/cm_cxx_override.cxx
deleted file mode 100644
index 5a33fbb78..000000000
--- a/Source/Checks/cm_cxx_override.cxx
+++ /dev/null
@@ -1,24 +0,0 @@
-struct Foo
-{
- Foo() {}
- virtual ~Foo() {}
- virtual int test() const = 0;
-};
-
-struct Bar : Foo
-{
- Bar() {}
- ~Bar() override {}
- int test() const override { return 0; }
-};
-
-int test(Foo const& foo)
-{
- return foo.test();
-}
-
-int main()
-{
- Bar const bar;
- return test(bar);
-}
diff --git a/Source/Checks/cm_cxx_unordered_map.cxx b/Source/Checks/cm_cxx_unordered_map.cxx
deleted file mode 100644
index be3de252b..000000000
--- a/Source/Checks/cm_cxx_unordered_map.cxx
+++ /dev/null
@@ -1,7 +0,0 @@
-#include <unordered_map>
-int main()
-{
- std::unordered_map<int, int> map;
- map[0] = 0;
- return 0;
-}
diff --git a/Source/Checks/cm_cxx_unordered_set.cxx b/Source/Checks/cm_cxx_unordered_set.cxx
deleted file mode 100644
index de4bb7765..000000000
--- a/Source/Checks/cm_cxx_unordered_set.cxx
+++ /dev/null
@@ -1,7 +0,0 @@
-#include <unordered_set>
-int main()
-{
- std::unordered_set<int> set;
- set.insert(0);
- return 0;
-}
diff --git a/Source/CursesDialog/CMakeLists.txt b/Source/CursesDialog/CMakeLists.txt
index c5ac1f1a6..6023c83eb 100644
--- a/Source/CursesDialog/CMakeLists.txt
+++ b/Source/CursesDialog/CMakeLists.txt
@@ -17,10 +17,6 @@ set( CURSES_SRCS
CursesDialog/ccmake
)
-if( NOT CMAKE_USE_SYSTEM_FORM )
- include_directories(${CMake_SOURCE_DIR}/Source/CursesDialog/form
- ${CMake_BINARY_DIR}/Source/CursesDialog/form)
-endif()
include_directories(${CURSES_INCLUDE_PATH})
diff --git a/Source/CursesDialog/ccmake.cxx b/Source/CursesDialog/ccmake.cxx
index 28a0e95b9..97d5579c2 100644
--- a/Source/CursesDialog/ccmake.cxx
+++ b/Source/CursesDialog/ccmake.cxx
@@ -1,6 +1,5 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmConfigure.h"
#include "cmCursesForm.h"
#include "cmCursesMainForm.h"
@@ -18,30 +17,29 @@
#include <vector>
static const char* cmDocumentationName[][2] = {
- { CM_NULLPTR, " ccmake - Curses Interface for CMake." },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, " ccmake - Curses Interface for CMake." },
+ { nullptr, nullptr }
};
static const char* cmDocumentationUsage[][2] = {
- { CM_NULLPTR, " ccmake <path-to-source>\n"
- " ccmake <path-to-existing-build>" },
- { CM_NULLPTR,
- "Specify a source directory to (re-)generate a build system for "
- "it in the current working directory. Specify an existing build "
- "directory to re-generate its build system." },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, " ccmake <path-to-source>\n"
+ " ccmake <path-to-existing-build>" },
+ { nullptr, "Specify a source directory to (re-)generate a build system for "
+ "it in the current working directory. Specify an existing build "
+ "directory to re-generate its build system." },
+ { nullptr, nullptr }
};
static const char* cmDocumentationUsageNote[][2] = {
- { CM_NULLPTR, "Run 'ccmake --help' for more information." },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, "Run 'ccmake --help' for more information." },
+ { nullptr, nullptr }
};
static const char* cmDocumentationOptions[]
[2] = { CMAKE_STANDARD_OPTIONS_TABLE,
- { CM_NULLPTR, CM_NULLPTR } };
+ { nullptr, nullptr } };
-cmCursesForm* cmCursesForm::CurrentForm = CM_NULLPTR;
+cmCursesForm* cmCursesForm::CurrentForm = nullptr;
extern "C" {
@@ -169,7 +167,7 @@ int main(int argc, char const* const* argv)
touchwin(stdscr);
endwin();
delete cmCursesForm::CurrentForm;
- cmCursesForm::CurrentForm = CM_NULLPTR;
+ cmCursesForm::CurrentForm = nullptr;
std::cout << std::endl << std::endl;
diff --git a/Source/CursesDialog/cmCursesBoolWidget.h b/Source/CursesDialog/cmCursesBoolWidget.h
index 90bcc2209..cdb9478e1 100644
--- a/Source/CursesDialog/cmCursesBoolWidget.h
+++ b/Source/CursesDialog/cmCursesBoolWidget.h
@@ -3,7 +3,7 @@
#ifndef cmCursesBoolWidget_h
#define cmCursesBoolWidget_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCursesStandardIncludes.h"
#include "cmCursesWidget.h"
@@ -21,7 +21,7 @@ public:
// Handle user input. Called by the container of this widget
// when this widget has focus. Returns true if the input was
// handled.
- bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
+ bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) override;
// Description:
// Set/Get the value (on/off).
diff --git a/Source/CursesDialog/cmCursesCacheEntryComposite.cxx b/Source/CursesDialog/cmCursesCacheEntryComposite.cxx
index d071c9178..e7ed09717 100644
--- a/Source/CursesDialog/cmCursesCacheEntryComposite.cxx
+++ b/Source/CursesDialog/cmCursesCacheEntryComposite.cxx
@@ -25,7 +25,7 @@ cmCursesCacheEntryComposite::cmCursesCacheEntryComposite(
{
this->Label = new cmCursesLabelWidget(this->LabelWidth, 1, 1, 1, key);
this->IsNewLabel = new cmCursesLabelWidget(1, 1, 1, 1, " ");
- this->Entry = CM_NULLPTR;
+ this->Entry = nullptr;
this->Entry = new cmCursesStringWidget(this->EntryWidth, 1, 1, 1);
}
@@ -43,7 +43,7 @@ cmCursesCacheEntryComposite::cmCursesCacheEntryComposite(
this->IsNewLabel = new cmCursesLabelWidget(1, 1, 1, 1, " ");
}
- this->Entry = CM_NULLPTR;
+ this->Entry = nullptr;
const char* value = cm->GetState()->GetCacheEntryValue(key);
assert(value);
switch (cm->GetState()->GetCacheEntryType(key)) {
@@ -72,9 +72,8 @@ cmCursesCacheEntryComposite::cmCursesCacheEntryComposite(
this->Entry = ow;
std::vector<std::string> options;
cmSystemTools::ExpandListArgument(stringsProp, options);
- for (std::vector<std::string>::iterator si = options.begin();
- si != options.end(); ++si) {
- ow->AddOption(*si);
+ for (auto const& opt : options) {
+ ow->AddOption(opt);
}
ow->SetOption(value);
} else {
@@ -104,5 +103,5 @@ const char* cmCursesCacheEntryComposite::GetValue()
if (this->Label) {
return this->Label->GetValue();
}
- return CM_NULLPTR;
+ return nullptr;
}
diff --git a/Source/CursesDialog/cmCursesCacheEntryComposite.h b/Source/CursesDialog/cmCursesCacheEntryComposite.h
index 3c500785d..54b2f1fd1 100644
--- a/Source/CursesDialog/cmCursesCacheEntryComposite.h
+++ b/Source/CursesDialog/cmCursesCacheEntryComposite.h
@@ -3,7 +3,7 @@
#ifndef cmCursesCacheEntryComposite_h
#define cmCursesCacheEntryComposite_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
diff --git a/Source/CursesDialog/cmCursesDummyWidget.h b/Source/CursesDialog/cmCursesDummyWidget.h
index d9bb6babc..c509ae773 100644
--- a/Source/CursesDialog/cmCursesDummyWidget.h
+++ b/Source/CursesDialog/cmCursesDummyWidget.h
@@ -3,7 +3,7 @@
#ifndef cmCursesDummyWidget_h
#define cmCursesDummyWidget_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCursesStandardIncludes.h"
#include "cmCursesWidget.h"
@@ -21,7 +21,7 @@ public:
// Handle user input. Called by the container of this widget
// when this widget has focus. Returns true if the input was
// handled.
- bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
+ bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) override;
};
#endif // cmCursesDummyWidget_h
diff --git a/Source/CursesDialog/cmCursesFilePathWidget.h b/Source/CursesDialog/cmCursesFilePathWidget.h
index 6ad535b99..0a304023e 100644
--- a/Source/CursesDialog/cmCursesFilePathWidget.h
+++ b/Source/CursesDialog/cmCursesFilePathWidget.h
@@ -3,7 +3,7 @@
#ifndef cmCursesFilePathWidget_h
#define cmCursesFilePathWidget_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCursesPathWidget.h"
diff --git a/Source/CursesDialog/cmCursesForm.cxx b/Source/CursesDialog/cmCursesForm.cxx
index 06c1e9c70..bd65c4a08 100644
--- a/Source/CursesDialog/cmCursesForm.cxx
+++ b/Source/CursesDialog/cmCursesForm.cxx
@@ -7,7 +7,7 @@ bool cmCursesForm::Debug = false;
cmCursesForm::cmCursesForm()
{
- this->Form = CM_NULLPTR;
+ this->Form = nullptr;
}
cmCursesForm::~cmCursesForm()
@@ -15,7 +15,7 @@ cmCursesForm::~cmCursesForm()
if (this->Form) {
unpost_form(this->Form);
free_form(this->Form);
- this->Form = CM_NULLPTR;
+ this->Form = nullptr;
}
}
diff --git a/Source/CursesDialog/cmCursesForm.h b/Source/CursesDialog/cmCursesForm.h
index 553105c76..249b34936 100644
--- a/Source/CursesDialog/cmCursesForm.h
+++ b/Source/CursesDialog/cmCursesForm.h
@@ -3,7 +3,7 @@
#ifndef cmCursesForm_h
#define cmCursesForm_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCursesStandardIncludes.h"
diff --git a/Source/CursesDialog/cmCursesLabelWidget.h b/Source/CursesDialog/cmCursesLabelWidget.h
index 267de7c8c..aab559b16 100644
--- a/Source/CursesDialog/cmCursesLabelWidget.h
+++ b/Source/CursesDialog/cmCursesLabelWidget.h
@@ -3,7 +3,7 @@
#ifndef cmCursesLabelWidget_h
#define cmCursesLabelWidget_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCursesStandardIncludes.h"
#include "cmCursesWidget.h"
@@ -19,13 +19,13 @@ class cmCursesLabelWidget : public cmCursesWidget
public:
cmCursesLabelWidget(int width, int height, int left, int top,
const std::string& name);
- ~cmCursesLabelWidget() CM_OVERRIDE;
+ ~cmCursesLabelWidget() override;
// Description:
// Handle user input. Called by the container of this widget
// when this widget has focus. Returns true if the input was
// handled
- bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
+ bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) override;
};
#endif // cmCursesLabelWidget_h
diff --git a/Source/CursesDialog/cmCursesLongMessageForm.cxx b/Source/CursesDialog/cmCursesLongMessageForm.cxx
index 7fb065d30..9bd1c11b5 100644
--- a/Source/CursesDialog/cmCursesLongMessageForm.cxx
+++ b/Source/CursesDialog/cmCursesLongMessageForm.cxx
@@ -26,8 +26,8 @@ cmCursesLongMessageForm::cmCursesLongMessageForm(
this->Messages += "\n\n";
}
this->Title = title;
- this->Fields[0] = CM_NULLPTR;
- this->Fields[1] = CM_NULLPTR;
+ this->Fields[0] = nullptr;
+ this->Fields[1] = nullptr;
}
cmCursesLongMessageForm::~cmCursesLongMessageForm()
@@ -105,7 +105,7 @@ void cmCursesLongMessageForm::Render(int /*left*/, int /*top*/, int /*width*/,
if (this->Form) {
unpost_form(this->Form);
free_form(this->Form);
- this->Form = CM_NULLPTR;
+ this->Form = nullptr;
}
const char* msg = this->Messages.c_str();
@@ -114,7 +114,7 @@ void cmCursesLongMessageForm::Render(int /*left*/, int /*top*/, int /*width*/,
if (this->Fields[0]) {
free_field(this->Fields[0]);
- this->Fields[0] = CM_NULLPTR;
+ this->Fields[0] = nullptr;
}
this->Fields[0] = new_field(y - 6, x - 2, 1, 1, 0, 0);
diff --git a/Source/CursesDialog/cmCursesLongMessageForm.h b/Source/CursesDialog/cmCursesLongMessageForm.h
index cd8e0953a..2bcc15a20 100644
--- a/Source/CursesDialog/cmCursesLongMessageForm.h
+++ b/Source/CursesDialog/cmCursesLongMessageForm.h
@@ -3,7 +3,7 @@
#ifndef cmCursesLongMessageForm_h
#define cmCursesLongMessageForm_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCursesForm.h"
#include "cmCursesStandardIncludes.h"
@@ -18,16 +18,16 @@ class cmCursesLongMessageForm : public cmCursesForm
public:
cmCursesLongMessageForm(std::vector<std::string> const& messages,
const char* title);
- ~cmCursesLongMessageForm() CM_OVERRIDE;
+ ~cmCursesLongMessageForm() override;
// Description:
// Handle user input.
- void HandleInput() CM_OVERRIDE;
+ void HandleInput() override;
// Description:
// Display form. Use a window of size width x height, starting
// at top, left.
- void Render(int left, int top, int width, int height) CM_OVERRIDE;
+ void Render(int left, int top, int width, int height) override;
// Description:
// This method should normally called only by the form.
@@ -37,7 +37,7 @@ public:
// Description:
// This method should normally called only by the form.
// The only exception is during a resize.
- void UpdateStatusBar() CM_OVERRIDE;
+ void UpdateStatusBar() override;
protected:
std::string Messages;
diff --git a/Source/CursesDialog/cmCursesMainForm.cxx b/Source/CursesDialog/cmCursesMainForm.cxx
index 026320a1f..dbd024da6 100644
--- a/Source/CursesDialog/cmCursesMainForm.cxx
+++ b/Source/CursesDialog/cmCursesMainForm.cxx
@@ -17,6 +17,7 @@
#include "cmVersion.h"
#include "cmake.h"
+#include <algorithm>
#include <stdio.h>
#include <string.h>
@@ -31,8 +32,8 @@ cmCursesMainForm::cmCursesMainForm(std::vector<std::string> const& args,
, InitialWidth(initWidth)
{
this->NumberOfPages = 0;
- this->Fields = CM_NULLPTR;
- this->Entries = CM_NULLPTR;
+ this->Fields = nullptr;
+ this->Entries = nullptr;
this->AdvancedMode = false;
this->NumberOfVisibleEntries = 0;
this->OkToGenerate = false;
@@ -59,7 +60,7 @@ cmCursesMainForm::~cmCursesMainForm()
if (this->Form) {
unpost_form(this->Form);
free_form(this->Form);
- this->Form = CM_NULLPTR;
+ this->Form = nullptr;
}
delete[] this->Fields;
@@ -70,7 +71,7 @@ cmCursesMainForm::~cmCursesMainForm()
delete this->Entries;
if (this->CMakeInstance) {
delete this->CMakeInstance;
- this->CMakeInstance = CM_NULLPTR;
+ this->CMakeInstance = nullptr;
}
}
@@ -180,7 +181,7 @@ void cmCursesMainForm::RePost()
if (this->Form) {
unpost_form(this->Form);
free_form(this->Form);
- this->Form = CM_NULLPTR;
+ this->Form = nullptr;
}
delete[] this->Fields;
if (this->AdvancedMode) {
@@ -210,7 +211,7 @@ void cmCursesMainForm::RePost()
this->Fields = new FIELD*[3 * this->NumberOfVisibleEntries + 1];
size_t cc;
for (cc = 0; cc < 3 * this->NumberOfVisibleEntries + 1; cc++) {
- this->Fields[cc] = CM_NULLPTR;
+ this->Fields[cc] = nullptr;
}
// Assign fields
@@ -239,7 +240,7 @@ void cmCursesMainForm::RePost()
this->NumberOfVisibleEntries = 1;
}
// Has to be null terminated.
- this->Fields[3 * this->NumberOfVisibleEntries] = CM_NULLPTR;
+ this->Fields[3 * this->NumberOfVisibleEntries] = nullptr;
}
void cmCursesMainForm::Render(int left, int top, int width, int height)
@@ -259,7 +260,7 @@ void cmCursesMainForm::Render(int left, int top, int width, int height)
// Delete the previous form
unpost_form(this->Form);
free_form(this->Form);
- this->Form = CM_NULLPTR;
+ this->Form = nullptr;
}
// Wrong window size
@@ -341,23 +342,21 @@ void cmCursesMainForm::PrintKeys(int process /* = 0 */)
}
// Give the current widget (if it exists), a chance to print keys
- cmCursesWidget* cw = CM_NULLPTR;
+ cmCursesWidget* cw = nullptr;
if (this->Form) {
FIELD* currentField = current_field(this->Form);
cw = reinterpret_cast<cmCursesWidget*>(field_userptr(currentField));
}
char fmt_s[] = "%s";
- if (cw == CM_NULLPTR || !cw->PrintKeys()) {
+ if (cw == nullptr || !cw->PrintKeys()) {
char firstLine[512] = "";
char secondLine[512] = "";
char thirdLine[512] = "";
if (process) {
- const char* clearLine =
- " ";
- strcpy(firstLine, clearLine);
- strcpy(secondLine, clearLine);
- strcpy(thirdLine, clearLine);
+ memset(firstLine, ' ', 68);
+ memset(secondLine, ' ', 68);
+ memset(thirdLine, ' ', 68);
} else {
if (this->OkToGenerate) {
sprintf(firstLine,
@@ -380,7 +379,7 @@ void cmCursesMainForm::PrintKeys(int process /* = 0 */)
char fmt[512] =
"Press [enter] to edit option Press [d] to delete an entry";
if (process) {
- strcpy(fmt, " ");
+ memset(fmt, ' ', 27);
}
printw(fmt_s, fmt);
curses_move(y - 3, 0);
@@ -425,7 +424,7 @@ void cmCursesMainForm::UpdateStatusBar(const char* message)
// Get the key of the current entry
FIELD* cur = current_field(this->Form);
int findex = field_index(cur);
- cmCursesWidget* lbl = CM_NULLPTR;
+ cmCursesWidget* lbl = nullptr;
if (findex >= 0) {
lbl = reinterpret_cast<cmCursesWidget*>(
field_userptr(this->Fields[findex - 2]));
@@ -456,41 +455,27 @@ void cmCursesMainForm::UpdateStatusBar(const char* message)
// Join the key, help string and pad with spaces
// (or truncate) as necessary
char bar[cmCursesMainForm::MAX_WIDTH];
- size_t i, curFieldLen = strlen(curField);
+ size_t curFieldLen = strlen(curField);
size_t helpLen = strlen(help);
- size_t width;
- if (x < cmCursesMainForm::MAX_WIDTH) {
- width = x;
- } else {
- width = cmCursesMainForm::MAX_WIDTH;
- }
+ size_t width = std::min<size_t>(x, cmCursesMainForm::MAX_WIDTH);
if (message) {
curField = message;
curFieldLen = strlen(message);
+ strncpy(bar, curField, width);
if (curFieldLen < width) {
- strcpy(bar, curField);
- for (i = curFieldLen; i < width; ++i) {
- bar[i] = ' ';
- }
- } else {
- strncpy(bar, curField, width);
+ memset(bar + curFieldLen, ' ', width - curFieldLen);
}
} else {
- if (curFieldLen >= width) {
- strncpy(bar, curField, width);
- } else {
- strcpy(bar, curField);
+ strncpy(bar, curField, width);
+ if (curFieldLen < width) {
bar[curFieldLen] = ':';
bar[curFieldLen + 1] = ' ';
- if (curFieldLen + helpLen + 2 >= width) {
- strncpy(bar + curFieldLen + 2, help, width - curFieldLen - 2);
- } else {
- strcpy(bar + curFieldLen + 2, help);
- for (i = curFieldLen + helpLen + 2; i < width; ++i) {
- bar[i] = ' ';
- }
+ strncpy(bar + curFieldLen + 2, help, width - curFieldLen - 2);
+ if (curFieldLen + helpLen + 2 < width) {
+ memset(bar + curFieldLen + helpLen + 2, ' ',
+ width - curFieldLen + helpLen + 2);
}
}
}
@@ -503,9 +488,7 @@ void cmCursesMainForm::UpdateStatusBar(const char* message)
char vertmp[128];
sprintf(vertmp, "CMake Version %s", cmVersion::GetCMakeVersion());
size_t sideSpace = (width - strlen(vertmp));
- for (i = 0; i < sideSpace; i++) {
- version[i] = ' ';
- }
+ memset(version, ' ', sideSpace);
sprintf(version + sideSpace, "%s", vertmp);
version[width] = '\0';
@@ -529,7 +512,7 @@ void cmCursesMainForm::UpdateProgress(const char* msg, float prog, void* vp)
char tmp[1024];
const char* cmsg = tmp;
if (prog >= 0) {
- sprintf(tmp, "%s %i%%", msg, (int)(100 * prog));
+ sprintf(tmp, "%s %i%%", msg, static_cast<int>(100 * prog));
} else {
cmsg = msg;
}
@@ -557,7 +540,7 @@ int cmCursesMainForm::Configure(int noconfigure)
this->FillCacheManagerFromUI();
this->CMakeInstance->SaveCache(
this->CMakeInstance->GetHomeOutputDirectory());
- this->LoadCache(CM_NULLPTR);
+ this->LoadCache(nullptr);
// Get rid of previous errors
this->Errors = std::vector<std::string>();
@@ -574,7 +557,7 @@ int cmCursesMainForm::Configure(int noconfigure)
} else {
retVal = this->CMakeInstance->Configure();
}
- this->CMakeInstance->SetProgressCallback(CM_NULLPTR, CM_NULLPTR);
+ this->CMakeInstance->SetProgressCallback(nullptr, nullptr);
keypad(stdscr, true); /* Use key symbols as KEY_DOWN */
@@ -628,7 +611,7 @@ int cmCursesMainForm::Generate()
// run the generate process
int retVal = this->CMakeInstance->Generate();
- this->CMakeInstance->SetProgressCallback(CM_NULLPTR, CM_NULLPTR);
+ this->CMakeInstance->SetProgressCallback(nullptr, nullptr);
keypad(stdscr, true); /* Use key symbols as KEY_DOWN */
if (retVal != 0 || !this->Errors.empty()) {
@@ -877,7 +860,7 @@ void cmCursesMainForm::HandleInput()
cmCursesWidget* lbl = reinterpret_cast<cmCursesWidget*>(
field_userptr(this->Fields[findex - 2]));
const char* curField = lbl->GetValue();
- const char* helpString = CM_NULLPTR;
+ const char* helpString = nullptr;
const char* existingValue =
this->CMakeInstance->GetState()->GetCacheEntryValue(curField);
@@ -962,7 +945,7 @@ void cmCursesMainForm::HandleInput()
// (findex always corresponds to the value field)
FIELD* nextCur;
if (findex == 2) {
- nextCur = CM_NULLPTR;
+ nextCur = nullptr;
} else if (findex == 3 * this->NumberOfVisibleEntries - 1) {
nextCur = this->Fields[findex - 5];
} else {
@@ -992,7 +975,7 @@ void cmCursesMainForm::HandleInput()
if (nextCur) {
// make the next or prev. current field after deletion
- nextCur = CM_NULLPTR;
+ nextCur = nullptr;
std::vector<cmCursesCacheEntryComposite*>::iterator it;
for (it = this->Entries->begin(); it != this->Entries->end();
++it) {
@@ -1041,7 +1024,7 @@ void cmCursesMainForm::JumpToCacheEntry(const char* astr)
int findex = start_index;
for (;;) {
if (!str.empty()) {
- cmCursesWidget* lbl = CM_NULLPTR;
+ cmCursesWidget* lbl = nullptr;
if (findex >= 0) {
lbl = reinterpret_cast<cmCursesWidget*>(
field_userptr(this->Fields[findex - 2]));
diff --git a/Source/CursesDialog/cmCursesMainForm.h b/Source/CursesDialog/cmCursesMainForm.h
index e35cf3ed7..7f5b3cad6 100644
--- a/Source/CursesDialog/cmCursesMainForm.h
+++ b/Source/CursesDialog/cmCursesMainForm.h
@@ -3,7 +3,7 @@
#ifndef cmCursesMainForm_h
#define cmCursesMainForm_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCursesForm.h"
#include "cmCursesStandardIncludes.h"
@@ -27,7 +27,7 @@ class cmCursesMainForm : public cmCursesForm
public:
cmCursesMainForm(std::vector<std::string> const& args, int initwidth);
- ~cmCursesMainForm() CM_OVERRIDE;
+ ~cmCursesMainForm() override;
/**
* Set the widgets which represent the cache entries.
@@ -37,13 +37,13 @@ public:
/**
* Handle user input.
*/
- void HandleInput() CM_OVERRIDE;
+ void HandleInput() override;
/**
* Display form. Use a window of size width x height, starting
* at top, left.
*/
- void Render(int left, int top, int width, int height) CM_OVERRIDE;
+ void Render(int left, int top, int width, int height) override;
/**
* Returns true if an entry with the given key is in the
@@ -64,7 +64,7 @@ public:
* exception is during a resize. The optional argument specifies the
* string to be displayed in the status bar.
*/
- void UpdateStatusBar() CM_OVERRIDE { this->UpdateStatusBar(CM_NULLPTR); }
+ void UpdateStatusBar() override { this->UpdateStatusBar(nullptr); }
virtual void UpdateStatusBar(const char* message);
/**
@@ -80,7 +80,7 @@ public:
* During a CMake run, an error handle should add errors
* to be displayed afterwards.
*/
- void AddError(const char* message, const char* title) CM_OVERRIDE;
+ void AddError(const char* message, const char* title) override;
/**
* Used to do a configure. If argument is specified, it does only the check
diff --git a/Source/CursesDialog/cmCursesOptionsWidget.cxx b/Source/CursesDialog/cmCursesOptionsWidget.cxx
index d26a98f86..a8c493380 100644
--- a/Source/CursesDialog/cmCursesOptionsWidget.cxx
+++ b/Source/CursesDialog/cmCursesOptionsWidget.cxx
@@ -75,9 +75,8 @@ void cmCursesOptionsWidget::SetOption(const std::string& value)
this->CurrentOption = 0; // default to 0 index
this->SetValue(value);
int index = 0;
- for (std::vector<std::string>::iterator i = this->Options.begin();
- i != this->Options.end(); ++i) {
- if (*i == value) {
+ for (auto const& opt : this->Options) {
+ if (opt == value) {
this->CurrentOption = index;
}
index++;
diff --git a/Source/CursesDialog/cmCursesOptionsWidget.h b/Source/CursesDialog/cmCursesOptionsWidget.h
index 7f4416f95..3e50e2d4c 100644
--- a/Source/CursesDialog/cmCursesOptionsWidget.h
+++ b/Source/CursesDialog/cmCursesOptionsWidget.h
@@ -3,7 +3,7 @@
#ifndef cmCursesOptionsWidget_h
#define cmCursesOptionsWidget_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCursesStandardIncludes.h"
#include "cmCursesWidget.h"
@@ -24,7 +24,7 @@ public:
// Handle user input. Called by the container of this widget
// when this widget has focus. Returns true if the input was
// handled.
- bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
+ bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) override;
void SetOption(const std::string&);
void AddOption(std::string const&);
void NextOption();
diff --git a/Source/CursesDialog/cmCursesPathWidget.h b/Source/CursesDialog/cmCursesPathWidget.h
index ae6c16d02..bfa0ea343 100644
--- a/Source/CursesDialog/cmCursesPathWidget.h
+++ b/Source/CursesDialog/cmCursesPathWidget.h
@@ -3,7 +3,7 @@
#ifndef cmCursesPathWidget_h
#define cmCursesPathWidget_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCursesStandardIncludes.h"
#include "cmCursesStringWidget.h"
@@ -23,9 +23,9 @@ public:
* This method is called when different keys are pressed. The
* subclass can have a special implementation handler for this.
*/
- void OnTab(cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
- void OnReturn(cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
- void OnType(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
+ void OnTab(cmCursesMainForm* fm, WINDOW* w) override;
+ void OnReturn(cmCursesMainForm* fm, WINDOW* w) override;
+ void OnType(int& key, cmCursesMainForm* fm, WINDOW* w) override;
protected:
std::string LastString;
diff --git a/Source/CursesDialog/cmCursesStandardIncludes.h b/Source/CursesDialog/cmCursesStandardIncludes.h
index 5c5950483..332d2af08 100644
--- a/Source/CursesDialog/cmCursesStandardIncludes.h
+++ b/Source/CursesDialog/cmCursesStandardIncludes.h
@@ -3,7 +3,7 @@
#ifndef cmCursesStandardIncludes_h
#define cmCursesStandardIncludes_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#if defined(__hpux)
#define _BOOL_DEFINED
diff --git a/Source/CursesDialog/cmCursesStringWidget.cxx b/Source/CursesDialog/cmCursesStringWidget.cxx
index ff189f01e..5e2a329d9 100644
--- a/Source/CursesDialog/cmCursesStringWidget.cxx
+++ b/Source/CursesDialog/cmCursesStringWidget.cxx
@@ -74,7 +74,7 @@ bool cmCursesStringWidget::HandleInput(int& key, cmCursesMainForm* fm,
return false;
}
- this->OriginalString = CM_NULLPTR;
+ this->OriginalString = nullptr;
this->Done = false;
char debugMessage[128];
@@ -188,9 +188,7 @@ bool cmCursesStringWidget::PrintKeys()
char fmt_s[] = "%s";
char firstLine[512];
// Clean the toolbar
- for (int i = 0; i < 512; i++) {
- firstLine[i] = ' ';
- }
+ memset(firstLine, ' ', sizeof(firstLine));
firstLine[511] = '\0';
curses_move(y - 4, 0);
printw(fmt_s, firstLine);
diff --git a/Source/CursesDialog/cmCursesStringWidget.h b/Source/CursesDialog/cmCursesStringWidget.h
index 5eb33666d..90310f612 100644
--- a/Source/CursesDialog/cmCursesStringWidget.h
+++ b/Source/CursesDialog/cmCursesStringWidget.h
@@ -3,7 +3,7 @@
#ifndef cmCursesStringWidget_h
#define cmCursesStringWidget_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCursesStandardIncludes.h"
#include "cmCursesWidget.h"
@@ -30,14 +30,14 @@ public:
* when this widget has focus. Returns true if the input was
* handled.
*/
- bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) CM_OVERRIDE;
+ bool HandleInput(int& key, cmCursesMainForm* fm, WINDOW* w) override;
/**
* Set/Get the string.
*/
void SetString(const std::string& value);
const char* GetString();
- const char* GetValue() CM_OVERRIDE;
+ const char* GetValue() override;
/**
* Set/Get InEdit flag. Can be used to tell the widget to leave
@@ -59,7 +59,7 @@ public:
* in the toolbar and return true. Otherwise, return false
* and the parent widget will print.
*/
- bool PrintKeys() CM_OVERRIDE;
+ bool PrintKeys() override;
protected:
// true if the widget is in edit mode
diff --git a/Source/CursesDialog/cmCursesWidget.cxx b/Source/CursesDialog/cmCursesWidget.cxx
index 054f27e29..cc07411d4 100644
--- a/Source/CursesDialog/cmCursesWidget.cxx
+++ b/Source/CursesDialog/cmCursesWidget.cxx
@@ -14,7 +14,7 @@ cmCursesWidget::~cmCursesWidget()
{
if (this->Field) {
free_field(this->Field);
- this->Field = CM_NULLPTR;
+ this->Field = nullptr;
}
}
diff --git a/Source/CursesDialog/cmCursesWidget.h b/Source/CursesDialog/cmCursesWidget.h
index 3470d7096..a44c5e6b6 100644
--- a/Source/CursesDialog/cmCursesWidget.h
+++ b/Source/CursesDialog/cmCursesWidget.h
@@ -3,7 +3,7 @@
#ifndef cmCursesWidget_h
#define cmCursesWidget_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCursesStandardIncludes.h"
#include "cmStateTypes.h"
diff --git a/Source/CursesDialog/form/.gitattributes b/Source/CursesDialog/form/.gitattributes
deleted file mode 100644
index 62d728cf6..000000000
--- a/Source/CursesDialog/form/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -format.clang-format
diff --git a/Source/CursesDialog/form/CMakeLists.txt b/Source/CursesDialog/form/CMakeLists.txt
index 0677043a9..b468f5b31 100644
--- a/Source/CursesDialog/form/CMakeLists.txt
+++ b/Source/CursesDialog/form/CMakeLists.txt
@@ -3,12 +3,9 @@
project(CMAKE_FORM)
-include_regular_expression("^.*$")
-include_directories(${CURSES_INCLUDE_PATH} "${CMAKE_CURRENT_BINARY_DIR}")
-
configure_file(cmFormConfigure.h.in "${CMAKE_CURRENT_BINARY_DIR}/cmFormConfigure.h")
-set( FORM_SRCS
+add_library(cmForm
fld_arg.c
fld_attr.c
fld_current.c
@@ -49,10 +46,16 @@ set( FORM_SRCS
fty_num.c
fty_regex.c
)
-
-include_directories(${CMAKE_FORM_SOURCE_DIR})
-add_library(cmForm ${FORM_SRCS} )
+
+target_include_directories(cmForm
+ PUBLIC
+ ${CURSES_INCLUDE_PATH}
+ ${CMAKE_FORM_BINARY_DIR}
+ ${CMAKE_FORM_SOURCE_DIR}
+ )
+
target_link_libraries(cmForm ${CURSES_LIBRARY})
+
if(CURSES_EXTRA_LIBRARY)
target_link_libraries(cmForm ${CURSES_EXTRA_LIBRARY})
endif()
diff --git a/Source/LexerParser/.gitattributes b/Source/LexerParser/.gitattributes
deleted file mode 100644
index 47eedfb4b..000000000
--- a/Source/LexerParser/.gitattributes
+++ /dev/null
@@ -1,17 +0,0 @@
-/cmCommandArgumentLexer.cxx generated
-/cmCommandArgumentLexer.h generated
-/cmCommandArgumentParser.cxx generated
-/cmCommandArgumentParserTokens.h generated
-/cmDependsJavaLexer.cxx generated
-/cmDependsJavaLexer.h generated
-/cmDependsJavaParser.cxx generated
-/cmDependsJavaParserTokens.h generated
-/cmExprLexer.cxx generated
-/cmExprLexer.h generated
-/cmExprParser.cxx generated
-/cmExprParserTokens.h generated
-/cmFortranLexer.cxx generated
-/cmFortranLexer.h generated
-/cmFortranParser.cxx generated
-/cmFortranParserTokens.h generated
-/cmListFileLexer.c generated
diff --git a/Source/LexerParser/cmCommandArgumentLexer.cxx b/Source/LexerParser/cmCommandArgumentLexer.cxx
index 12dce3758..bf6bc2f1e 100644
--- a/Source/LexerParser/cmCommandArgumentLexer.cxx
+++ b/Source/LexerParser/cmCommandArgumentLexer.cxx
@@ -1,7 +1,4 @@
#include "cmStandardLexer.h"
-#line 2 "cmCommandArgumentLexer.cxx"
-
-#line 4 "cmCommandArgumentLexer.cxx"
#define FLEXINT_H 1
#define YY_INT_ALIGNED short int
@@ -11,11 +8,221 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
-#define YY_FLEX_SUBMINOR_VERSION 1
+#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
+#ifdef yy_create_buffer
+#define cmCommandArgument_yy_create_buffer_ALREADY_DEFINED
+#else
+#define yy_create_buffer cmCommandArgument_yy_create_buffer
+#endif
+
+#ifdef yy_delete_buffer
+#define cmCommandArgument_yy_delete_buffer_ALREADY_DEFINED
+#else
+#define yy_delete_buffer cmCommandArgument_yy_delete_buffer
+#endif
+
+#ifdef yy_scan_buffer
+#define cmCommandArgument_yy_scan_buffer_ALREADY_DEFINED
+#else
+#define yy_scan_buffer cmCommandArgument_yy_scan_buffer
+#endif
+
+#ifdef yy_scan_string
+#define cmCommandArgument_yy_scan_string_ALREADY_DEFINED
+#else
+#define yy_scan_string cmCommandArgument_yy_scan_string
+#endif
+
+#ifdef yy_scan_bytes
+#define cmCommandArgument_yy_scan_bytes_ALREADY_DEFINED
+#else
+#define yy_scan_bytes cmCommandArgument_yy_scan_bytes
+#endif
+
+#ifdef yy_init_buffer
+#define cmCommandArgument_yy_init_buffer_ALREADY_DEFINED
+#else
+#define yy_init_buffer cmCommandArgument_yy_init_buffer
+#endif
+
+#ifdef yy_flush_buffer
+#define cmCommandArgument_yy_flush_buffer_ALREADY_DEFINED
+#else
+#define yy_flush_buffer cmCommandArgument_yy_flush_buffer
+#endif
+
+#ifdef yy_load_buffer_state
+#define cmCommandArgument_yy_load_buffer_state_ALREADY_DEFINED
+#else
+#define yy_load_buffer_state cmCommandArgument_yy_load_buffer_state
+#endif
+
+#ifdef yy_switch_to_buffer
+#define cmCommandArgument_yy_switch_to_buffer_ALREADY_DEFINED
+#else
+#define yy_switch_to_buffer cmCommandArgument_yy_switch_to_buffer
+#endif
+
+#ifdef yypush_buffer_state
+#define cmCommandArgument_yypush_buffer_state_ALREADY_DEFINED
+#else
+#define yypush_buffer_state cmCommandArgument_yypush_buffer_state
+#endif
+
+#ifdef yypop_buffer_state
+#define cmCommandArgument_yypop_buffer_state_ALREADY_DEFINED
+#else
+#define yypop_buffer_state cmCommandArgument_yypop_buffer_state
+#endif
+
+#ifdef yyensure_buffer_stack
+#define cmCommandArgument_yyensure_buffer_stack_ALREADY_DEFINED
+#else
+#define yyensure_buffer_stack cmCommandArgument_yyensure_buffer_stack
+#endif
+
+#ifdef yylex
+#define cmCommandArgument_yylex_ALREADY_DEFINED
+#else
+#define yylex cmCommandArgument_yylex
+#endif
+
+#ifdef yyrestart
+#define cmCommandArgument_yyrestart_ALREADY_DEFINED
+#else
+#define yyrestart cmCommandArgument_yyrestart
+#endif
+
+#ifdef yylex_init
+#define cmCommandArgument_yylex_init_ALREADY_DEFINED
+#else
+#define yylex_init cmCommandArgument_yylex_init
+#endif
+
+#ifdef yylex_init_extra
+#define cmCommandArgument_yylex_init_extra_ALREADY_DEFINED
+#else
+#define yylex_init_extra cmCommandArgument_yylex_init_extra
+#endif
+
+#ifdef yylex_destroy
+#define cmCommandArgument_yylex_destroy_ALREADY_DEFINED
+#else
+#define yylex_destroy cmCommandArgument_yylex_destroy
+#endif
+
+#ifdef yyget_debug
+#define cmCommandArgument_yyget_debug_ALREADY_DEFINED
+#else
+#define yyget_debug cmCommandArgument_yyget_debug
+#endif
+
+#ifdef yyset_debug
+#define cmCommandArgument_yyset_debug_ALREADY_DEFINED
+#else
+#define yyset_debug cmCommandArgument_yyset_debug
+#endif
+
+#ifdef yyget_extra
+#define cmCommandArgument_yyget_extra_ALREADY_DEFINED
+#else
+#define yyget_extra cmCommandArgument_yyget_extra
+#endif
+
+#ifdef yyset_extra
+#define cmCommandArgument_yyset_extra_ALREADY_DEFINED
+#else
+#define yyset_extra cmCommandArgument_yyset_extra
+#endif
+
+#ifdef yyget_in
+#define cmCommandArgument_yyget_in_ALREADY_DEFINED
+#else
+#define yyget_in cmCommandArgument_yyget_in
+#endif
+
+#ifdef yyset_in
+#define cmCommandArgument_yyset_in_ALREADY_DEFINED
+#else
+#define yyset_in cmCommandArgument_yyset_in
+#endif
+
+#ifdef yyget_out
+#define cmCommandArgument_yyget_out_ALREADY_DEFINED
+#else
+#define yyget_out cmCommandArgument_yyget_out
+#endif
+
+#ifdef yyset_out
+#define cmCommandArgument_yyset_out_ALREADY_DEFINED
+#else
+#define yyset_out cmCommandArgument_yyset_out
+#endif
+
+#ifdef yyget_leng
+#define cmCommandArgument_yyget_leng_ALREADY_DEFINED
+#else
+#define yyget_leng cmCommandArgument_yyget_leng
+#endif
+
+#ifdef yyget_text
+#define cmCommandArgument_yyget_text_ALREADY_DEFINED
+#else
+#define yyget_text cmCommandArgument_yyget_text
+#endif
+
+#ifdef yyget_lineno
+#define cmCommandArgument_yyget_lineno_ALREADY_DEFINED
+#else
+#define yyget_lineno cmCommandArgument_yyget_lineno
+#endif
+
+#ifdef yyset_lineno
+#define cmCommandArgument_yyset_lineno_ALREADY_DEFINED
+#else
+#define yyset_lineno cmCommandArgument_yyset_lineno
+#endif
+
+#ifdef yyget_column
+#define cmCommandArgument_yyget_column_ALREADY_DEFINED
+#else
+#define yyget_column cmCommandArgument_yyget_column
+#endif
+
+#ifdef yyset_column
+#define cmCommandArgument_yyset_column_ALREADY_DEFINED
+#else
+#define yyset_column cmCommandArgument_yyset_column
+#endif
+
+#ifdef yywrap
+#define cmCommandArgument_yywrap_ALREADY_DEFINED
+#else
+#define yywrap cmCommandArgument_yywrap
+#endif
+
+#ifdef yyalloc
+#define cmCommandArgument_yyalloc_ALREADY_DEFINED
+#else
+#define yyalloc cmCommandArgument_yyalloc
+#endif
+
+#ifdef yyrealloc
+#define cmCommandArgument_yyrealloc_ALREADY_DEFINED
+#else
+#define yyrealloc cmCommandArgument_yyrealloc
+#endif
+
+#ifdef yyfree
+#define cmCommandArgument_yyfree_ALREADY_DEFINED
+#else
+#define yyfree cmCommandArgument_yyfree
+#endif
+
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
@@ -86,10 +293,16 @@ typedef unsigned int flex_uint32_t;
#define UINT32_MAX (4294967295U)
#endif
+#ifndef SIZE_MAX
+#define SIZE_MAX (~(size_t)0)
+#endif
+
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
+/* begin standard C++ headers. */
+
/* TODO: this is always defined, so inline it */
#define yyconst const
@@ -102,12 +315,10 @@ typedef unsigned int flex_uint32_t;
/* Returned upon end-of-file. */
#define YY_NULL 0
-/* Promotes a possibly negative, possibly signed char to an unsigned
- * integer for use as an array index. If the signed char is negative,
- * we want to instead treat it as an 8-bit unsigned char, hence the
- * double cast.
+/* Promotes a possibly negative, possibly signed char to an
+ * integer in range [0..255] for use as an array index.
*/
-#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
+#define YY_SC_TO_UI(c) ((YY_CHAR) (c))
/* An opaque pointer. */
#ifndef YY_TYPEDEF_YY_SCANNER_T
@@ -131,20 +342,16 @@ typedef void* yyscan_t;
* definition of BEGIN.
*/
#define BEGIN yyg->yy_start = 1 + 2 *
-
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START ((yyg->yy_start - 1) / 2)
#define YYSTATE YY_START
-
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
-
/* Special action meaning "start processing a new file". */
-#define YY_NEW_FILE cmCommandArgument_yyrestart(yyin ,yyscanner )
-
+#define YY_NEW_FILE yyrestart( yyin , yyscanner )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
@@ -194,7 +401,6 @@ typedef size_t yy_size_t;
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
-
#define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
#ifndef YY_STRUCT_YY_BUFFER_STATE
@@ -254,7 +460,7 @@ struct yy_buffer_state
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
- * (via cmCommandArgument_yyrestart()), so that the user can continue scanning by
+ * (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
@@ -271,73 +477,67 @@ struct yy_buffer_state
#define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \
? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \
: NULL)
-
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top]
-void cmCommandArgument_yyrestart (FILE *input_file ,yyscan_t yyscanner );
-void cmCommandArgument_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmCommandArgument_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
-void cmCommandArgument_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmCommandArgument_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmCommandArgument_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-void cmCommandArgument_yypop_buffer_state (yyscan_t yyscanner );
-
-static void cmCommandArgument_yyensure_buffer_stack (yyscan_t yyscanner );
-static void cmCommandArgument_yy_load_buffer_state (yyscan_t yyscanner );
-static void cmCommandArgument_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner );
+void yyrestart ( FILE *input_file , yyscan_t yyscanner );
+void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size , yyscan_t yyscanner );
+void yy_delete_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yy_flush_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yypush_buffer_state ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+void yypop_buffer_state ( yyscan_t yyscanner );
-#define YY_FLUSH_BUFFER cmCommandArgument_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner)
+static void yyensure_buffer_stack ( yyscan_t yyscanner );
+static void yy_load_buffer_state ( yyscan_t yyscanner );
+static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file , yyscan_t yyscanner );
+#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER , yyscanner)
-YY_BUFFER_STATE cmCommandArgument_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmCommandArgument_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmCommandArgument_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_string ( const char *yy_str , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len , yyscan_t yyscanner );
-void *cmCommandArgument_yyalloc (yy_size_t ,yyscan_t yyscanner );
-void *cmCommandArgument_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
-void cmCommandArgument_yyfree (void * ,yyscan_t yyscanner );
-
-#define yy_new_buffer cmCommandArgument_yy_create_buffer
+void *yyalloc ( yy_size_t , yyscan_t yyscanner );
+void *yyrealloc ( void *, yy_size_t , yyscan_t yyscanner );
+void yyfree ( void * , yyscan_t yyscanner );
+#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
- cmCommandArgument_yyensure_buffer_stack (yyscanner); \
+ yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
- cmCommandArgument_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
-
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
- cmCommandArgument_yyensure_buffer_stack (yyscanner); \
+ yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
- cmCommandArgument_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
-
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define cmCommandArgument_yywrap(yyscanner) (/*CONSTCOND*/1)
#define YY_SKIP_YYWRAP
-
-typedef unsigned char YY_CHAR;
+typedef flex_uint8_t YY_CHAR;
typedef int yy_state_type;
#define yytext_ptr yytext_r
-static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
-static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner);
-static int yy_get_next_buffer (yyscan_t yyscanner );
-static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
+static yy_state_type yy_get_previous_state ( yyscan_t yyscanner );
+static yy_state_type yy_try_NUL_trans ( yy_state_type current_state , yyscan_t yyscanner);
+static int yy_get_next_buffer ( yyscan_t yyscanner );
+static void yynoreturn yy_fatal_error ( const char* msg , yyscan_t yyscanner );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
@@ -348,7 +548,6 @@ static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
yyg->yy_hold_char = *yy_cp; \
*yy_cp = '\0'; \
yyg->yy_c_buf_p = yy_cp;
-
#define YY_NUM_RULES 14
#define YY_END_OF_BUFFER 15
/* This struct is not used in this scanner,
@@ -358,14 +557,14 @@ struct yy_trans_info
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
-static yyconst flex_int16_t yy_accept[30] =
+static const flex_int16_t yy_accept[30] =
{ 0,
0, 0, 0, 0, 0, 0, 15, 9, 10, 7,
6, 14, 11, 5, 12, 13, 9, 0, 0, 4,
7, 0, 8, 2, 0, 3, 0, 1, 0
} ;
-static yyconst YY_CHAR yy_ec[256] =
+static const YY_CHAR yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
@@ -397,13 +596,13 @@ static yyconst YY_CHAR yy_ec[256] =
1, 1, 1, 1, 1
} ;
-static yyconst YY_CHAR yy_meta[12] =
+static const YY_CHAR yy_meta[12] =
{ 0,
1, 2, 3, 4, 3, 4, 4, 4, 3, 5,
3
} ;
-static yyconst flex_uint16_t yy_base[35] =
+static const flex_int16_t yy_base[35] =
{ 0,
0, 0, 31, 30, 29, 28, 36, 0, 6, 16,
0, 41, 41, 41, 0, 41, 0, 22, 22, 41,
@@ -411,7 +610,7 @@ static yyconst flex_uint16_t yy_base[35] =
21, 26, 9, 30
} ;
-static yyconst flex_int16_t yy_def[35] =
+static const flex_int16_t yy_def[35] =
{ 0,
29, 1, 1, 1, 1, 1, 29, 30, 31, 32,
33, 29, 29, 29, 34, 29, 30, 31, 18, 29,
@@ -419,7 +618,7 @@ static yyconst flex_int16_t yy_def[35] =
29, 29, 29, 29
} ;
-static yyconst flex_uint16_t yy_nxt[53] =
+static const flex_int16_t yy_nxt[53] =
{ 0,
8, 8, 9, 10, 11, 10, 10, 10, 12, 13,
14, 19, 22, 28, 27, 20, 17, 17, 17, 17,
@@ -429,7 +628,7 @@ static yyconst flex_uint16_t yy_nxt[53] =
29, 29
} ;
-static yyconst flex_int16_t yy_chk[53] =
+static const flex_int16_t yy_chk[53] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 9, 33, 27, 25, 9, 10, 10, 21, 21,
@@ -446,8 +645,6 @@ static yyconst flex_int16_t yy_chk[53] =
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
-#line 1 "cmCommandArgumentLexer.in.l"
-#line 2 "cmCommandArgumentLexer.in.l"
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
/*
@@ -456,13 +653,12 @@ This file must be translated to C++ and modified to build everywhere.
Run flex >= 2.6 like this:
- flex --nounistd -DFLEXINT_H --prefix=cmCommandArgument_yy --header-file=cmCommandArgumentLexer.h -ocmCommandArgumentLexer.cxx cmCommandArgumentLexer.in.l
+ flex --nounistd -DFLEXINT_H --noline --header-file=cmCommandArgumentLexer.h -ocmCommandArgumentLexer.cxx cmCommandArgumentLexer.in.l
Modify cmCommandArgumentLexer.cxx:
- - remove trailing whitespace: sed -i 's/\s*$//' cmCommandArgumentLexer.h cmCommandArgumentLexer.cxx
- - remove blank lines at end of file
- - #include "cmStandardLexer.h" at the top
- - add cast in cmCommandArgument_yy_scan_bytes for loop condition of _yybytes_len to size_t
+ - remove trailing whitespace: sed -i 's/\s*$//' cmCommandArgumentLexer.h cmCommandArgumentLexer.cxx
+ - remove blank lines at end of file: sed -i '${/^$/d;}' cmCommandArgumentLexer.h cmCommandArgumentLexer.cxx
+ - #include "cmStandardLexer.h" at the top: sed -i '1i#include "cmStandardLexer.h"' cmCommandArgumentLexer.cxx
*/
@@ -480,9 +676,6 @@ Modify cmCommandArgumentLexer.cxx:
/*--------------------------------------------------------------------------*/
-
-#line 484 "cmCommandArgumentLexer.cxx"
-
#define INITIAL 0
#define ESCAPES 1
#define NOESCAPES 2
@@ -525,44 +718,44 @@ struct yyguts_t
}; /* end struct yyguts_t */
-static int yy_init_globals (yyscan_t yyscanner );
+static int yy_init_globals ( yyscan_t yyscanner );
-int cmCommandArgument_yylex_init (yyscan_t* scanner);
+int yylex_init (yyscan_t* scanner);
-int cmCommandArgument_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
-int cmCommandArgument_yylex_destroy (yyscan_t yyscanner );
+int yylex_destroy ( yyscan_t yyscanner );
-int cmCommandArgument_yyget_debug (yyscan_t yyscanner );
+int yyget_debug ( yyscan_t yyscanner );
-void cmCommandArgument_yyset_debug (int debug_flag ,yyscan_t yyscanner );
+void yyset_debug ( int debug_flag , yyscan_t yyscanner );
-YY_EXTRA_TYPE cmCommandArgument_yyget_extra (yyscan_t yyscanner );
+YY_EXTRA_TYPE yyget_extra ( yyscan_t yyscanner );
-void cmCommandArgument_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
+void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t yyscanner );
-FILE *cmCommandArgument_yyget_in (yyscan_t yyscanner );
+FILE *yyget_in ( yyscan_t yyscanner );
-void cmCommandArgument_yyset_in (FILE * _in_str ,yyscan_t yyscanner );
+void yyset_in ( FILE * _in_str , yyscan_t yyscanner );
-FILE *cmCommandArgument_yyget_out (yyscan_t yyscanner );
+FILE *yyget_out ( yyscan_t yyscanner );
-void cmCommandArgument_yyset_out (FILE * _out_str ,yyscan_t yyscanner );
+void yyset_out ( FILE * _out_str , yyscan_t yyscanner );
- int cmCommandArgument_yyget_leng (yyscan_t yyscanner );
+ int yyget_leng ( yyscan_t yyscanner );
-char *cmCommandArgument_yyget_text (yyscan_t yyscanner );
+char *yyget_text ( yyscan_t yyscanner );
-int cmCommandArgument_yyget_lineno (yyscan_t yyscanner );
+int yyget_lineno ( yyscan_t yyscanner );
-void cmCommandArgument_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+void yyset_lineno ( int _line_number , yyscan_t yyscanner );
-int cmCommandArgument_yyget_column (yyscan_t yyscanner );
+int yyget_column ( yyscan_t yyscanner );
-void cmCommandArgument_yyset_column (int _column_no ,yyscan_t yyscanner );
+void yyset_column ( int _column_no , yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
@@ -570,9 +763,9 @@ void cmCommandArgument_yyset_column (int _column_no ,yyscan_t yyscanner );
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
-extern "C" int cmCommandArgument_yywrap (yyscan_t yyscanner );
+extern "C" int yywrap ( yyscan_t yyscanner );
#else
-extern int cmCommandArgument_yywrap (yyscan_t yyscanner );
+extern int yywrap ( yyscan_t yyscanner );
#endif
#endif
@@ -581,19 +774,18 @@ extern int cmCommandArgument_yywrap (yyscan_t yyscanner );
#endif
#ifndef yytext_ptr
-static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
+static void yy_flex_strncpy ( char *, const char *, int , yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
+static int yy_flex_strlen ( const char * , yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
-
#ifdef __cplusplus
-static int yyinput (yyscan_t yyscanner );
+static int yyinput ( yyscan_t yyscanner );
#else
-static int input (yyscan_t yyscanner );
+static int input ( yyscan_t yyscanner );
#endif
#endif
@@ -624,7 +816,7 @@ static int input (yyscan_t yyscanner );
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
- size_t n; \
+ int n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
@@ -637,7 +829,7 @@ static int input (yyscan_t yyscanner );
else \
{ \
errno=0; \
- while ( (result = (int) fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+ while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
@@ -678,9 +870,9 @@ static int input (yyscan_t yyscanner );
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
-extern int cmCommandArgument_yylex (yyscan_t yyscanner);
+extern int yylex (yyscan_t yyscanner);
-#define YY_DECL int cmCommandArgument_yylex (yyscan_t yyscanner)
+#define YY_DECL int yylex (yyscan_t yyscanner)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
@@ -725,19 +917,15 @@ YY_DECL
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
- cmCommandArgument_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
- cmCommandArgument_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner);
}
- cmCommandArgument_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
}
{
-#line 42 "cmCommandArgumentLexer.in.l"
-
-
-#line 740 "cmCommandArgumentLexer.cxx"
while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */
{
@@ -765,9 +953,9 @@ yy_match:
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 30 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
++yy_cp;
}
while ( yy_base[yy_current_state] != 41 );
@@ -796,7 +984,6 @@ do_action: /* This label is used only to access EOF actions. */
case 1:
YY_RULE_SETUP
-#line 44 "cmCommandArgumentLexer.in.l"
{
//std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
yyextra->AllocateParserType(yylvalp, yytext+1, strlen(yytext)-2);
@@ -805,7 +992,6 @@ YY_RULE_SETUP
YY_BREAK
case 2:
YY_RULE_SETUP
-#line 50 "cmCommandArgumentLexer.in.l"
{
//std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
yyextra->AllocateParserType(yylvalp, yytext+1, strlen(yytext)-2);
@@ -814,7 +1000,6 @@ YY_RULE_SETUP
YY_BREAK
case 3:
YY_RULE_SETUP
-#line 56 "cmCommandArgumentLexer.in.l"
{
//std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
yyextra->AllocateParserType(yylvalp, yytext+1, strlen(yytext)-2);
@@ -823,7 +1008,6 @@ YY_RULE_SETUP
YY_BREAK
case 4:
YY_RULE_SETUP
-#line 62 "cmCommandArgumentLexer.in.l"
{
//std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
//yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
@@ -833,7 +1017,6 @@ YY_RULE_SETUP
YY_BREAK
case 5:
YY_RULE_SETUP
-#line 69 "cmCommandArgumentLexer.in.l"
{
//std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
//yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
@@ -843,7 +1026,6 @@ YY_RULE_SETUP
YY_BREAK
case 6:
YY_RULE_SETUP
-#line 76 "cmCommandArgumentLexer.in.l"
{
//std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
//yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
@@ -853,7 +1035,6 @@ YY_RULE_SETUP
YY_BREAK
case 7:
YY_RULE_SETUP
-#line 83 "cmCommandArgumentLexer.in.l"
{
//std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
@@ -862,7 +1043,6 @@ YY_RULE_SETUP
YY_BREAK
case 8:
YY_RULE_SETUP
-#line 89 "cmCommandArgumentLexer.in.l"
{
if ( !yyextra->HandleEscapeSymbol(yylvalp, *(yytext+1)) )
{
@@ -874,7 +1054,6 @@ YY_RULE_SETUP
case 9:
/* rule 9 can match eol */
YY_RULE_SETUP
-#line 97 "cmCommandArgumentLexer.in.l"
{
//std::cerr << __LINE__ << " here: [" << yytext << "]" << std::endl;
yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
@@ -883,7 +1062,6 @@ YY_RULE_SETUP
YY_BREAK
case 10:
YY_RULE_SETUP
-#line 103 "cmCommandArgumentLexer.in.l"
{
//yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
yylvalp->str = yyextra->DOLLARVariable;
@@ -892,7 +1070,6 @@ YY_RULE_SETUP
YY_BREAK
case 11:
YY_RULE_SETUP
-#line 109 "cmCommandArgumentLexer.in.l"
{
//yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
yylvalp->str = yyextra->LCURLYVariable;
@@ -901,7 +1078,6 @@ YY_RULE_SETUP
YY_BREAK
case 12:
YY_RULE_SETUP
-#line 115 "cmCommandArgumentLexer.in.l"
{
//yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
yylvalp->str = yyextra->BSLASHVariable;
@@ -910,7 +1086,6 @@ YY_RULE_SETUP
YY_BREAK
case 13:
YY_RULE_SETUP
-#line 121 "cmCommandArgumentLexer.in.l"
{
//yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
yylvalp->str = yyextra->BSLASHVariable;
@@ -919,10 +1094,8 @@ YY_RULE_SETUP
YY_BREAK
case 14:
YY_RULE_SETUP
-#line 127 "cmCommandArgumentLexer.in.l"
ECHO;
YY_BREAK
-#line 925 "cmCommandArgumentLexer.cxx"
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(ESCAPES):
case YY_STATE_EOF(NOESCAPES):
@@ -942,7 +1115,7 @@ case YY_STATE_EOF(NOESCAPES):
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
- * cmCommandArgument_yylex(). If so, then we have to assure
+ * yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
@@ -1002,7 +1175,7 @@ case YY_STATE_EOF(NOESCAPES):
{
yyg->yy_did_buffer_switch_on_eof = 0;
- if ( cmCommandArgument_yywrap(yyscanner ) )
+ if ( yywrap( yyscanner ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
@@ -1056,7 +1229,7 @@ case YY_STATE_EOF(NOESCAPES):
} /* end of action switch */
} /* end of scanning one token */
} /* end of user's declarations */
-} /* end of cmCommandArgument_yylex */
+} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
@@ -1070,7 +1243,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
char *source = yyg->yytext_ptr;
- yy_size_t number_to_move, i;
+ int number_to_move, i;
int ret_val;
if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
@@ -1099,7 +1272,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
/* Try to read more data. */
/* First move last chars to start of buffer. */
- number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
+ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr - 1);
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
@@ -1135,7 +1308,8 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
- cmCommandArgument_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
+ yyrealloc( (void *) b->yy_ch_buf,
+ (yy_size_t) (b->yy_buf_size + 2) , yyscanner );
}
else
/* Can't grow it, we don't own it. */
@@ -1167,7 +1341,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
- cmCommandArgument_yyrestart(yyin ,yyscanner);
+ yyrestart( yyin , yyscanner);
}
else
@@ -1181,12 +1355,15 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
else
ret_val = EOB_ACT_CONTINUE_SCAN;
- if ((int) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
+ if ((yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
- YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) cmCommandArgument_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
+ YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc(
+ (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size , yyscanner );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+ /* "- 2" to take care of EOB's */
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2);
}
yyg->yy_n_chars += number_to_move;
@@ -1220,9 +1397,9 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 30 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
}
return yy_current_state;
@@ -1249,9 +1426,9 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 30 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
yy_is_jam = (yy_current_state == 29);
(void)yyg;
@@ -1287,7 +1464,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
else
{ /* need more input */
- int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
+ int offset = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr);
++yyg->yy_c_buf_p;
switch ( yy_get_next_buffer( yyscanner ) )
@@ -1304,13 +1481,13 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
*/
/* Reset buffer status. */
- cmCommandArgument_yyrestart(yyin ,yyscanner);
+ yyrestart( yyin , yyscanner);
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
- if ( cmCommandArgument_yywrap(yyscanner ) )
+ if ( yywrap( yyscanner ) )
return 0;
if ( ! yyg->yy_did_buffer_switch_on_eof )
@@ -1342,34 +1519,34 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @note This function does not reset the start condition to @c INITIAL .
*/
- void cmCommandArgument_yyrestart (FILE * input_file , yyscan_t yyscanner)
+ void yyrestart (FILE * input_file , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! YY_CURRENT_BUFFER ){
- cmCommandArgument_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
- cmCommandArgument_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner);
}
- cmCommandArgument_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
- cmCommandArgument_yy_load_buffer_state(yyscanner );
+ yy_init_buffer( YY_CURRENT_BUFFER, input_file , yyscanner);
+ yy_load_buffer_state( yyscanner );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
* @param yyscanner The scanner object.
*/
- void cmCommandArgument_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
+ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* TODO. We should be able to replace this entire function body
* with
- * cmCommandArgument_yypop_buffer_state();
- * cmCommandArgument_yypush_buffer_state(new_buffer);
+ * yypop_buffer_state();
+ * yypush_buffer_state(new_buffer);
*/
- cmCommandArgument_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
if ( YY_CURRENT_BUFFER == new_buffer )
return;
@@ -1382,17 +1559,17 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
- cmCommandArgument_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
/* We don't actually know whether we did this switch during
- * EOF (cmCommandArgument_yywrap()) processing, but the only time this flag
- * is looked at is after cmCommandArgument_yywrap() is called, so it's safe
+ * EOF (yywrap()) processing, but the only time this flag
+ * is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
yyg->yy_did_buffer_switch_on_eof = 1;
}
-static void cmCommandArgument_yy_load_buffer_state (yyscan_t yyscanner)
+static void yy_load_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
@@ -1407,35 +1584,35 @@ static void cmCommandArgument_yy_load_buffer_state (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @return the allocated buffer state.
*/
- YY_BUFFER_STATE cmCommandArgument_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
+ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
- b = (YY_BUFFER_STATE) cmCommandArgument_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+ b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner );
if ( ! b )
- YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yy_create_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
- b->yy_buf_size = (yy_size_t)size;
+ b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
- b->yy_ch_buf = (char *) cmCommandArgument_yyalloc(b->yy_buf_size + 2 ,yyscanner );
+ b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) , yyscanner );
if ( ! b->yy_ch_buf )
- YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yy_create_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
- cmCommandArgument_yy_init_buffer(b,file ,yyscanner);
+ yy_init_buffer( b, file , yyscanner);
return b;
}
/** Destroy the buffer.
- * @param b a buffer created with cmCommandArgument_yy_create_buffer()
+ * @param b a buffer created with yy_create_buffer()
* @param yyscanner The scanner object.
*/
- void cmCommandArgument_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
+ void yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -1446,28 +1623,28 @@ static void cmCommandArgument_yy_load_buffer_state (yyscan_t yyscanner)
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
- cmCommandArgument_yyfree((void *) b->yy_ch_buf ,yyscanner );
+ yyfree( (void *) b->yy_ch_buf , yyscanner );
- cmCommandArgument_yyfree((void *) b ,yyscanner );
+ yyfree( (void *) b , yyscanner );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
- * such as during a cmCommandArgument_yyrestart() or at EOF.
+ * such as during a yyrestart() or at EOF.
*/
- static void cmCommandArgument_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
+ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
{
int oerrno = errno;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
- cmCommandArgument_yy_flush_buffer(b ,yyscanner);
+ yy_flush_buffer( b , yyscanner);
b->yy_input_file = file;
b->yy_fill_buffer = 1;
- /* If b is the current buffer, then cmCommandArgument_yy_init_buffer was _probably_
- * called from cmCommandArgument_yyrestart() or through yy_get_next_buffer.
+ /* If b is the current buffer, then yy_init_buffer was _probably_
+ * called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
@@ -1484,7 +1661,7 @@ static void cmCommandArgument_yy_load_buffer_state (yyscan_t yyscanner)
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
* @param yyscanner The scanner object.
*/
- void cmCommandArgument_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
+ void yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
@@ -1505,7 +1682,7 @@ static void cmCommandArgument_yy_load_buffer_state (yyscan_t yyscanner)
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
- cmCommandArgument_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
}
/** Pushes the new state onto the stack. The new state becomes
@@ -1514,15 +1691,15 @@ static void cmCommandArgument_yy_load_buffer_state (yyscan_t yyscanner)
* @param new_buffer The new state.
* @param yyscanner The scanner object.
*/
-void cmCommandArgument_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
+void yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (new_buffer == NULL)
return;
- cmCommandArgument_yyensure_buffer_stack(yyscanner);
+ yyensure_buffer_stack(yyscanner);
- /* This block is copied from cmCommandArgument_yy_switch_to_buffer. */
+ /* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
@@ -1536,8 +1713,8 @@ void cmCommandArgument_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_
yyg->yy_buffer_stack_top++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
- /* copied from cmCommandArgument_yy_switch_to_buffer. */
- cmCommandArgument_yy_load_buffer_state(yyscanner );
+ /* copied from yy_switch_to_buffer. */
+ yy_load_buffer_state( yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
@@ -1545,19 +1722,19 @@ void cmCommandArgument_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_
* The next element becomes the new top.
* @param yyscanner The scanner object.
*/
-void cmCommandArgument_yypop_buffer_state (yyscan_t yyscanner)
+void yypop_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER)
return;
- cmCommandArgument_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
+ yy_delete_buffer(YY_CURRENT_BUFFER , yyscanner);
YY_CURRENT_BUFFER_LVALUE = NULL;
if (yyg->yy_buffer_stack_top > 0)
--yyg->yy_buffer_stack_top;
if (YY_CURRENT_BUFFER) {
- cmCommandArgument_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
}
@@ -1565,9 +1742,9 @@ void cmCommandArgument_yypop_buffer_state (yyscan_t yyscanner)
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
-static void cmCommandArgument_yyensure_buffer_stack (yyscan_t yyscanner)
+static void yyensure_buffer_stack (yyscan_t yyscanner)
{
- int num_to_alloc;
+ yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
@@ -1577,11 +1754,11 @@ static void cmCommandArgument_yyensure_buffer_stack (yyscan_t yyscanner)
* immediate realloc on the next call.
*/
num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
- yyg->yy_buffer_stack = (struct yy_buffer_state**)cmCommandArgument_yyalloc
+ yyg->yy_buffer_stack = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
- YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yyensure_buffer_stack()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
@@ -1596,12 +1773,12 @@ static void cmCommandArgument_yyensure_buffer_stack (yyscan_t yyscanner)
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
- yyg->yy_buffer_stack = (struct yy_buffer_state**)cmCommandArgument_yyrealloc
+ yyg->yy_buffer_stack = (struct yy_buffer_state**)yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
- YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yyensure_buffer_stack()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
@@ -1615,7 +1792,7 @@ static void cmCommandArgument_yyensure_buffer_stack (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
-YY_BUFFER_STATE cmCommandArgument_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
@@ -1625,11 +1802,11 @@ YY_BUFFER_STATE cmCommandArgument_yy_scan_buffer (char * base, yy_size_t size
/* They forgot to leave room for the EOB's. */
return NULL;
- b = (YY_BUFFER_STATE) cmCommandArgument_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+ b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner );
if ( ! b )
- YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yy_scan_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
- b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
+ b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = NULL;
@@ -1639,53 +1816,53 @@ YY_BUFFER_STATE cmCommandArgument_yy_scan_buffer (char * base, yy_size_t size
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
- cmCommandArgument_yy_switch_to_buffer(b ,yyscanner );
+ yy_switch_to_buffer( b , yyscanner );
return b;
}
-/** Setup the input buffer state to scan a string. The next call to cmCommandArgument_yylex() will
+/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
- * cmCommandArgument_yy_scan_bytes() instead.
+ * yy_scan_bytes() instead.
*/
-YY_BUFFER_STATE cmCommandArgument_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_string (const char * yystr , yyscan_t yyscanner)
{
- return cmCommandArgument_yy_scan_bytes(yystr,(int) strlen(yystr) ,yyscanner);
+ return yy_scan_bytes( yystr, (int) strlen(yystr) , yyscanner);
}
-/** Setup the input buffer state to scan the given bytes. The next call to cmCommandArgument_yylex() will
+/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
-YY_BUFFER_STATE cmCommandArgument_yy_scan_bytes (yyconst char * yybytes, int _yybytes_len , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
- yy_size_t i;
+ int i;
/* Get memory for full buffer, including space for trailing EOB's. */
- n = (yy_size_t) _yybytes_len + 2;
- buf = (char *) cmCommandArgument_yyalloc(n ,yyscanner );
+ n = (yy_size_t) (_yybytes_len + 2);
+ buf = (char *) yyalloc( n , yyscanner );
if ( ! buf )
- YY_FATAL_ERROR( "out of dynamic memory in cmCommandArgument_yy_scan_bytes()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
- for ( i = 0; i < (size_t)_yybytes_len; ++i )
+ for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
- b = cmCommandArgument_yy_scan_buffer(buf,n ,yyscanner);
+ b = yy_scan_buffer( buf, n , yyscanner);
if ( ! b )
- YY_FATAL_ERROR( "bad buffer in cmCommandArgument_yy_scan_bytes()" );
+ YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
@@ -1699,11 +1876,11 @@ YY_BUFFER_STATE cmCommandArgument_yy_scan_bytes (yyconst char * yybytes, int _
#define YY_EXIT_FAILURE 2
#endif
-static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
+static void yynoreturn yy_fatal_error (const char* msg , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
- (void) fprintf( stderr, "%s\n", msg );
+ fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
@@ -1729,7 +1906,7 @@ static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
/** Get the user-defined data for this scanner.
* @param yyscanner The scanner object.
*/
-YY_EXTRA_TYPE cmCommandArgument_yyget_extra (yyscan_t yyscanner)
+YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyextra;
@@ -1738,7 +1915,7 @@ YY_EXTRA_TYPE cmCommandArgument_yyget_extra (yyscan_t yyscanner)
/** Get the current line number.
* @param yyscanner The scanner object.
*/
-int cmCommandArgument_yyget_lineno (yyscan_t yyscanner)
+int yyget_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -1751,7 +1928,7 @@ int cmCommandArgument_yyget_lineno (yyscan_t yyscanner)
/** Get the current column number.
* @param yyscanner The scanner object.
*/
-int cmCommandArgument_yyget_column (yyscan_t yyscanner)
+int yyget_column (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -1764,7 +1941,7 @@ int cmCommandArgument_yyget_column (yyscan_t yyscanner)
/** Get the input stream.
* @param yyscanner The scanner object.
*/
-FILE *cmCommandArgument_yyget_in (yyscan_t yyscanner)
+FILE *yyget_in (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyin;
@@ -1773,7 +1950,7 @@ FILE *cmCommandArgument_yyget_in (yyscan_t yyscanner)
/** Get the output stream.
* @param yyscanner The scanner object.
*/
-FILE *cmCommandArgument_yyget_out (yyscan_t yyscanner)
+FILE *yyget_out (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyout;
@@ -1782,7 +1959,7 @@ FILE *cmCommandArgument_yyget_out (yyscan_t yyscanner)
/** Get the length of the current token.
* @param yyscanner The scanner object.
*/
-int cmCommandArgument_yyget_leng (yyscan_t yyscanner)
+int yyget_leng (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyleng;
@@ -1792,7 +1969,7 @@ int cmCommandArgument_yyget_leng (yyscan_t yyscanner)
* @param yyscanner The scanner object.
*/
-char *cmCommandArgument_yyget_text (yyscan_t yyscanner)
+char *yyget_text (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yytext;
@@ -1802,7 +1979,7 @@ char *cmCommandArgument_yyget_text (yyscan_t yyscanner)
* @param user_defined The data to be associated with this scanner.
* @param yyscanner The scanner object.
*/
-void cmCommandArgument_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
+void yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyextra = user_defined ;
@@ -1812,13 +1989,13 @@ void cmCommandArgument_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yysca
* @param _line_number line number
* @param yyscanner The scanner object.
*/
-void cmCommandArgument_yyset_lineno (int _line_number , yyscan_t yyscanner)
+void yyset_lineno (int _line_number , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* lineno is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
- YY_FATAL_ERROR( "cmCommandArgument_yyset_lineno called with no buffer" );
+ YY_FATAL_ERROR( "yyset_lineno called with no buffer" );
yylineno = _line_number;
}
@@ -1827,13 +2004,13 @@ void cmCommandArgument_yyset_lineno (int _line_number , yyscan_t yyscanner)
* @param _column_no column number
* @param yyscanner The scanner object.
*/
-void cmCommandArgument_yyset_column (int _column_no , yyscan_t yyscanner)
+void yyset_column (int _column_no , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* column is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
- YY_FATAL_ERROR( "cmCommandArgument_yyset_column called with no buffer" );
+ YY_FATAL_ERROR( "yyset_column called with no buffer" );
yycolumn = _column_no;
}
@@ -1842,27 +2019,27 @@ void cmCommandArgument_yyset_column (int _column_no , yyscan_t yyscanner)
* input buffer.
* @param _in_str A readable stream.
* @param yyscanner The scanner object.
- * @see cmCommandArgument_yy_switch_to_buffer
+ * @see yy_switch_to_buffer
*/
-void cmCommandArgument_yyset_in (FILE * _in_str , yyscan_t yyscanner)
+void yyset_in (FILE * _in_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyin = _in_str ;
}
-void cmCommandArgument_yyset_out (FILE * _out_str , yyscan_t yyscanner)
+void yyset_out (FILE * _out_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyout = _out_str ;
}
-int cmCommandArgument_yyget_debug (yyscan_t yyscanner)
+int yyget_debug (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yy_flex_debug;
}
-void cmCommandArgument_yyset_debug (int _bdebug , yyscan_t yyscanner)
+void yyset_debug (int _bdebug , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_flex_debug = _bdebug ;
@@ -1872,20 +2049,18 @@ void cmCommandArgument_yyset_debug (int _bdebug , yyscan_t yyscanner)
/* User-visible API */
-/* cmCommandArgument_yylex_init is special because it creates the scanner itself, so it is
+/* yylex_init is special because it creates the scanner itself, so it is
* the ONLY reentrant function that doesn't take the scanner as the last argument.
* That's why we explicitly handle the declaration, instead of using our macros.
*/
-
-int cmCommandArgument_yylex_init(yyscan_t* ptr_yy_globals)
-
+int yylex_init(yyscan_t* ptr_yy_globals)
{
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
- *ptr_yy_globals = (yyscan_t) cmCommandArgument_yyalloc ( sizeof( struct yyguts_t ), NULL );
+ *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), NULL );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
@@ -1898,27 +2073,25 @@ int cmCommandArgument_yylex_init(yyscan_t* ptr_yy_globals)
return yy_init_globals ( *ptr_yy_globals );
}
-/* cmCommandArgument_yylex_init_extra has the same functionality as cmCommandArgument_yylex_init, but follows the
+/* yylex_init_extra has the same functionality as yylex_init, but follows the
* convention of taking the scanner as the last argument. Note however, that
* this is a *pointer* to a scanner, as it will be allocated by this call (and
* is the reason, too, why this function also must handle its own declaration).
- * The user defined value in the first argument will be available to cmCommandArgument_yyalloc in
+ * The user defined value in the first argument will be available to yyalloc in
* the yyextra field.
*/
-
-int cmCommandArgument_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )
-
+int yylex_init_extra( YY_EXTRA_TYPE yy_user_defined, yyscan_t* ptr_yy_globals )
{
struct yyguts_t dummy_yyguts;
- cmCommandArgument_yyset_extra (yy_user_defined, &dummy_yyguts);
+ yyset_extra (yy_user_defined, &dummy_yyguts);
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
- *ptr_yy_globals = (yyscan_t) cmCommandArgument_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
+ *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
@@ -1929,7 +2102,7 @@ int cmCommandArgument_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* p
yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
- cmCommandArgument_yyset_extra (yy_user_defined, *ptr_yy_globals);
+ yyset_extra (yy_user_defined, *ptr_yy_globals);
return yy_init_globals ( *ptr_yy_globals );
}
@@ -1938,7 +2111,7 @@ static int yy_init_globals (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Initialization is the same as for the non-reentrant scanner.
- * This function is called from cmCommandArgument_yylex_destroy(), so don't allocate here.
+ * This function is called from yylex_destroy(), so don't allocate here.
*/
yyg->yy_buffer_stack = NULL;
@@ -1962,37 +2135,37 @@ static int yy_init_globals (yyscan_t yyscanner)
#endif
/* For future reference: Set errno on error, since we are called by
- * cmCommandArgument_yylex_init()
+ * yylex_init()
*/
return 0;
}
-/* cmCommandArgument_yylex_destroy is for both reentrant and non-reentrant scanners. */
-int cmCommandArgument_yylex_destroy (yyscan_t yyscanner)
+/* yylex_destroy is for both reentrant and non-reentrant scanners. */
+int yylex_destroy (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
- cmCommandArgument_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
+ yy_delete_buffer( YY_CURRENT_BUFFER , yyscanner );
YY_CURRENT_BUFFER_LVALUE = NULL;
- cmCommandArgument_yypop_buffer_state(yyscanner);
+ yypop_buffer_state(yyscanner);
}
/* Destroy the stack itself. */
- cmCommandArgument_yyfree(yyg->yy_buffer_stack ,yyscanner);
+ yyfree(yyg->yy_buffer_stack , yyscanner);
yyg->yy_buffer_stack = NULL;
/* Destroy the start condition stack. */
- cmCommandArgument_yyfree(yyg->yy_start_stack ,yyscanner );
+ yyfree( yyg->yy_start_stack , yyscanner );
yyg->yy_start_stack = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
- * cmCommandArgument_yylex() is called, initialization will occur. */
+ * yylex() is called, initialization will occur. */
yy_init_globals( yyscanner);
/* Destroy the main struct (reentrant only). */
- cmCommandArgument_yyfree ( yyscanner , yyscanner );
+ yyfree ( yyscanner , yyscanner );
yyscanner = NULL;
return 0;
}
@@ -2002,7 +2175,7 @@ int cmCommandArgument_yylex_destroy (yyscan_t yyscanner)
*/
#ifndef yytext_ptr
-static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner)
+static void yy_flex_strncpy (char* s1, const char * s2, int n , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
@@ -2014,7 +2187,7 @@ static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yysca
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
+static int yy_flex_strlen (const char * s , yyscan_t yyscanner)
{
int n;
for ( n = 0; s[n]; ++n )
@@ -2024,14 +2197,14 @@ static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
}
#endif
-void *cmCommandArgument_yyalloc (yy_size_t size , yyscan_t yyscanner)
+void *yyalloc (yy_size_t size , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
return malloc(size);
}
-void *cmCommandArgument_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
+void *yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
@@ -2046,19 +2219,15 @@ void *cmCommandArgument_yyrealloc (void * ptr, yy_size_t size , yyscan_t yysca
return realloc(ptr, size);
}
-void cmCommandArgument_yyfree (void * ptr , yyscan_t yyscanner)
+void yyfree (void * ptr , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
- free( (char *) ptr ); /* see cmCommandArgument_yyrealloc() for (char *) cast */
+ free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
-#line 127 "cmCommandArgumentLexer.in.l"
-
-
-
/*--------------------------------------------------------------------------*/
void cmCommandArgument_SetupEscapes(yyscan_t yyscanner, bool noEscapes)
{
diff --git a/Source/LexerParser/cmCommandArgumentLexer.h b/Source/LexerParser/cmCommandArgumentLexer.h
index 82e87b557..567751349 100644
--- a/Source/LexerParser/cmCommandArgumentLexer.h
+++ b/Source/LexerParser/cmCommandArgumentLexer.h
@@ -2,10 +2,6 @@
#define cmCommandArgument_yyHEADER_H 1
#define cmCommandArgument_yyIN_HEADER 1
-#line 6 "cmCommandArgumentLexer.h"
-
-#line 8 "cmCommandArgumentLexer.h"
-
#define FLEXINT_H 1
#define YY_INT_ALIGNED short int
@@ -14,11 +10,221 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
-#define YY_FLEX_SUBMINOR_VERSION 1
+#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
+#ifdef yy_create_buffer
+#define cmCommandArgument_yy_create_buffer_ALREADY_DEFINED
+#else
+#define yy_create_buffer cmCommandArgument_yy_create_buffer
+#endif
+
+#ifdef yy_delete_buffer
+#define cmCommandArgument_yy_delete_buffer_ALREADY_DEFINED
+#else
+#define yy_delete_buffer cmCommandArgument_yy_delete_buffer
+#endif
+
+#ifdef yy_scan_buffer
+#define cmCommandArgument_yy_scan_buffer_ALREADY_DEFINED
+#else
+#define yy_scan_buffer cmCommandArgument_yy_scan_buffer
+#endif
+
+#ifdef yy_scan_string
+#define cmCommandArgument_yy_scan_string_ALREADY_DEFINED
+#else
+#define yy_scan_string cmCommandArgument_yy_scan_string
+#endif
+
+#ifdef yy_scan_bytes
+#define cmCommandArgument_yy_scan_bytes_ALREADY_DEFINED
+#else
+#define yy_scan_bytes cmCommandArgument_yy_scan_bytes
+#endif
+
+#ifdef yy_init_buffer
+#define cmCommandArgument_yy_init_buffer_ALREADY_DEFINED
+#else
+#define yy_init_buffer cmCommandArgument_yy_init_buffer
+#endif
+
+#ifdef yy_flush_buffer
+#define cmCommandArgument_yy_flush_buffer_ALREADY_DEFINED
+#else
+#define yy_flush_buffer cmCommandArgument_yy_flush_buffer
+#endif
+
+#ifdef yy_load_buffer_state
+#define cmCommandArgument_yy_load_buffer_state_ALREADY_DEFINED
+#else
+#define yy_load_buffer_state cmCommandArgument_yy_load_buffer_state
+#endif
+
+#ifdef yy_switch_to_buffer
+#define cmCommandArgument_yy_switch_to_buffer_ALREADY_DEFINED
+#else
+#define yy_switch_to_buffer cmCommandArgument_yy_switch_to_buffer
+#endif
+
+#ifdef yypush_buffer_state
+#define cmCommandArgument_yypush_buffer_state_ALREADY_DEFINED
+#else
+#define yypush_buffer_state cmCommandArgument_yypush_buffer_state
+#endif
+
+#ifdef yypop_buffer_state
+#define cmCommandArgument_yypop_buffer_state_ALREADY_DEFINED
+#else
+#define yypop_buffer_state cmCommandArgument_yypop_buffer_state
+#endif
+
+#ifdef yyensure_buffer_stack
+#define cmCommandArgument_yyensure_buffer_stack_ALREADY_DEFINED
+#else
+#define yyensure_buffer_stack cmCommandArgument_yyensure_buffer_stack
+#endif
+
+#ifdef yylex
+#define cmCommandArgument_yylex_ALREADY_DEFINED
+#else
+#define yylex cmCommandArgument_yylex
+#endif
+
+#ifdef yyrestart
+#define cmCommandArgument_yyrestart_ALREADY_DEFINED
+#else
+#define yyrestart cmCommandArgument_yyrestart
+#endif
+
+#ifdef yylex_init
+#define cmCommandArgument_yylex_init_ALREADY_DEFINED
+#else
+#define yylex_init cmCommandArgument_yylex_init
+#endif
+
+#ifdef yylex_init_extra
+#define cmCommandArgument_yylex_init_extra_ALREADY_DEFINED
+#else
+#define yylex_init_extra cmCommandArgument_yylex_init_extra
+#endif
+
+#ifdef yylex_destroy
+#define cmCommandArgument_yylex_destroy_ALREADY_DEFINED
+#else
+#define yylex_destroy cmCommandArgument_yylex_destroy
+#endif
+
+#ifdef yyget_debug
+#define cmCommandArgument_yyget_debug_ALREADY_DEFINED
+#else
+#define yyget_debug cmCommandArgument_yyget_debug
+#endif
+
+#ifdef yyset_debug
+#define cmCommandArgument_yyset_debug_ALREADY_DEFINED
+#else
+#define yyset_debug cmCommandArgument_yyset_debug
+#endif
+
+#ifdef yyget_extra
+#define cmCommandArgument_yyget_extra_ALREADY_DEFINED
+#else
+#define yyget_extra cmCommandArgument_yyget_extra
+#endif
+
+#ifdef yyset_extra
+#define cmCommandArgument_yyset_extra_ALREADY_DEFINED
+#else
+#define yyset_extra cmCommandArgument_yyset_extra
+#endif
+
+#ifdef yyget_in
+#define cmCommandArgument_yyget_in_ALREADY_DEFINED
+#else
+#define yyget_in cmCommandArgument_yyget_in
+#endif
+
+#ifdef yyset_in
+#define cmCommandArgument_yyset_in_ALREADY_DEFINED
+#else
+#define yyset_in cmCommandArgument_yyset_in
+#endif
+
+#ifdef yyget_out
+#define cmCommandArgument_yyget_out_ALREADY_DEFINED
+#else
+#define yyget_out cmCommandArgument_yyget_out
+#endif
+
+#ifdef yyset_out
+#define cmCommandArgument_yyset_out_ALREADY_DEFINED
+#else
+#define yyset_out cmCommandArgument_yyset_out
+#endif
+
+#ifdef yyget_leng
+#define cmCommandArgument_yyget_leng_ALREADY_DEFINED
+#else
+#define yyget_leng cmCommandArgument_yyget_leng
+#endif
+
+#ifdef yyget_text
+#define cmCommandArgument_yyget_text_ALREADY_DEFINED
+#else
+#define yyget_text cmCommandArgument_yyget_text
+#endif
+
+#ifdef yyget_lineno
+#define cmCommandArgument_yyget_lineno_ALREADY_DEFINED
+#else
+#define yyget_lineno cmCommandArgument_yyget_lineno
+#endif
+
+#ifdef yyset_lineno
+#define cmCommandArgument_yyset_lineno_ALREADY_DEFINED
+#else
+#define yyset_lineno cmCommandArgument_yyset_lineno
+#endif
+
+#ifdef yyget_column
+#define cmCommandArgument_yyget_column_ALREADY_DEFINED
+#else
+#define yyget_column cmCommandArgument_yyget_column
+#endif
+
+#ifdef yyset_column
+#define cmCommandArgument_yyset_column_ALREADY_DEFINED
+#else
+#define yyset_column cmCommandArgument_yyset_column
+#endif
+
+#ifdef yywrap
+#define cmCommandArgument_yywrap_ALREADY_DEFINED
+#else
+#define yywrap cmCommandArgument_yywrap
+#endif
+
+#ifdef yyalloc
+#define cmCommandArgument_yyalloc_ALREADY_DEFINED
+#else
+#define yyalloc cmCommandArgument_yyalloc
+#endif
+
+#ifdef yyrealloc
+#define cmCommandArgument_yyrealloc_ALREADY_DEFINED
+#else
+#define yyrealloc cmCommandArgument_yyrealloc
+#endif
+
+#ifdef yyfree
+#define cmCommandArgument_yyfree_ALREADY_DEFINED
+#else
+#define yyfree cmCommandArgument_yyfree
+#endif
+
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
@@ -89,10 +295,16 @@ typedef unsigned int flex_uint32_t;
#define UINT32_MAX (4294967295U)
#endif
+#ifndef SIZE_MAX
+#define SIZE_MAX (~(size_t)0)
+#endif
+
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
+/* begin standard C++ headers. */
+
/* TODO: this is always defined, so inline it */
#define yyconst const
@@ -193,21 +405,21 @@ struct yy_buffer_state
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
-void cmCommandArgument_yyrestart (FILE *input_file ,yyscan_t yyscanner );
-void cmCommandArgument_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmCommandArgument_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
-void cmCommandArgument_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmCommandArgument_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmCommandArgument_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-void cmCommandArgument_yypop_buffer_state (yyscan_t yyscanner );
+void yyrestart ( FILE *input_file , yyscan_t yyscanner );
+void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size , yyscan_t yyscanner );
+void yy_delete_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yy_flush_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yypush_buffer_state ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+void yypop_buffer_state ( yyscan_t yyscanner );
-YY_BUFFER_STATE cmCommandArgument_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmCommandArgument_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmCommandArgument_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_string ( const char *yy_str , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len , yyscan_t yyscanner );
-void *cmCommandArgument_yyalloc (yy_size_t ,yyscan_t yyscanner );
-void *cmCommandArgument_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
-void cmCommandArgument_yyfree (void * ,yyscan_t yyscanner );
+void *yyalloc ( yy_size_t , yyscan_t yyscanner );
+void *yyrealloc ( void *, yy_size_t , yyscan_t yyscanner );
+void yyfree ( void * , yyscan_t yyscanner );
/* Begin user sect3 */
@@ -227,42 +439,42 @@ void cmCommandArgument_yyfree (void * ,yyscan_t yyscanner );
#define YY_EXTRA_TYPE void *
#endif
-int cmCommandArgument_yylex_init (yyscan_t* scanner);
+int yylex_init (yyscan_t* scanner);
-int cmCommandArgument_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
-int cmCommandArgument_yylex_destroy (yyscan_t yyscanner );
+int yylex_destroy ( yyscan_t yyscanner );
-int cmCommandArgument_yyget_debug (yyscan_t yyscanner );
+int yyget_debug ( yyscan_t yyscanner );
-void cmCommandArgument_yyset_debug (int debug_flag ,yyscan_t yyscanner );
+void yyset_debug ( int debug_flag , yyscan_t yyscanner );
-YY_EXTRA_TYPE cmCommandArgument_yyget_extra (yyscan_t yyscanner );
+YY_EXTRA_TYPE yyget_extra ( yyscan_t yyscanner );
-void cmCommandArgument_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
+void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t yyscanner );
-FILE *cmCommandArgument_yyget_in (yyscan_t yyscanner );
+FILE *yyget_in ( yyscan_t yyscanner );
-void cmCommandArgument_yyset_in (FILE * _in_str ,yyscan_t yyscanner );
+void yyset_in ( FILE * _in_str , yyscan_t yyscanner );
-FILE *cmCommandArgument_yyget_out (yyscan_t yyscanner );
+FILE *yyget_out ( yyscan_t yyscanner );
-void cmCommandArgument_yyset_out (FILE * _out_str ,yyscan_t yyscanner );
+void yyset_out ( FILE * _out_str , yyscan_t yyscanner );
- int cmCommandArgument_yyget_leng (yyscan_t yyscanner );
+ int yyget_leng ( yyscan_t yyscanner );
-char *cmCommandArgument_yyget_text (yyscan_t yyscanner );
+char *yyget_text ( yyscan_t yyscanner );
-int cmCommandArgument_yyget_lineno (yyscan_t yyscanner );
+int yyget_lineno ( yyscan_t yyscanner );
-void cmCommandArgument_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+void yyset_lineno ( int _line_number , yyscan_t yyscanner );
-int cmCommandArgument_yyget_column (yyscan_t yyscanner );
+int yyget_column ( yyscan_t yyscanner );
-void cmCommandArgument_yyset_column (int _column_no ,yyscan_t yyscanner );
+void yyset_column ( int _column_no , yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
@@ -270,18 +482,18 @@ void cmCommandArgument_yyset_column (int _column_no ,yyscan_t yyscanner );
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
-extern "C" int cmCommandArgument_yywrap (yyscan_t yyscanner );
+extern "C" int yywrap ( yyscan_t yyscanner );
#else
-extern int cmCommandArgument_yywrap (yyscan_t yyscanner );
+extern int yywrap ( yyscan_t yyscanner );
#endif
#endif
#ifndef yytext_ptr
-static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
+static void yy_flex_strncpy ( char *, const char *, int , yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
+static int yy_flex_strlen ( const char * , yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
@@ -309,9 +521,9 @@ static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
-extern int cmCommandArgument_yylex (yyscan_t yyscanner);
+extern int yylex (yyscan_t yyscanner);
-#define YY_DECL int cmCommandArgument_yylex (yyscan_t yyscanner)
+#define YY_DECL int yylex (yyscan_t yyscanner)
#endif /* !YY_DECL */
/* yy_get_previous_state - get the state just before the EOB char was reached */
@@ -328,9 +540,150 @@ extern int cmCommandArgument_yylex (yyscan_t yyscanner);
#undef YY_DECL
#endif
-#line 127 "cmCommandArgumentLexer.in.l"
-
+#ifndef cmCommandArgument_yy_create_buffer_ALREADY_DEFINED
+#undef yy_create_buffer
+#endif
+#ifndef cmCommandArgument_yy_delete_buffer_ALREADY_DEFINED
+#undef yy_delete_buffer
+#endif
+#ifndef cmCommandArgument_yy_scan_buffer_ALREADY_DEFINED
+#undef yy_scan_buffer
+#endif
+#ifndef cmCommandArgument_yy_scan_string_ALREADY_DEFINED
+#undef yy_scan_string
+#endif
+#ifndef cmCommandArgument_yy_scan_bytes_ALREADY_DEFINED
+#undef yy_scan_bytes
+#endif
+#ifndef cmCommandArgument_yy_init_buffer_ALREADY_DEFINED
+#undef yy_init_buffer
+#endif
+#ifndef cmCommandArgument_yy_flush_buffer_ALREADY_DEFINED
+#undef yy_flush_buffer
+#endif
+#ifndef cmCommandArgument_yy_load_buffer_state_ALREADY_DEFINED
+#undef yy_load_buffer_state
+#endif
+#ifndef cmCommandArgument_yy_switch_to_buffer_ALREADY_DEFINED
+#undef yy_switch_to_buffer
+#endif
+#ifndef cmCommandArgument_yypush_buffer_state_ALREADY_DEFINED
+#undef yypush_buffer_state
+#endif
+#ifndef cmCommandArgument_yypop_buffer_state_ALREADY_DEFINED
+#undef yypop_buffer_state
+#endif
+#ifndef cmCommandArgument_yyensure_buffer_stack_ALREADY_DEFINED
+#undef yyensure_buffer_stack
+#endif
+#ifndef cmCommandArgument_yylex_ALREADY_DEFINED
+#undef yylex
+#endif
+#ifndef cmCommandArgument_yyrestart_ALREADY_DEFINED
+#undef yyrestart
+#endif
+#ifndef cmCommandArgument_yylex_init_ALREADY_DEFINED
+#undef yylex_init
+#endif
+#ifndef cmCommandArgument_yylex_init_extra_ALREADY_DEFINED
+#undef yylex_init_extra
+#endif
+#ifndef cmCommandArgument_yylex_destroy_ALREADY_DEFINED
+#undef yylex_destroy
+#endif
+#ifndef cmCommandArgument_yyget_debug_ALREADY_DEFINED
+#undef yyget_debug
+#endif
+#ifndef cmCommandArgument_yyset_debug_ALREADY_DEFINED
+#undef yyset_debug
+#endif
+#ifndef cmCommandArgument_yyget_extra_ALREADY_DEFINED
+#undef yyget_extra
+#endif
+#ifndef cmCommandArgument_yyset_extra_ALREADY_DEFINED
+#undef yyset_extra
+#endif
+#ifndef cmCommandArgument_yyget_in_ALREADY_DEFINED
+#undef yyget_in
+#endif
+#ifndef cmCommandArgument_yyset_in_ALREADY_DEFINED
+#undef yyset_in
+#endif
+#ifndef cmCommandArgument_yyget_out_ALREADY_DEFINED
+#undef yyget_out
+#endif
+#ifndef cmCommandArgument_yyset_out_ALREADY_DEFINED
+#undef yyset_out
+#endif
+#ifndef cmCommandArgument_yyget_leng_ALREADY_DEFINED
+#undef yyget_leng
+#endif
+#ifndef cmCommandArgument_yyget_text_ALREADY_DEFINED
+#undef yyget_text
+#endif
+#ifndef cmCommandArgument_yyget_lineno_ALREADY_DEFINED
+#undef yyget_lineno
+#endif
+#ifndef cmCommandArgument_yyset_lineno_ALREADY_DEFINED
+#undef yyset_lineno
+#endif
+#ifndef cmCommandArgument_yyget_column_ALREADY_DEFINED
+#undef yyget_column
+#endif
+#ifndef cmCommandArgument_yyset_column_ALREADY_DEFINED
+#undef yyset_column
+#endif
+#ifndef cmCommandArgument_yywrap_ALREADY_DEFINED
+#undef yywrap
+#endif
+#ifndef cmCommandArgument_yyget_lval_ALREADY_DEFINED
+#undef yyget_lval
+#endif
+#ifndef cmCommandArgument_yyset_lval_ALREADY_DEFINED
+#undef yyset_lval
+#endif
+#ifndef cmCommandArgument_yyget_lloc_ALREADY_DEFINED
+#undef yyget_lloc
+#endif
+#ifndef cmCommandArgument_yyset_lloc_ALREADY_DEFINED
+#undef yyset_lloc
+#endif
+#ifndef cmCommandArgument_yyalloc_ALREADY_DEFINED
+#undef yyalloc
+#endif
+#ifndef cmCommandArgument_yyrealloc_ALREADY_DEFINED
+#undef yyrealloc
+#endif
+#ifndef cmCommandArgument_yyfree_ALREADY_DEFINED
+#undef yyfree
+#endif
+#ifndef cmCommandArgument_yytext_ALREADY_DEFINED
+#undef yytext
+#endif
+#ifndef cmCommandArgument_yyleng_ALREADY_DEFINED
+#undef yyleng
+#endif
+#ifndef cmCommandArgument_yyin_ALREADY_DEFINED
+#undef yyin
+#endif
+#ifndef cmCommandArgument_yyout_ALREADY_DEFINED
+#undef yyout
+#endif
+#ifndef cmCommandArgument_yy_flex_debug_ALREADY_DEFINED
+#undef yy_flex_debug
+#endif
+#ifndef cmCommandArgument_yylineno_ALREADY_DEFINED
+#undef yylineno
+#endif
+#ifndef cmCommandArgument_yytables_fload_ALREADY_DEFINED
+#undef yytables_fload
+#endif
+#ifndef cmCommandArgument_yytables_destroy_ALREADY_DEFINED
+#undef yytables_destroy
+#endif
+#ifndef cmCommandArgument_yyTABLES_NAME_ALREADY_DEFINED
+#undef yyTABLES_NAME
+#endif
-#line 335 "cmCommandArgumentLexer.h"
#undef cmCommandArgument_yyIN_HEADER
#endif /* cmCommandArgument_yyHEADER_H */
diff --git a/Source/LexerParser/cmCommandArgumentLexer.in.l b/Source/LexerParser/cmCommandArgumentLexer.in.l
index e3a80948c..acf18f3a7 100644
--- a/Source/LexerParser/cmCommandArgumentLexer.in.l
+++ b/Source/LexerParser/cmCommandArgumentLexer.in.l
@@ -7,13 +7,12 @@ This file must be translated to C++ and modified to build everywhere.
Run flex >= 2.6 like this:
- flex --nounistd -DFLEXINT_H --prefix=cmCommandArgument_yy --header-file=cmCommandArgumentLexer.h -ocmCommandArgumentLexer.cxx cmCommandArgumentLexer.in.l
+ flex --nounistd -DFLEXINT_H --noline --header-file=cmCommandArgumentLexer.h -ocmCommandArgumentLexer.cxx cmCommandArgumentLexer.in.l
Modify cmCommandArgumentLexer.cxx:
- - remove trailing whitespace: sed -i 's/\s*$//' cmCommandArgumentLexer.h cmCommandArgumentLexer.cxx
- - remove blank lines at end of file
- - #include "cmStandardLexer.h" at the top
- - add cast in yy_scan_bytes for loop condition of _yybytes_len to size_t
+ - remove trailing whitespace: sed -i 's/\s*$//' cmCommandArgumentLexer.h cmCommandArgumentLexer.cxx
+ - remove blank lines at end of file: sed -i '${/^$/d;}' cmCommandArgumentLexer.h cmCommandArgumentLexer.cxx
+ - #include "cmStandardLexer.h" at the top: sed -i '1i#include "cmStandardLexer.h"' cmCommandArgumentLexer.cxx
*/
@@ -32,6 +31,8 @@ Modify cmCommandArgumentLexer.cxx:
/*--------------------------------------------------------------------------*/
%}
+%option prefix="cmCommandArgument_yy"
+
%option reentrant
%option noyywrap
%option nounput
diff --git a/Source/LexerParser/cmDependsJavaLexer.cxx b/Source/LexerParser/cmDependsJavaLexer.cxx
index 8159f47bb..36cac61f9 100644
--- a/Source/LexerParser/cmDependsJavaLexer.cxx
+++ b/Source/LexerParser/cmDependsJavaLexer.cxx
@@ -1,7 +1,4 @@
#include "cmStandardLexer.h"
-#line 2 "cmDependsJavaLexer.cxx"
-
-#line 4 "cmDependsJavaLexer.cxx"
#define FLEXINT_H 1
#define YY_INT_ALIGNED short int
@@ -11,11 +8,221 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
-#define YY_FLEX_SUBMINOR_VERSION 1
+#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
+#ifdef yy_create_buffer
+#define cmDependsJava_yy_create_buffer_ALREADY_DEFINED
+#else
+#define yy_create_buffer cmDependsJava_yy_create_buffer
+#endif
+
+#ifdef yy_delete_buffer
+#define cmDependsJava_yy_delete_buffer_ALREADY_DEFINED
+#else
+#define yy_delete_buffer cmDependsJava_yy_delete_buffer
+#endif
+
+#ifdef yy_scan_buffer
+#define cmDependsJava_yy_scan_buffer_ALREADY_DEFINED
+#else
+#define yy_scan_buffer cmDependsJava_yy_scan_buffer
+#endif
+
+#ifdef yy_scan_string
+#define cmDependsJava_yy_scan_string_ALREADY_DEFINED
+#else
+#define yy_scan_string cmDependsJava_yy_scan_string
+#endif
+
+#ifdef yy_scan_bytes
+#define cmDependsJava_yy_scan_bytes_ALREADY_DEFINED
+#else
+#define yy_scan_bytes cmDependsJava_yy_scan_bytes
+#endif
+
+#ifdef yy_init_buffer
+#define cmDependsJava_yy_init_buffer_ALREADY_DEFINED
+#else
+#define yy_init_buffer cmDependsJava_yy_init_buffer
+#endif
+
+#ifdef yy_flush_buffer
+#define cmDependsJava_yy_flush_buffer_ALREADY_DEFINED
+#else
+#define yy_flush_buffer cmDependsJava_yy_flush_buffer
+#endif
+
+#ifdef yy_load_buffer_state
+#define cmDependsJava_yy_load_buffer_state_ALREADY_DEFINED
+#else
+#define yy_load_buffer_state cmDependsJava_yy_load_buffer_state
+#endif
+
+#ifdef yy_switch_to_buffer
+#define cmDependsJava_yy_switch_to_buffer_ALREADY_DEFINED
+#else
+#define yy_switch_to_buffer cmDependsJava_yy_switch_to_buffer
+#endif
+
+#ifdef yypush_buffer_state
+#define cmDependsJava_yypush_buffer_state_ALREADY_DEFINED
+#else
+#define yypush_buffer_state cmDependsJava_yypush_buffer_state
+#endif
+
+#ifdef yypop_buffer_state
+#define cmDependsJava_yypop_buffer_state_ALREADY_DEFINED
+#else
+#define yypop_buffer_state cmDependsJava_yypop_buffer_state
+#endif
+
+#ifdef yyensure_buffer_stack
+#define cmDependsJava_yyensure_buffer_stack_ALREADY_DEFINED
+#else
+#define yyensure_buffer_stack cmDependsJava_yyensure_buffer_stack
+#endif
+
+#ifdef yylex
+#define cmDependsJava_yylex_ALREADY_DEFINED
+#else
+#define yylex cmDependsJava_yylex
+#endif
+
+#ifdef yyrestart
+#define cmDependsJava_yyrestart_ALREADY_DEFINED
+#else
+#define yyrestart cmDependsJava_yyrestart
+#endif
+
+#ifdef yylex_init
+#define cmDependsJava_yylex_init_ALREADY_DEFINED
+#else
+#define yylex_init cmDependsJava_yylex_init
+#endif
+
+#ifdef yylex_init_extra
+#define cmDependsJava_yylex_init_extra_ALREADY_DEFINED
+#else
+#define yylex_init_extra cmDependsJava_yylex_init_extra
+#endif
+
+#ifdef yylex_destroy
+#define cmDependsJava_yylex_destroy_ALREADY_DEFINED
+#else
+#define yylex_destroy cmDependsJava_yylex_destroy
+#endif
+
+#ifdef yyget_debug
+#define cmDependsJava_yyget_debug_ALREADY_DEFINED
+#else
+#define yyget_debug cmDependsJava_yyget_debug
+#endif
+
+#ifdef yyset_debug
+#define cmDependsJava_yyset_debug_ALREADY_DEFINED
+#else
+#define yyset_debug cmDependsJava_yyset_debug
+#endif
+
+#ifdef yyget_extra
+#define cmDependsJava_yyget_extra_ALREADY_DEFINED
+#else
+#define yyget_extra cmDependsJava_yyget_extra
+#endif
+
+#ifdef yyset_extra
+#define cmDependsJava_yyset_extra_ALREADY_DEFINED
+#else
+#define yyset_extra cmDependsJava_yyset_extra
+#endif
+
+#ifdef yyget_in
+#define cmDependsJava_yyget_in_ALREADY_DEFINED
+#else
+#define yyget_in cmDependsJava_yyget_in
+#endif
+
+#ifdef yyset_in
+#define cmDependsJava_yyset_in_ALREADY_DEFINED
+#else
+#define yyset_in cmDependsJava_yyset_in
+#endif
+
+#ifdef yyget_out
+#define cmDependsJava_yyget_out_ALREADY_DEFINED
+#else
+#define yyget_out cmDependsJava_yyget_out
+#endif
+
+#ifdef yyset_out
+#define cmDependsJava_yyset_out_ALREADY_DEFINED
+#else
+#define yyset_out cmDependsJava_yyset_out
+#endif
+
+#ifdef yyget_leng
+#define cmDependsJava_yyget_leng_ALREADY_DEFINED
+#else
+#define yyget_leng cmDependsJava_yyget_leng
+#endif
+
+#ifdef yyget_text
+#define cmDependsJava_yyget_text_ALREADY_DEFINED
+#else
+#define yyget_text cmDependsJava_yyget_text
+#endif
+
+#ifdef yyget_lineno
+#define cmDependsJava_yyget_lineno_ALREADY_DEFINED
+#else
+#define yyget_lineno cmDependsJava_yyget_lineno
+#endif
+
+#ifdef yyset_lineno
+#define cmDependsJava_yyset_lineno_ALREADY_DEFINED
+#else
+#define yyset_lineno cmDependsJava_yyset_lineno
+#endif
+
+#ifdef yyget_column
+#define cmDependsJava_yyget_column_ALREADY_DEFINED
+#else
+#define yyget_column cmDependsJava_yyget_column
+#endif
+
+#ifdef yyset_column
+#define cmDependsJava_yyset_column_ALREADY_DEFINED
+#else
+#define yyset_column cmDependsJava_yyset_column
+#endif
+
+#ifdef yywrap
+#define cmDependsJava_yywrap_ALREADY_DEFINED
+#else
+#define yywrap cmDependsJava_yywrap
+#endif
+
+#ifdef yyalloc
+#define cmDependsJava_yyalloc_ALREADY_DEFINED
+#else
+#define yyalloc cmDependsJava_yyalloc
+#endif
+
+#ifdef yyrealloc
+#define cmDependsJava_yyrealloc_ALREADY_DEFINED
+#else
+#define yyrealloc cmDependsJava_yyrealloc
+#endif
+
+#ifdef yyfree
+#define cmDependsJava_yyfree_ALREADY_DEFINED
+#else
+#define yyfree cmDependsJava_yyfree
+#endif
+
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
@@ -86,10 +293,16 @@ typedef unsigned int flex_uint32_t;
#define UINT32_MAX (4294967295U)
#endif
+#ifndef SIZE_MAX
+#define SIZE_MAX (~(size_t)0)
+#endif
+
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
+/* begin standard C++ headers. */
+
/* TODO: this is always defined, so inline it */
#define yyconst const
@@ -102,12 +315,10 @@ typedef unsigned int flex_uint32_t;
/* Returned upon end-of-file. */
#define YY_NULL 0
-/* Promotes a possibly negative, possibly signed char to an unsigned
- * integer for use as an array index. If the signed char is negative,
- * we want to instead treat it as an 8-bit unsigned char, hence the
- * double cast.
+/* Promotes a possibly negative, possibly signed char to an
+ * integer in range [0..255] for use as an array index.
*/
-#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
+#define YY_SC_TO_UI(c) ((YY_CHAR) (c))
/* An opaque pointer. */
#ifndef YY_TYPEDEF_YY_SCANNER_T
@@ -131,20 +342,16 @@ typedef void* yyscan_t;
* definition of BEGIN.
*/
#define BEGIN yyg->yy_start = 1 + 2 *
-
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START ((yyg->yy_start - 1) / 2)
#define YYSTATE YY_START
-
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
-
/* Special action meaning "start processing a new file". */
-#define YY_NEW_FILE cmDependsJava_yyrestart(yyin ,yyscanner )
-
+#define YY_NEW_FILE yyrestart( yyin , yyscanner )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
@@ -194,7 +401,6 @@ typedef size_t yy_size_t;
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
-
#define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
#ifndef YY_STRUCT_YY_BUFFER_STATE
@@ -254,7 +460,7 @@ struct yy_buffer_state
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
- * (via cmDependsJava_yyrestart()), so that the user can continue scanning by
+ * (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
@@ -271,73 +477,67 @@ struct yy_buffer_state
#define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \
? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \
: NULL)
-
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top]
-void cmDependsJava_yyrestart (FILE *input_file ,yyscan_t yyscanner );
-void cmDependsJava_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmDependsJava_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
-void cmDependsJava_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmDependsJava_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmDependsJava_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-void cmDependsJava_yypop_buffer_state (yyscan_t yyscanner );
+void yyrestart ( FILE *input_file , yyscan_t yyscanner );
+void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size , yyscan_t yyscanner );
+void yy_delete_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yy_flush_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yypush_buffer_state ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+void yypop_buffer_state ( yyscan_t yyscanner );
-static void cmDependsJava_yyensure_buffer_stack (yyscan_t yyscanner );
-static void cmDependsJava_yy_load_buffer_state (yyscan_t yyscanner );
-static void cmDependsJava_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner );
+static void yyensure_buffer_stack ( yyscan_t yyscanner );
+static void yy_load_buffer_state ( yyscan_t yyscanner );
+static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file , yyscan_t yyscanner );
+#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER , yyscanner)
-#define YY_FLUSH_BUFFER cmDependsJava_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner)
+YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_string ( const char *yy_str , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len , yyscan_t yyscanner );
-YY_BUFFER_STATE cmDependsJava_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmDependsJava_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmDependsJava_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
-
-void *cmDependsJava_yyalloc (yy_size_t ,yyscan_t yyscanner );
-void *cmDependsJava_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
-void cmDependsJava_yyfree (void * ,yyscan_t yyscanner );
-
-#define yy_new_buffer cmDependsJava_yy_create_buffer
+void *yyalloc ( yy_size_t , yyscan_t yyscanner );
+void *yyrealloc ( void *, yy_size_t , yyscan_t yyscanner );
+void yyfree ( void * , yyscan_t yyscanner );
+#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
- cmDependsJava_yyensure_buffer_stack (yyscanner); \
+ yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
- cmDependsJava_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
-
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
- cmDependsJava_yyensure_buffer_stack (yyscanner); \
+ yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
- cmDependsJava_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
-
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define cmDependsJava_yywrap(yyscanner) (/*CONSTCOND*/1)
#define YY_SKIP_YYWRAP
-
-typedef unsigned char YY_CHAR;
+typedef flex_uint8_t YY_CHAR;
typedef int yy_state_type;
#define yytext_ptr yytext_r
-static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
-static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner);
-static int yy_get_next_buffer (yyscan_t yyscanner );
-static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
+static yy_state_type yy_get_previous_state ( yyscan_t yyscanner );
+static yy_state_type yy_try_NUL_trans ( yy_state_type current_state , yyscan_t yyscanner);
+static int yy_get_next_buffer ( yyscan_t yyscanner );
+static void yynoreturn yy_fatal_error ( const char* msg , yyscan_t yyscanner );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
@@ -348,7 +548,6 @@ static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
yyg->yy_hold_char = *yy_cp; \
*yy_cp = '\0'; \
yyg->yy_c_buf_p = yy_cp;
-
#define YY_NUM_RULES 111
#define YY_END_OF_BUFFER 112
/* This struct is not used in this scanner,
@@ -358,7 +557,7 @@ struct yy_trans_info
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
-static yyconst flex_int16_t yy_accept[327] =
+static const flex_int16_t yy_accept[327] =
{ 0,
0, 0, 0, 0, 0, 0, 112, 110, 109, 109,
77, 4, 73, 94, 60, 110, 93, 92, 105, 99,
@@ -398,7 +597,7 @@ static yyconst flex_int16_t yy_accept[327] =
27, 29, 107, 107, 45, 0
} ;
-static yyconst YY_CHAR yy_ec[256] =
+static const YY_CHAR yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
1, 2, 2, 1, 1, 1, 1, 1, 1, 1,
@@ -430,7 +629,7 @@ static yyconst YY_CHAR yy_ec[256] =
1, 1, 1, 1, 1
} ;
-static yyconst YY_CHAR yy_meta[65] =
+static const YY_CHAR yy_meta[65] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 1,
1, 1, 1, 1, 1, 1, 1, 3, 3, 3,
@@ -441,7 +640,7 @@ static yyconst YY_CHAR yy_meta[65] =
1, 1, 1, 1
} ;
-static yyconst flex_uint16_t yy_base[334] =
+static const flex_int16_t yy_base[334] =
{ 0,
0, 0, 401, 400, 62, 63, 411, 414, 414, 414,
386, 414, 414, 385, 61, 374, 414, 414, 383, 57,
@@ -482,7 +681,7 @@ static yyconst flex_uint16_t yy_base[334] =
232, 96, 235
} ;
-static yyconst flex_int16_t yy_def[334] =
+static const flex_int16_t yy_def[334] =
{ 0,
326, 1, 327, 327, 328, 328, 326, 326, 326, 326,
326, 326, 326, 326, 326, 329, 326, 326, 326, 326,
@@ -523,7 +722,7 @@ static yyconst flex_int16_t yy_def[334] =
326, 326, 326
} ;
-static yyconst flex_uint16_t yy_nxt[479] =
+static const flex_int16_t yy_nxt[479] =
{ 0,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26, 26,
@@ -579,7 +778,7 @@ static yyconst flex_uint16_t yy_nxt[479] =
326, 326, 326, 326, 326, 326, 326, 326
} ;
-static yyconst flex_int16_t yy_chk[479] =
+static const flex_int16_t yy_chk[479] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
@@ -642,8 +841,6 @@ static yyconst flex_int16_t yy_chk[479] =
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
-#line 1 "cmDependsJavaLexer.in.l"
-#line 2 "cmDependsJavaLexer.in.l"
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
/*
@@ -652,13 +849,12 @@ This file must be translated to C++ and modified to build everywhere.
Run flex >= 2.6 like this:
- flex --nounistd -DFLEXINT_H --prefix=cmDependsJava_yy --header-file=cmDependsJavaLexer.h -ocmDependsJavaLexer.cxx cmDependsJavaLexer.in.l
+ flex --nounistd -DFLEXINT_H --noline --header-file=cmDependsJavaLexer.h -ocmDependsJavaLexer.cxx cmDependsJavaLexer.in.l
Modify cmDependsJavaLexer.cxx:
- - remove trailing whitespace: sed -i 's/\s*$//' cmDependsJavaLexer.h cmDependsJavaLexer.cxx
- - remove blank lines at end of file
- - #include "cmStandardLexer.h" at the top
- - add cast in cmDependsJava_yy_scan_bytes for loop condition of _yybytes_len to size_t
+ - remove trailing whitespace: sed -i 's/\s*$//' cmDependsJavaLexer.h cmDependsJavaLexer.cxx
+ - remove blank lines at end of file: sed -i '${/^$/d;}' cmDependsJavaLexer.h cmDependsJavaLexer.cxx
+ - #include "cmStandardLexer.h" at the top: sed -i '1i#include "cmStandardLexer.h"' cmDependsJavaLexer.cxx
*/
@@ -682,9 +878,6 @@ Modify cmDependsJavaLexer.cxx:
/*--------------------------------------------------------------------------*/
-
-#line 686 "cmDependsJavaLexer.cxx"
-
#define INITIAL 0
#define comment 1
#define string 2
@@ -727,44 +920,44 @@ struct yyguts_t
}; /* end struct yyguts_t */
-static int yy_init_globals (yyscan_t yyscanner );
+static int yy_init_globals ( yyscan_t yyscanner );
-int cmDependsJava_yylex_init (yyscan_t* scanner);
+int yylex_init (yyscan_t* scanner);
-int cmDependsJava_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
-int cmDependsJava_yylex_destroy (yyscan_t yyscanner );
+int yylex_destroy ( yyscan_t yyscanner );
-int cmDependsJava_yyget_debug (yyscan_t yyscanner );
+int yyget_debug ( yyscan_t yyscanner );
-void cmDependsJava_yyset_debug (int debug_flag ,yyscan_t yyscanner );
+void yyset_debug ( int debug_flag , yyscan_t yyscanner );
-YY_EXTRA_TYPE cmDependsJava_yyget_extra (yyscan_t yyscanner );
+YY_EXTRA_TYPE yyget_extra ( yyscan_t yyscanner );
-void cmDependsJava_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
+void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t yyscanner );
-FILE *cmDependsJava_yyget_in (yyscan_t yyscanner );
+FILE *yyget_in ( yyscan_t yyscanner );
-void cmDependsJava_yyset_in (FILE * _in_str ,yyscan_t yyscanner );
+void yyset_in ( FILE * _in_str , yyscan_t yyscanner );
-FILE *cmDependsJava_yyget_out (yyscan_t yyscanner );
+FILE *yyget_out ( yyscan_t yyscanner );
-void cmDependsJava_yyset_out (FILE * _out_str ,yyscan_t yyscanner );
+void yyset_out ( FILE * _out_str , yyscan_t yyscanner );
- int cmDependsJava_yyget_leng (yyscan_t yyscanner );
+ int yyget_leng ( yyscan_t yyscanner );
-char *cmDependsJava_yyget_text (yyscan_t yyscanner );
+char *yyget_text ( yyscan_t yyscanner );
-int cmDependsJava_yyget_lineno (yyscan_t yyscanner );
+int yyget_lineno ( yyscan_t yyscanner );
-void cmDependsJava_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+void yyset_lineno ( int _line_number , yyscan_t yyscanner );
-int cmDependsJava_yyget_column (yyscan_t yyscanner );
+int yyget_column ( yyscan_t yyscanner );
-void cmDependsJava_yyset_column (int _column_no ,yyscan_t yyscanner );
+void yyset_column ( int _column_no , yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
@@ -772,32 +965,31 @@ void cmDependsJava_yyset_column (int _column_no ,yyscan_t yyscanner );
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
-extern "C" int cmDependsJava_yywrap (yyscan_t yyscanner );
+extern "C" int yywrap ( yyscan_t yyscanner );
#else
-extern int cmDependsJava_yywrap (yyscan_t yyscanner );
+extern int yywrap ( yyscan_t yyscanner );
#endif
#endif
#ifndef YY_NO_UNPUT
- static void yyunput (int c,char *buf_ptr ,yyscan_t yyscanner);
+ static void yyunput ( int c, char *buf_ptr , yyscan_t yyscanner);
#endif
#ifndef yytext_ptr
-static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
+static void yy_flex_strncpy ( char *, const char *, int , yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
+static int yy_flex_strlen ( const char * , yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
-
#ifdef __cplusplus
-static int yyinput (yyscan_t yyscanner );
+static int yyinput ( yyscan_t yyscanner );
#else
-static int input (yyscan_t yyscanner );
+static int input ( yyscan_t yyscanner );
#endif
#endif
@@ -828,7 +1020,7 @@ static int input (yyscan_t yyscanner );
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
- size_t n; \
+ int n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
@@ -841,7 +1033,7 @@ static int input (yyscan_t yyscanner );
else \
{ \
errno=0; \
- while ( (result = (int) fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+ while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
@@ -882,9 +1074,9 @@ static int input (yyscan_t yyscanner );
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
-extern int cmDependsJava_yylex (yyscan_t yyscanner);
+extern int yylex (yyscan_t yyscanner);
-#define YY_DECL int cmDependsJava_yylex (yyscan_t yyscanner)
+#define YY_DECL int yylex (yyscan_t yyscanner)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
@@ -929,18 +1121,15 @@ YY_DECL
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
- cmDependsJava_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
- cmDependsJava_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner);
}
- cmDependsJava_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
}
{
-#line 48 "cmDependsJavaLexer.in.l"
-
-#line 943 "cmDependsJavaLexer.cxx"
while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */
{
@@ -968,9 +1157,9 @@ yy_match:
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 327 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
++yy_cp;
}
while ( yy_base[yy_current_state] != 414 );
@@ -999,539 +1188,432 @@ do_action: /* This label is used only to access EOF actions. */
case 1:
YY_RULE_SETUP
-#line 49 "cmDependsJavaLexer.in.l"
{ BEGIN(comment); }
YY_BREAK
case 2:
YY_RULE_SETUP
-#line 50 "cmDependsJavaLexer.in.l"
{ BEGIN(INITIAL); }
YY_BREAK
case 3:
/* rule 3 can match eol */
YY_RULE_SETUP
-#line 51 "cmDependsJavaLexer.in.l"
{}
YY_BREAK
case 4:
YY_RULE_SETUP
-#line 53 "cmDependsJavaLexer.in.l"
{ BEGIN(string); }
YY_BREAK
case 5:
YY_RULE_SETUP
-#line 54 "cmDependsJavaLexer.in.l"
{ BEGIN(INITIAL); return jp_STRINGLITERAL; }
YY_BREAK
case 6:
YY_RULE_SETUP
-#line 55 "cmDependsJavaLexer.in.l"
{}
YY_BREAK
case 7:
YY_RULE_SETUP
-#line 57 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_ABSTRACT; }
YY_BREAK
case 8:
YY_RULE_SETUP
-#line 58 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_ASSERT; }
YY_BREAK
case 9:
YY_RULE_SETUP
-#line 59 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_BOOLEAN_TYPE; }
YY_BREAK
case 10:
YY_RULE_SETUP
-#line 60 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_BREAK; }
YY_BREAK
case 11:
YY_RULE_SETUP
-#line 61 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_BYTE_TYPE; }
YY_BREAK
case 12:
YY_RULE_SETUP
-#line 62 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_CASE; }
YY_BREAK
case 13:
YY_RULE_SETUP
-#line 63 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_CATCH; }
YY_BREAK
case 14:
YY_RULE_SETUP
-#line 64 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_CHAR_TYPE; }
YY_BREAK
case 15:
YY_RULE_SETUP
-#line 65 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_CLASS; }
YY_BREAK
case 16:
YY_RULE_SETUP
-#line 66 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_CONTINUE; }
YY_BREAK
case 17:
YY_RULE_SETUP
-#line 67 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_DEFAULT; }
YY_BREAK
case 18:
YY_RULE_SETUP
-#line 68 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_DO; }
YY_BREAK
case 19:
YY_RULE_SETUP
-#line 69 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_DOUBLE_TYPE; }
YY_BREAK
case 20:
YY_RULE_SETUP
-#line 70 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_ELSE; }
YY_BREAK
case 21:
YY_RULE_SETUP
-#line 71 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_EXTENDS; }
YY_BREAK
case 22:
YY_RULE_SETUP
-#line 72 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_FINAL; }
YY_BREAK
case 23:
YY_RULE_SETUP
-#line 73 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_FINALLY; }
YY_BREAK
case 24:
YY_RULE_SETUP
-#line 74 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_FLOAT_TYPE; }
YY_BREAK
case 25:
YY_RULE_SETUP
-#line 75 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_FOR; }
YY_BREAK
case 26:
YY_RULE_SETUP
-#line 76 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_IF; }
YY_BREAK
case 27:
YY_RULE_SETUP
-#line 77 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_IMPLEMENTS; }
YY_BREAK
case 28:
YY_RULE_SETUP
-#line 78 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_IMPORT; }
YY_BREAK
case 29:
YY_RULE_SETUP
-#line 79 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_INSTANCEOF; }
YY_BREAK
case 30:
YY_RULE_SETUP
-#line 80 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_INT_TYPE; }
YY_BREAK
case 31:
YY_RULE_SETUP
-#line 81 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_INTERFACE; }
YY_BREAK
case 32:
YY_RULE_SETUP
-#line 82 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_LONG_TYPE; }
YY_BREAK
case 33:
YY_RULE_SETUP
-#line 83 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_NATIVE; }
YY_BREAK
case 34:
YY_RULE_SETUP
-#line 84 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_NEW; }
YY_BREAK
case 35:
YY_RULE_SETUP
-#line 85 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_PACKAGE; }
YY_BREAK
case 36:
YY_RULE_SETUP
-#line 86 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_PRIVATE; }
YY_BREAK
case 37:
YY_RULE_SETUP
-#line 87 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_PROTECTED; }
YY_BREAK
case 38:
YY_RULE_SETUP
-#line 88 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_PUBLIC; }
YY_BREAK
case 39:
YY_RULE_SETUP
-#line 89 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_RETURN; }
YY_BREAK
case 40:
YY_RULE_SETUP
-#line 90 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_SHORT_TYPE; }
YY_BREAK
case 41:
YY_RULE_SETUP
-#line 91 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_STATIC; }
YY_BREAK
case 42:
YY_RULE_SETUP
-#line 92 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_STRICTFP; }
YY_BREAK
case 43:
YY_RULE_SETUP
-#line 93 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_SUPER; }
YY_BREAK
case 44:
YY_RULE_SETUP
-#line 94 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_SWITCH; }
YY_BREAK
case 45:
YY_RULE_SETUP
-#line 95 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_SYNCHRONIZED; }
YY_BREAK
case 46:
YY_RULE_SETUP
-#line 96 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_THIS; }
YY_BREAK
case 47:
YY_RULE_SETUP
-#line 97 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_THROW; }
YY_BREAK
case 48:
YY_RULE_SETUP
-#line 98 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_THROWS; }
YY_BREAK
case 49:
YY_RULE_SETUP
-#line 99 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_TRANSIENT; }
YY_BREAK
case 50:
YY_RULE_SETUP
-#line 100 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_TRY; }
YY_BREAK
case 51:
YY_RULE_SETUP
-#line 101 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_VOID; }
YY_BREAK
case 52:
YY_RULE_SETUP
-#line 102 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_VOLATILE; }
YY_BREAK
case 53:
YY_RULE_SETUP
-#line 103 "cmDependsJavaLexer.in.l"
{ KEYWORD; return jp_WHILE; }
YY_BREAK
case 54:
YY_RULE_SETUP
-#line 105 "cmDependsJavaLexer.in.l"
{ PRIMITIVE; return jp_BOOLEANLITERAL; }
YY_BREAK
case 55:
/* rule 55 can match eol */
YY_RULE_SETUP
-#line 106 "cmDependsJavaLexer.in.l"
{ PRIMITIVE; return jp_CHARACTERLITERAL; }
YY_BREAK
case 56:
YY_RULE_SETUP
-#line 107 "cmDependsJavaLexer.in.l"
{ PRIMITIVE; return jp_DECIMALINTEGERLITERAL; }
YY_BREAK
case 57:
YY_RULE_SETUP
-#line 108 "cmDependsJavaLexer.in.l"
{ PRIMITIVE; return jp_FLOATINGPOINTLITERAL; }
YY_BREAK
case 58:
YY_RULE_SETUP
-#line 109 "cmDependsJavaLexer.in.l"
{ PRIMITIVE; return jp_HEXINTEGERLITERAL; }
YY_BREAK
case 59:
YY_RULE_SETUP
-#line 110 "cmDependsJavaLexer.in.l"
{ PRIMITIVE; return jp_NULLLITERAL; }
YY_BREAK
case 60:
YY_RULE_SETUP
-#line 112 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_AND; }
YY_BREAK
case 61:
YY_RULE_SETUP
-#line 113 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_ANDAND; }
YY_BREAK
case 62:
YY_RULE_SETUP
-#line 114 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_ANDEQUALS; }
YY_BREAK
case 63:
YY_RULE_SETUP
-#line 115 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_BRACKETEND; }
YY_BREAK
case 64:
YY_RULE_SETUP
-#line 116 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_BRACKETSTART; }
YY_BREAK
case 65:
YY_RULE_SETUP
-#line 117 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_CARROT; }
YY_BREAK
case 66:
YY_RULE_SETUP
-#line 118 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_CARROTEQUALS; }
YY_BREAK
case 67:
YY_RULE_SETUP
-#line 119 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_COLON; }
YY_BREAK
case 68:
YY_RULE_SETUP
-#line 120 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_COMMA; }
YY_BREAK
case 69:
YY_RULE_SETUP
-#line 121 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_CURLYEND; }
YY_BREAK
case 70:
YY_RULE_SETUP
-#line 122 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_CURLYSTART; }
YY_BREAK
case 71:
YY_RULE_SETUP
-#line 123 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_DIVIDE; }
YY_BREAK
case 72:
YY_RULE_SETUP
-#line 124 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_DIVIDEEQUALS; }
YY_BREAK
case 73:
YY_RULE_SETUP
-#line 125 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_DOLLAR; }
YY_BREAK
case 74:
YY_RULE_SETUP
-#line 126 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_DOT; }
YY_BREAK
case 75:
YY_RULE_SETUP
-#line 127 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_EQUALS; }
YY_BREAK
case 76:
YY_RULE_SETUP
-#line 128 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_EQUALSEQUALS; }
YY_BREAK
case 77:
YY_RULE_SETUP
-#line 129 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_EXCLAMATION; }
YY_BREAK
case 78:
YY_RULE_SETUP
-#line 130 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_EXCLAMATIONEQUALS; }
YY_BREAK
case 79:
YY_RULE_SETUP
-#line 131 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_GREATER; }
YY_BREAK
case 80:
YY_RULE_SETUP
-#line 132 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_GTEQUALS; }
YY_BREAK
case 81:
YY_RULE_SETUP
-#line 133 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_GTGT; }
YY_BREAK
case 82:
YY_RULE_SETUP
-#line 134 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_GTGTEQUALS; }
YY_BREAK
case 83:
YY_RULE_SETUP
-#line 135 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_GTGTGT; }
YY_BREAK
case 84:
YY_RULE_SETUP
-#line 136 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_GTGTGTEQUALS; }
YY_BREAK
case 85:
YY_RULE_SETUP
-#line 137 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_LESLESEQUALS; }
YY_BREAK
case 86:
YY_RULE_SETUP
-#line 138 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_LESSTHAN; }
YY_BREAK
case 87:
YY_RULE_SETUP
-#line 139 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_LTEQUALS; }
YY_BREAK
case 88:
YY_RULE_SETUP
-#line 140 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_LTLT; }
YY_BREAK
case 89:
YY_RULE_SETUP
-#line 141 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_MINUS; }
YY_BREAK
case 90:
YY_RULE_SETUP
-#line 142 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_MINUSEQUALS; }
YY_BREAK
case 91:
YY_RULE_SETUP
-#line 143 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_MINUSMINUS; }
YY_BREAK
case 92:
YY_RULE_SETUP
-#line 144 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_PAREEND; }
YY_BREAK
case 93:
YY_RULE_SETUP
-#line 145 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_PARESTART; }
YY_BREAK
case 94:
YY_RULE_SETUP
-#line 146 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_PERCENT; }
YY_BREAK
case 95:
YY_RULE_SETUP
-#line 147 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_PERCENTEQUALS; }
YY_BREAK
case 96:
YY_RULE_SETUP
-#line 148 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_PIPE; }
YY_BREAK
case 97:
YY_RULE_SETUP
-#line 149 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_PIPEEQUALS; }
YY_BREAK
case 98:
YY_RULE_SETUP
-#line 150 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_PIPEPIPE; }
YY_BREAK
case 99:
YY_RULE_SETUP
-#line 151 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_PLUS; }
YY_BREAK
case 100:
YY_RULE_SETUP
-#line 152 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_PLUSEQUALS; }
YY_BREAK
case 101:
YY_RULE_SETUP
-#line 153 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_PLUSPLUS; }
YY_BREAK
case 102:
YY_RULE_SETUP
-#line 154 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_QUESTION; }
YY_BREAK
case 103:
YY_RULE_SETUP
-#line 155 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_SEMICOL; }
YY_BREAK
case 104:
YY_RULE_SETUP
-#line 156 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_TILDE; }
YY_BREAK
case 105:
YY_RULE_SETUP
-#line 157 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_TIMES; }
YY_BREAK
case 106:
YY_RULE_SETUP
-#line 158 "cmDependsJavaLexer.in.l"
{ SYMBOL; return jp_TIMESEQUALS; }
YY_BREAK
case 107:
YY_RULE_SETUP
-#line 160 "cmDependsJavaLexer.in.l"
{
yyextra->AllocateParserType(yylvalp, yytext, strlen(yytext));
return jp_NAME;
@@ -1540,18 +1622,15 @@ YY_RULE_SETUP
case 108:
/* rule 108 can match eol */
YY_RULE_SETUP
-#line 165 "cmDependsJavaLexer.in.l"
{ }
YY_BREAK
case 109:
/* rule 109 can match eol */
YY_RULE_SETUP
-#line 166 "cmDependsJavaLexer.in.l"
{ }
YY_BREAK
case 110:
YY_RULE_SETUP
-#line 167 "cmDependsJavaLexer.in.l"
{
std::cerr << "Unknown character: " << yytext[0]
<< " (" << (int)yytext[0] << ")" << std::endl;
@@ -1561,10 +1640,8 @@ YY_RULE_SETUP
YY_BREAK
case 111:
YY_RULE_SETUP
-#line 174 "cmDependsJavaLexer.in.l"
ECHO;
YY_BREAK
-#line 1567 "cmDependsJavaLexer.cxx"
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(comment):
case YY_STATE_EOF(string):
@@ -1584,7 +1661,7 @@ case YY_STATE_EOF(string):
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
- * cmDependsJava_yylex(). If so, then we have to assure
+ * yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
@@ -1644,7 +1721,7 @@ case YY_STATE_EOF(string):
{
yyg->yy_did_buffer_switch_on_eof = 0;
- if ( cmDependsJava_yywrap(yyscanner ) )
+ if ( yywrap( yyscanner ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
@@ -1698,7 +1775,7 @@ case YY_STATE_EOF(string):
} /* end of action switch */
} /* end of scanning one token */
} /* end of user's declarations */
-} /* end of cmDependsJava_yylex */
+} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
@@ -1712,7 +1789,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
char *source = yyg->yytext_ptr;
- yy_size_t number_to_move, i;
+ int number_to_move, i;
int ret_val;
if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
@@ -1741,7 +1818,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
/* Try to read more data. */
/* First move last chars to start of buffer. */
- number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
+ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr - 1);
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
@@ -1777,7 +1854,8 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
- cmDependsJava_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
+ yyrealloc( (void *) b->yy_ch_buf,
+ (yy_size_t) (b->yy_buf_size + 2) , yyscanner );
}
else
/* Can't grow it, we don't own it. */
@@ -1809,7 +1887,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
- cmDependsJava_yyrestart(yyin ,yyscanner);
+ yyrestart( yyin , yyscanner);
}
else
@@ -1823,12 +1901,15 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
else
ret_val = EOB_ACT_CONTINUE_SCAN;
- if ((int) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
+ if ((yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
- YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) cmDependsJava_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
+ YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc(
+ (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size , yyscanner );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+ /* "- 2" to take care of EOB's */
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2);
}
yyg->yy_n_chars += number_to_move;
@@ -1862,9 +1943,9 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 327 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
}
return yy_current_state;
@@ -1891,9 +1972,9 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 327 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
yy_is_jam = (yy_current_state == 326);
(void)yyg;
@@ -1967,7 +2048,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
else
{ /* need more input */
- int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
+ int offset = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr);
++yyg->yy_c_buf_p;
switch ( yy_get_next_buffer( yyscanner ) )
@@ -1984,13 +2065,13 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
*/
/* Reset buffer status. */
- cmDependsJava_yyrestart(yyin ,yyscanner);
+ yyrestart( yyin , yyscanner);
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
- if ( cmDependsJava_yywrap(yyscanner ) )
+ if ( yywrap( yyscanner ) )
return 0;
if ( ! yyg->yy_did_buffer_switch_on_eof )
@@ -2022,34 +2103,34 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @note This function does not reset the start condition to @c INITIAL .
*/
- void cmDependsJava_yyrestart (FILE * input_file , yyscan_t yyscanner)
+ void yyrestart (FILE * input_file , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! YY_CURRENT_BUFFER ){
- cmDependsJava_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
- cmDependsJava_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner);
}
- cmDependsJava_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
- cmDependsJava_yy_load_buffer_state(yyscanner );
+ yy_init_buffer( YY_CURRENT_BUFFER, input_file , yyscanner);
+ yy_load_buffer_state( yyscanner );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
* @param yyscanner The scanner object.
*/
- void cmDependsJava_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
+ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* TODO. We should be able to replace this entire function body
* with
- * cmDependsJava_yypop_buffer_state();
- * cmDependsJava_yypush_buffer_state(new_buffer);
+ * yypop_buffer_state();
+ * yypush_buffer_state(new_buffer);
*/
- cmDependsJava_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
if ( YY_CURRENT_BUFFER == new_buffer )
return;
@@ -2062,17 +2143,17 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
- cmDependsJava_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
/* We don't actually know whether we did this switch during
- * EOF (cmDependsJava_yywrap()) processing, but the only time this flag
- * is looked at is after cmDependsJava_yywrap() is called, so it's safe
+ * EOF (yywrap()) processing, but the only time this flag
+ * is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
yyg->yy_did_buffer_switch_on_eof = 1;
}
-static void cmDependsJava_yy_load_buffer_state (yyscan_t yyscanner)
+static void yy_load_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
@@ -2087,35 +2168,35 @@ static void cmDependsJava_yy_load_buffer_state (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @return the allocated buffer state.
*/
- YY_BUFFER_STATE cmDependsJava_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
+ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
- b = (YY_BUFFER_STATE) cmDependsJava_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+ b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner );
if ( ! b )
- YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yy_create_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
- b->yy_buf_size = (yy_size_t)size;
+ b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
- b->yy_ch_buf = (char *) cmDependsJava_yyalloc(b->yy_buf_size + 2 ,yyscanner );
+ b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) , yyscanner );
if ( ! b->yy_ch_buf )
- YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yy_create_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
- cmDependsJava_yy_init_buffer(b,file ,yyscanner);
+ yy_init_buffer( b, file , yyscanner);
return b;
}
/** Destroy the buffer.
- * @param b a buffer created with cmDependsJava_yy_create_buffer()
+ * @param b a buffer created with yy_create_buffer()
* @param yyscanner The scanner object.
*/
- void cmDependsJava_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
+ void yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -2126,28 +2207,28 @@ static void cmDependsJava_yy_load_buffer_state (yyscan_t yyscanner)
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
- cmDependsJava_yyfree((void *) b->yy_ch_buf ,yyscanner );
+ yyfree( (void *) b->yy_ch_buf , yyscanner );
- cmDependsJava_yyfree((void *) b ,yyscanner );
+ yyfree( (void *) b , yyscanner );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
- * such as during a cmDependsJava_yyrestart() or at EOF.
+ * such as during a yyrestart() or at EOF.
*/
- static void cmDependsJava_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
+ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
{
int oerrno = errno;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
- cmDependsJava_yy_flush_buffer(b ,yyscanner);
+ yy_flush_buffer( b , yyscanner);
b->yy_input_file = file;
b->yy_fill_buffer = 1;
- /* If b is the current buffer, then cmDependsJava_yy_init_buffer was _probably_
- * called from cmDependsJava_yyrestart() or through yy_get_next_buffer.
+ /* If b is the current buffer, then yy_init_buffer was _probably_
+ * called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
@@ -2164,7 +2245,7 @@ static void cmDependsJava_yy_load_buffer_state (yyscan_t yyscanner)
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
* @param yyscanner The scanner object.
*/
- void cmDependsJava_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
+ void yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
@@ -2185,7 +2266,7 @@ static void cmDependsJava_yy_load_buffer_state (yyscan_t yyscanner)
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
- cmDependsJava_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
}
/** Pushes the new state onto the stack. The new state becomes
@@ -2194,15 +2275,15 @@ static void cmDependsJava_yy_load_buffer_state (yyscan_t yyscanner)
* @param new_buffer The new state.
* @param yyscanner The scanner object.
*/
-void cmDependsJava_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
+void yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (new_buffer == NULL)
return;
- cmDependsJava_yyensure_buffer_stack(yyscanner);
+ yyensure_buffer_stack(yyscanner);
- /* This block is copied from cmDependsJava_yy_switch_to_buffer. */
+ /* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
@@ -2216,8 +2297,8 @@ void cmDependsJava_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yy
yyg->yy_buffer_stack_top++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
- /* copied from cmDependsJava_yy_switch_to_buffer. */
- cmDependsJava_yy_load_buffer_state(yyscanner );
+ /* copied from yy_switch_to_buffer. */
+ yy_load_buffer_state( yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
@@ -2225,19 +2306,19 @@ void cmDependsJava_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yy
* The next element becomes the new top.
* @param yyscanner The scanner object.
*/
-void cmDependsJava_yypop_buffer_state (yyscan_t yyscanner)
+void yypop_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER)
return;
- cmDependsJava_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
+ yy_delete_buffer(YY_CURRENT_BUFFER , yyscanner);
YY_CURRENT_BUFFER_LVALUE = NULL;
if (yyg->yy_buffer_stack_top > 0)
--yyg->yy_buffer_stack_top;
if (YY_CURRENT_BUFFER) {
- cmDependsJava_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
}
@@ -2245,9 +2326,9 @@ void cmDependsJava_yypop_buffer_state (yyscan_t yyscanner)
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
-static void cmDependsJava_yyensure_buffer_stack (yyscan_t yyscanner)
+static void yyensure_buffer_stack (yyscan_t yyscanner)
{
- int num_to_alloc;
+ yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
@@ -2257,11 +2338,11 @@ static void cmDependsJava_yyensure_buffer_stack (yyscan_t yyscanner)
* immediate realloc on the next call.
*/
num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
- yyg->yy_buffer_stack = (struct yy_buffer_state**)cmDependsJava_yyalloc
+ yyg->yy_buffer_stack = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
- YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yyensure_buffer_stack()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
@@ -2276,12 +2357,12 @@ static void cmDependsJava_yyensure_buffer_stack (yyscan_t yyscanner)
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
- yyg->yy_buffer_stack = (struct yy_buffer_state**)cmDependsJava_yyrealloc
+ yyg->yy_buffer_stack = (struct yy_buffer_state**)yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
- YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yyensure_buffer_stack()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
@@ -2295,7 +2376,7 @@ static void cmDependsJava_yyensure_buffer_stack (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
-YY_BUFFER_STATE cmDependsJava_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
@@ -2305,11 +2386,11 @@ YY_BUFFER_STATE cmDependsJava_yy_scan_buffer (char * base, yy_size_t size , yy
/* They forgot to leave room for the EOB's. */
return NULL;
- b = (YY_BUFFER_STATE) cmDependsJava_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+ b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner );
if ( ! b )
- YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yy_scan_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
- b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
+ b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = NULL;
@@ -2319,53 +2400,53 @@ YY_BUFFER_STATE cmDependsJava_yy_scan_buffer (char * base, yy_size_t size , yy
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
- cmDependsJava_yy_switch_to_buffer(b ,yyscanner );
+ yy_switch_to_buffer( b , yyscanner );
return b;
}
-/** Setup the input buffer state to scan a string. The next call to cmDependsJava_yylex() will
+/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
- * cmDependsJava_yy_scan_bytes() instead.
+ * yy_scan_bytes() instead.
*/
-YY_BUFFER_STATE cmDependsJava_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_string (const char * yystr , yyscan_t yyscanner)
{
- return cmDependsJava_yy_scan_bytes(yystr,(int) strlen(yystr) ,yyscanner);
+ return yy_scan_bytes( yystr, (int) strlen(yystr) , yyscanner);
}
-/** Setup the input buffer state to scan the given bytes. The next call to cmDependsJava_yylex() will
+/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
-YY_BUFFER_STATE cmDependsJava_yy_scan_bytes (yyconst char * yybytes, int _yybytes_len , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
- yy_size_t i;
+ int i;
/* Get memory for full buffer, including space for trailing EOB's. */
- n = (yy_size_t) _yybytes_len + 2;
- buf = (char *) cmDependsJava_yyalloc(n ,yyscanner );
+ n = (yy_size_t) (_yybytes_len + 2);
+ buf = (char *) yyalloc( n , yyscanner );
if ( ! buf )
- YY_FATAL_ERROR( "out of dynamic memory in cmDependsJava_yy_scan_bytes()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
- for ( i = 0; i < (size_t)_yybytes_len; ++i )
+ for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
- b = cmDependsJava_yy_scan_buffer(buf,n ,yyscanner);
+ b = yy_scan_buffer( buf, n , yyscanner);
if ( ! b )
- YY_FATAL_ERROR( "bad buffer in cmDependsJava_yy_scan_bytes()" );
+ YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
@@ -2379,11 +2460,11 @@ YY_BUFFER_STATE cmDependsJava_yy_scan_bytes (yyconst char * yybytes, int _yyby
#define YY_EXIT_FAILURE 2
#endif
-static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
+static void yynoreturn yy_fatal_error (const char* msg , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
- (void) fprintf( stderr, "%s\n", msg );
+ fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
@@ -2409,7 +2490,7 @@ static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
/** Get the user-defined data for this scanner.
* @param yyscanner The scanner object.
*/
-YY_EXTRA_TYPE cmDependsJava_yyget_extra (yyscan_t yyscanner)
+YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyextra;
@@ -2418,7 +2499,7 @@ YY_EXTRA_TYPE cmDependsJava_yyget_extra (yyscan_t yyscanner)
/** Get the current line number.
* @param yyscanner The scanner object.
*/
-int cmDependsJava_yyget_lineno (yyscan_t yyscanner)
+int yyget_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -2431,7 +2512,7 @@ int cmDependsJava_yyget_lineno (yyscan_t yyscanner)
/** Get the current column number.
* @param yyscanner The scanner object.
*/
-int cmDependsJava_yyget_column (yyscan_t yyscanner)
+int yyget_column (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -2444,7 +2525,7 @@ int cmDependsJava_yyget_column (yyscan_t yyscanner)
/** Get the input stream.
* @param yyscanner The scanner object.
*/
-FILE *cmDependsJava_yyget_in (yyscan_t yyscanner)
+FILE *yyget_in (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyin;
@@ -2453,7 +2534,7 @@ FILE *cmDependsJava_yyget_in (yyscan_t yyscanner)
/** Get the output stream.
* @param yyscanner The scanner object.
*/
-FILE *cmDependsJava_yyget_out (yyscan_t yyscanner)
+FILE *yyget_out (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyout;
@@ -2462,7 +2543,7 @@ FILE *cmDependsJava_yyget_out (yyscan_t yyscanner)
/** Get the length of the current token.
* @param yyscanner The scanner object.
*/
-int cmDependsJava_yyget_leng (yyscan_t yyscanner)
+int yyget_leng (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyleng;
@@ -2472,7 +2553,7 @@ int cmDependsJava_yyget_leng (yyscan_t yyscanner)
* @param yyscanner The scanner object.
*/
-char *cmDependsJava_yyget_text (yyscan_t yyscanner)
+char *yyget_text (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yytext;
@@ -2482,7 +2563,7 @@ char *cmDependsJava_yyget_text (yyscan_t yyscanner)
* @param user_defined The data to be associated with this scanner.
* @param yyscanner The scanner object.
*/
-void cmDependsJava_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
+void yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyextra = user_defined ;
@@ -2492,13 +2573,13 @@ void cmDependsJava_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner
* @param _line_number line number
* @param yyscanner The scanner object.
*/
-void cmDependsJava_yyset_lineno (int _line_number , yyscan_t yyscanner)
+void yyset_lineno (int _line_number , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* lineno is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
- YY_FATAL_ERROR( "cmDependsJava_yyset_lineno called with no buffer" );
+ YY_FATAL_ERROR( "yyset_lineno called with no buffer" );
yylineno = _line_number;
}
@@ -2507,13 +2588,13 @@ void cmDependsJava_yyset_lineno (int _line_number , yyscan_t yyscanner)
* @param _column_no column number
* @param yyscanner The scanner object.
*/
-void cmDependsJava_yyset_column (int _column_no , yyscan_t yyscanner)
+void yyset_column (int _column_no , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* column is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
- YY_FATAL_ERROR( "cmDependsJava_yyset_column called with no buffer" );
+ YY_FATAL_ERROR( "yyset_column called with no buffer" );
yycolumn = _column_no;
}
@@ -2522,27 +2603,27 @@ void cmDependsJava_yyset_column (int _column_no , yyscan_t yyscanner)
* input buffer.
* @param _in_str A readable stream.
* @param yyscanner The scanner object.
- * @see cmDependsJava_yy_switch_to_buffer
+ * @see yy_switch_to_buffer
*/
-void cmDependsJava_yyset_in (FILE * _in_str , yyscan_t yyscanner)
+void yyset_in (FILE * _in_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyin = _in_str ;
}
-void cmDependsJava_yyset_out (FILE * _out_str , yyscan_t yyscanner)
+void yyset_out (FILE * _out_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyout = _out_str ;
}
-int cmDependsJava_yyget_debug (yyscan_t yyscanner)
+int yyget_debug (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yy_flex_debug;
}
-void cmDependsJava_yyset_debug (int _bdebug , yyscan_t yyscanner)
+void yyset_debug (int _bdebug , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_flex_debug = _bdebug ;
@@ -2552,20 +2633,18 @@ void cmDependsJava_yyset_debug (int _bdebug , yyscan_t yyscanner)
/* User-visible API */
-/* cmDependsJava_yylex_init is special because it creates the scanner itself, so it is
+/* yylex_init is special because it creates the scanner itself, so it is
* the ONLY reentrant function that doesn't take the scanner as the last argument.
* That's why we explicitly handle the declaration, instead of using our macros.
*/
-
-int cmDependsJava_yylex_init(yyscan_t* ptr_yy_globals)
-
+int yylex_init(yyscan_t* ptr_yy_globals)
{
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
- *ptr_yy_globals = (yyscan_t) cmDependsJava_yyalloc ( sizeof( struct yyguts_t ), NULL );
+ *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), NULL );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
@@ -2578,27 +2657,25 @@ int cmDependsJava_yylex_init(yyscan_t* ptr_yy_globals)
return yy_init_globals ( *ptr_yy_globals );
}
-/* cmDependsJava_yylex_init_extra has the same functionality as cmDependsJava_yylex_init, but follows the
+/* yylex_init_extra has the same functionality as yylex_init, but follows the
* convention of taking the scanner as the last argument. Note however, that
* this is a *pointer* to a scanner, as it will be allocated by this call (and
* is the reason, too, why this function also must handle its own declaration).
- * The user defined value in the first argument will be available to cmDependsJava_yyalloc in
+ * The user defined value in the first argument will be available to yyalloc in
* the yyextra field.
*/
-
-int cmDependsJava_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )
-
+int yylex_init_extra( YY_EXTRA_TYPE yy_user_defined, yyscan_t* ptr_yy_globals )
{
struct yyguts_t dummy_yyguts;
- cmDependsJava_yyset_extra (yy_user_defined, &dummy_yyguts);
+ yyset_extra (yy_user_defined, &dummy_yyguts);
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
- *ptr_yy_globals = (yyscan_t) cmDependsJava_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
+ *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
@@ -2609,7 +2686,7 @@ int cmDependsJava_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_y
yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
- cmDependsJava_yyset_extra (yy_user_defined, *ptr_yy_globals);
+ yyset_extra (yy_user_defined, *ptr_yy_globals);
return yy_init_globals ( *ptr_yy_globals );
}
@@ -2618,7 +2695,7 @@ static int yy_init_globals (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Initialization is the same as for the non-reentrant scanner.
- * This function is called from cmDependsJava_yylex_destroy(), so don't allocate here.
+ * This function is called from yylex_destroy(), so don't allocate here.
*/
yyg->yy_buffer_stack = NULL;
@@ -2642,37 +2719,37 @@ static int yy_init_globals (yyscan_t yyscanner)
#endif
/* For future reference: Set errno on error, since we are called by
- * cmDependsJava_yylex_init()
+ * yylex_init()
*/
return 0;
}
-/* cmDependsJava_yylex_destroy is for both reentrant and non-reentrant scanners. */
-int cmDependsJava_yylex_destroy (yyscan_t yyscanner)
+/* yylex_destroy is for both reentrant and non-reentrant scanners. */
+int yylex_destroy (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
- cmDependsJava_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
+ yy_delete_buffer( YY_CURRENT_BUFFER , yyscanner );
YY_CURRENT_BUFFER_LVALUE = NULL;
- cmDependsJava_yypop_buffer_state(yyscanner);
+ yypop_buffer_state(yyscanner);
}
/* Destroy the stack itself. */
- cmDependsJava_yyfree(yyg->yy_buffer_stack ,yyscanner);
+ yyfree(yyg->yy_buffer_stack , yyscanner);
yyg->yy_buffer_stack = NULL;
/* Destroy the start condition stack. */
- cmDependsJava_yyfree(yyg->yy_start_stack ,yyscanner );
+ yyfree( yyg->yy_start_stack , yyscanner );
yyg->yy_start_stack = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
- * cmDependsJava_yylex() is called, initialization will occur. */
+ * yylex() is called, initialization will occur. */
yy_init_globals( yyscanner);
/* Destroy the main struct (reentrant only). */
- cmDependsJava_yyfree ( yyscanner , yyscanner );
+ yyfree ( yyscanner , yyscanner );
yyscanner = NULL;
return 0;
}
@@ -2682,7 +2759,7 @@ int cmDependsJava_yylex_destroy (yyscan_t yyscanner)
*/
#ifndef yytext_ptr
-static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner)
+static void yy_flex_strncpy (char* s1, const char * s2, int n , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
@@ -2694,7 +2771,7 @@ static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yysca
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
+static int yy_flex_strlen (const char * s , yyscan_t yyscanner)
{
int n;
for ( n = 0; s[n]; ++n )
@@ -2704,14 +2781,14 @@ static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
}
#endif
-void *cmDependsJava_yyalloc (yy_size_t size , yyscan_t yyscanner)
+void *yyalloc (yy_size_t size , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
return malloc(size);
}
-void *cmDependsJava_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
+void *yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
@@ -2726,13 +2803,11 @@ void *cmDependsJava_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner
return realloc(ptr, size);
}
-void cmDependsJava_yyfree (void * ptr , yyscan_t yyscanner)
+void yyfree (void * ptr , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
- free( (char *) ptr ); /* see cmDependsJava_yyrealloc() for (char *) cast */
+ free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
-
-#line 174 "cmDependsJavaLexer.in.l"
diff --git a/Source/LexerParser/cmDependsJavaLexer.h b/Source/LexerParser/cmDependsJavaLexer.h
index ccadd70b9..f1e87d246 100644
--- a/Source/LexerParser/cmDependsJavaLexer.h
+++ b/Source/LexerParser/cmDependsJavaLexer.h
@@ -2,10 +2,6 @@
#define cmDependsJava_yyHEADER_H 1
#define cmDependsJava_yyIN_HEADER 1
-#line 6 "cmDependsJavaLexer.h"
-
-#line 8 "cmDependsJavaLexer.h"
-
#define FLEXINT_H 1
#define YY_INT_ALIGNED short int
@@ -14,11 +10,221 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
-#define YY_FLEX_SUBMINOR_VERSION 1
+#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
+#ifdef yy_create_buffer
+#define cmDependsJava_yy_create_buffer_ALREADY_DEFINED
+#else
+#define yy_create_buffer cmDependsJava_yy_create_buffer
+#endif
+
+#ifdef yy_delete_buffer
+#define cmDependsJava_yy_delete_buffer_ALREADY_DEFINED
+#else
+#define yy_delete_buffer cmDependsJava_yy_delete_buffer
+#endif
+
+#ifdef yy_scan_buffer
+#define cmDependsJava_yy_scan_buffer_ALREADY_DEFINED
+#else
+#define yy_scan_buffer cmDependsJava_yy_scan_buffer
+#endif
+
+#ifdef yy_scan_string
+#define cmDependsJava_yy_scan_string_ALREADY_DEFINED
+#else
+#define yy_scan_string cmDependsJava_yy_scan_string
+#endif
+
+#ifdef yy_scan_bytes
+#define cmDependsJava_yy_scan_bytes_ALREADY_DEFINED
+#else
+#define yy_scan_bytes cmDependsJava_yy_scan_bytes
+#endif
+
+#ifdef yy_init_buffer
+#define cmDependsJava_yy_init_buffer_ALREADY_DEFINED
+#else
+#define yy_init_buffer cmDependsJava_yy_init_buffer
+#endif
+
+#ifdef yy_flush_buffer
+#define cmDependsJava_yy_flush_buffer_ALREADY_DEFINED
+#else
+#define yy_flush_buffer cmDependsJava_yy_flush_buffer
+#endif
+
+#ifdef yy_load_buffer_state
+#define cmDependsJava_yy_load_buffer_state_ALREADY_DEFINED
+#else
+#define yy_load_buffer_state cmDependsJava_yy_load_buffer_state
+#endif
+
+#ifdef yy_switch_to_buffer
+#define cmDependsJava_yy_switch_to_buffer_ALREADY_DEFINED
+#else
+#define yy_switch_to_buffer cmDependsJava_yy_switch_to_buffer
+#endif
+
+#ifdef yypush_buffer_state
+#define cmDependsJava_yypush_buffer_state_ALREADY_DEFINED
+#else
+#define yypush_buffer_state cmDependsJava_yypush_buffer_state
+#endif
+
+#ifdef yypop_buffer_state
+#define cmDependsJava_yypop_buffer_state_ALREADY_DEFINED
+#else
+#define yypop_buffer_state cmDependsJava_yypop_buffer_state
+#endif
+
+#ifdef yyensure_buffer_stack
+#define cmDependsJava_yyensure_buffer_stack_ALREADY_DEFINED
+#else
+#define yyensure_buffer_stack cmDependsJava_yyensure_buffer_stack
+#endif
+
+#ifdef yylex
+#define cmDependsJava_yylex_ALREADY_DEFINED
+#else
+#define yylex cmDependsJava_yylex
+#endif
+
+#ifdef yyrestart
+#define cmDependsJava_yyrestart_ALREADY_DEFINED
+#else
+#define yyrestart cmDependsJava_yyrestart
+#endif
+
+#ifdef yylex_init
+#define cmDependsJava_yylex_init_ALREADY_DEFINED
+#else
+#define yylex_init cmDependsJava_yylex_init
+#endif
+
+#ifdef yylex_init_extra
+#define cmDependsJava_yylex_init_extra_ALREADY_DEFINED
+#else
+#define yylex_init_extra cmDependsJava_yylex_init_extra
+#endif
+
+#ifdef yylex_destroy
+#define cmDependsJava_yylex_destroy_ALREADY_DEFINED
+#else
+#define yylex_destroy cmDependsJava_yylex_destroy
+#endif
+
+#ifdef yyget_debug
+#define cmDependsJava_yyget_debug_ALREADY_DEFINED
+#else
+#define yyget_debug cmDependsJava_yyget_debug
+#endif
+
+#ifdef yyset_debug
+#define cmDependsJava_yyset_debug_ALREADY_DEFINED
+#else
+#define yyset_debug cmDependsJava_yyset_debug
+#endif
+
+#ifdef yyget_extra
+#define cmDependsJava_yyget_extra_ALREADY_DEFINED
+#else
+#define yyget_extra cmDependsJava_yyget_extra
+#endif
+
+#ifdef yyset_extra
+#define cmDependsJava_yyset_extra_ALREADY_DEFINED
+#else
+#define yyset_extra cmDependsJava_yyset_extra
+#endif
+
+#ifdef yyget_in
+#define cmDependsJava_yyget_in_ALREADY_DEFINED
+#else
+#define yyget_in cmDependsJava_yyget_in
+#endif
+
+#ifdef yyset_in
+#define cmDependsJava_yyset_in_ALREADY_DEFINED
+#else
+#define yyset_in cmDependsJava_yyset_in
+#endif
+
+#ifdef yyget_out
+#define cmDependsJava_yyget_out_ALREADY_DEFINED
+#else
+#define yyget_out cmDependsJava_yyget_out
+#endif
+
+#ifdef yyset_out
+#define cmDependsJava_yyset_out_ALREADY_DEFINED
+#else
+#define yyset_out cmDependsJava_yyset_out
+#endif
+
+#ifdef yyget_leng
+#define cmDependsJava_yyget_leng_ALREADY_DEFINED
+#else
+#define yyget_leng cmDependsJava_yyget_leng
+#endif
+
+#ifdef yyget_text
+#define cmDependsJava_yyget_text_ALREADY_DEFINED
+#else
+#define yyget_text cmDependsJava_yyget_text
+#endif
+
+#ifdef yyget_lineno
+#define cmDependsJava_yyget_lineno_ALREADY_DEFINED
+#else
+#define yyget_lineno cmDependsJava_yyget_lineno
+#endif
+
+#ifdef yyset_lineno
+#define cmDependsJava_yyset_lineno_ALREADY_DEFINED
+#else
+#define yyset_lineno cmDependsJava_yyset_lineno
+#endif
+
+#ifdef yyget_column
+#define cmDependsJava_yyget_column_ALREADY_DEFINED
+#else
+#define yyget_column cmDependsJava_yyget_column
+#endif
+
+#ifdef yyset_column
+#define cmDependsJava_yyset_column_ALREADY_DEFINED
+#else
+#define yyset_column cmDependsJava_yyset_column
+#endif
+
+#ifdef yywrap
+#define cmDependsJava_yywrap_ALREADY_DEFINED
+#else
+#define yywrap cmDependsJava_yywrap
+#endif
+
+#ifdef yyalloc
+#define cmDependsJava_yyalloc_ALREADY_DEFINED
+#else
+#define yyalloc cmDependsJava_yyalloc
+#endif
+
+#ifdef yyrealloc
+#define cmDependsJava_yyrealloc_ALREADY_DEFINED
+#else
+#define yyrealloc cmDependsJava_yyrealloc
+#endif
+
+#ifdef yyfree
+#define cmDependsJava_yyfree_ALREADY_DEFINED
+#else
+#define yyfree cmDependsJava_yyfree
+#endif
+
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
@@ -89,10 +295,16 @@ typedef unsigned int flex_uint32_t;
#define UINT32_MAX (4294967295U)
#endif
+#ifndef SIZE_MAX
+#define SIZE_MAX (~(size_t)0)
+#endif
+
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
+/* begin standard C++ headers. */
+
/* TODO: this is always defined, so inline it */
#define yyconst const
@@ -193,21 +405,21 @@ struct yy_buffer_state
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
-void cmDependsJava_yyrestart (FILE *input_file ,yyscan_t yyscanner );
-void cmDependsJava_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmDependsJava_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
-void cmDependsJava_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmDependsJava_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmDependsJava_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-void cmDependsJava_yypop_buffer_state (yyscan_t yyscanner );
+void yyrestart ( FILE *input_file , yyscan_t yyscanner );
+void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size , yyscan_t yyscanner );
+void yy_delete_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yy_flush_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yypush_buffer_state ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+void yypop_buffer_state ( yyscan_t yyscanner );
-YY_BUFFER_STATE cmDependsJava_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmDependsJava_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmDependsJava_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_string ( const char *yy_str , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len , yyscan_t yyscanner );
-void *cmDependsJava_yyalloc (yy_size_t ,yyscan_t yyscanner );
-void *cmDependsJava_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
-void cmDependsJava_yyfree (void * ,yyscan_t yyscanner );
+void *yyalloc ( yy_size_t , yyscan_t yyscanner );
+void *yyrealloc ( void *, yy_size_t , yyscan_t yyscanner );
+void yyfree ( void * , yyscan_t yyscanner );
/* Begin user sect3 */
@@ -227,42 +439,42 @@ void cmDependsJava_yyfree (void * ,yyscan_t yyscanner );
#define YY_EXTRA_TYPE void *
#endif
-int cmDependsJava_yylex_init (yyscan_t* scanner);
+int yylex_init (yyscan_t* scanner);
-int cmDependsJava_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
-int cmDependsJava_yylex_destroy (yyscan_t yyscanner );
+int yylex_destroy ( yyscan_t yyscanner );
-int cmDependsJava_yyget_debug (yyscan_t yyscanner );
+int yyget_debug ( yyscan_t yyscanner );
-void cmDependsJava_yyset_debug (int debug_flag ,yyscan_t yyscanner );
+void yyset_debug ( int debug_flag , yyscan_t yyscanner );
-YY_EXTRA_TYPE cmDependsJava_yyget_extra (yyscan_t yyscanner );
+YY_EXTRA_TYPE yyget_extra ( yyscan_t yyscanner );
-void cmDependsJava_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
+void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t yyscanner );
-FILE *cmDependsJava_yyget_in (yyscan_t yyscanner );
+FILE *yyget_in ( yyscan_t yyscanner );
-void cmDependsJava_yyset_in (FILE * _in_str ,yyscan_t yyscanner );
+void yyset_in ( FILE * _in_str , yyscan_t yyscanner );
-FILE *cmDependsJava_yyget_out (yyscan_t yyscanner );
+FILE *yyget_out ( yyscan_t yyscanner );
-void cmDependsJava_yyset_out (FILE * _out_str ,yyscan_t yyscanner );
+void yyset_out ( FILE * _out_str , yyscan_t yyscanner );
- int cmDependsJava_yyget_leng (yyscan_t yyscanner );
+ int yyget_leng ( yyscan_t yyscanner );
-char *cmDependsJava_yyget_text (yyscan_t yyscanner );
+char *yyget_text ( yyscan_t yyscanner );
-int cmDependsJava_yyget_lineno (yyscan_t yyscanner );
+int yyget_lineno ( yyscan_t yyscanner );
-void cmDependsJava_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+void yyset_lineno ( int _line_number , yyscan_t yyscanner );
-int cmDependsJava_yyget_column (yyscan_t yyscanner );
+int yyget_column ( yyscan_t yyscanner );
-void cmDependsJava_yyset_column (int _column_no ,yyscan_t yyscanner );
+void yyset_column ( int _column_no , yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
@@ -270,18 +482,18 @@ void cmDependsJava_yyset_column (int _column_no ,yyscan_t yyscanner );
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
-extern "C" int cmDependsJava_yywrap (yyscan_t yyscanner );
+extern "C" int yywrap ( yyscan_t yyscanner );
#else
-extern int cmDependsJava_yywrap (yyscan_t yyscanner );
+extern int yywrap ( yyscan_t yyscanner );
#endif
#endif
#ifndef yytext_ptr
-static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
+static void yy_flex_strncpy ( char *, const char *, int , yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
+static int yy_flex_strlen ( const char * , yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
@@ -309,9 +521,9 @@ static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
-extern int cmDependsJava_yylex (yyscan_t yyscanner);
+extern int yylex (yyscan_t yyscanner);
-#define YY_DECL int cmDependsJava_yylex (yyscan_t yyscanner)
+#define YY_DECL int yylex (yyscan_t yyscanner)
#endif /* !YY_DECL */
/* yy_get_previous_state - get the state just before the EOB char was reached */
@@ -328,9 +540,150 @@ extern int cmDependsJava_yylex (yyscan_t yyscanner);
#undef YY_DECL
#endif
-#line 174 "cmDependsJavaLexer.in.l"
-
+#ifndef cmDependsJava_yy_create_buffer_ALREADY_DEFINED
+#undef yy_create_buffer
+#endif
+#ifndef cmDependsJava_yy_delete_buffer_ALREADY_DEFINED
+#undef yy_delete_buffer
+#endif
+#ifndef cmDependsJava_yy_scan_buffer_ALREADY_DEFINED
+#undef yy_scan_buffer
+#endif
+#ifndef cmDependsJava_yy_scan_string_ALREADY_DEFINED
+#undef yy_scan_string
+#endif
+#ifndef cmDependsJava_yy_scan_bytes_ALREADY_DEFINED
+#undef yy_scan_bytes
+#endif
+#ifndef cmDependsJava_yy_init_buffer_ALREADY_DEFINED
+#undef yy_init_buffer
+#endif
+#ifndef cmDependsJava_yy_flush_buffer_ALREADY_DEFINED
+#undef yy_flush_buffer
+#endif
+#ifndef cmDependsJava_yy_load_buffer_state_ALREADY_DEFINED
+#undef yy_load_buffer_state
+#endif
+#ifndef cmDependsJava_yy_switch_to_buffer_ALREADY_DEFINED
+#undef yy_switch_to_buffer
+#endif
+#ifndef cmDependsJava_yypush_buffer_state_ALREADY_DEFINED
+#undef yypush_buffer_state
+#endif
+#ifndef cmDependsJava_yypop_buffer_state_ALREADY_DEFINED
+#undef yypop_buffer_state
+#endif
+#ifndef cmDependsJava_yyensure_buffer_stack_ALREADY_DEFINED
+#undef yyensure_buffer_stack
+#endif
+#ifndef cmDependsJava_yylex_ALREADY_DEFINED
+#undef yylex
+#endif
+#ifndef cmDependsJava_yyrestart_ALREADY_DEFINED
+#undef yyrestart
+#endif
+#ifndef cmDependsJava_yylex_init_ALREADY_DEFINED
+#undef yylex_init
+#endif
+#ifndef cmDependsJava_yylex_init_extra_ALREADY_DEFINED
+#undef yylex_init_extra
+#endif
+#ifndef cmDependsJava_yylex_destroy_ALREADY_DEFINED
+#undef yylex_destroy
+#endif
+#ifndef cmDependsJava_yyget_debug_ALREADY_DEFINED
+#undef yyget_debug
+#endif
+#ifndef cmDependsJava_yyset_debug_ALREADY_DEFINED
+#undef yyset_debug
+#endif
+#ifndef cmDependsJava_yyget_extra_ALREADY_DEFINED
+#undef yyget_extra
+#endif
+#ifndef cmDependsJava_yyset_extra_ALREADY_DEFINED
+#undef yyset_extra
+#endif
+#ifndef cmDependsJava_yyget_in_ALREADY_DEFINED
+#undef yyget_in
+#endif
+#ifndef cmDependsJava_yyset_in_ALREADY_DEFINED
+#undef yyset_in
+#endif
+#ifndef cmDependsJava_yyget_out_ALREADY_DEFINED
+#undef yyget_out
+#endif
+#ifndef cmDependsJava_yyset_out_ALREADY_DEFINED
+#undef yyset_out
+#endif
+#ifndef cmDependsJava_yyget_leng_ALREADY_DEFINED
+#undef yyget_leng
+#endif
+#ifndef cmDependsJava_yyget_text_ALREADY_DEFINED
+#undef yyget_text
+#endif
+#ifndef cmDependsJava_yyget_lineno_ALREADY_DEFINED
+#undef yyget_lineno
+#endif
+#ifndef cmDependsJava_yyset_lineno_ALREADY_DEFINED
+#undef yyset_lineno
+#endif
+#ifndef cmDependsJava_yyget_column_ALREADY_DEFINED
+#undef yyget_column
+#endif
+#ifndef cmDependsJava_yyset_column_ALREADY_DEFINED
+#undef yyset_column
+#endif
+#ifndef cmDependsJava_yywrap_ALREADY_DEFINED
+#undef yywrap
+#endif
+#ifndef cmDependsJava_yyget_lval_ALREADY_DEFINED
+#undef yyget_lval
+#endif
+#ifndef cmDependsJava_yyset_lval_ALREADY_DEFINED
+#undef yyset_lval
+#endif
+#ifndef cmDependsJava_yyget_lloc_ALREADY_DEFINED
+#undef yyget_lloc
+#endif
+#ifndef cmDependsJava_yyset_lloc_ALREADY_DEFINED
+#undef yyset_lloc
+#endif
+#ifndef cmDependsJava_yyalloc_ALREADY_DEFINED
+#undef yyalloc
+#endif
+#ifndef cmDependsJava_yyrealloc_ALREADY_DEFINED
+#undef yyrealloc
+#endif
+#ifndef cmDependsJava_yyfree_ALREADY_DEFINED
+#undef yyfree
+#endif
+#ifndef cmDependsJava_yytext_ALREADY_DEFINED
+#undef yytext
+#endif
+#ifndef cmDependsJava_yyleng_ALREADY_DEFINED
+#undef yyleng
+#endif
+#ifndef cmDependsJava_yyin_ALREADY_DEFINED
+#undef yyin
+#endif
+#ifndef cmDependsJava_yyout_ALREADY_DEFINED
+#undef yyout
+#endif
+#ifndef cmDependsJava_yy_flex_debug_ALREADY_DEFINED
+#undef yy_flex_debug
+#endif
+#ifndef cmDependsJava_yylineno_ALREADY_DEFINED
+#undef yylineno
+#endif
+#ifndef cmDependsJava_yytables_fload_ALREADY_DEFINED
+#undef yytables_fload
+#endif
+#ifndef cmDependsJava_yytables_destroy_ALREADY_DEFINED
+#undef yytables_destroy
+#endif
+#ifndef cmDependsJava_yyTABLES_NAME_ALREADY_DEFINED
+#undef yyTABLES_NAME
+#endif
-#line 335 "cmDependsJavaLexer.h"
#undef cmDependsJava_yyIN_HEADER
#endif /* cmDependsJava_yyHEADER_H */
diff --git a/Source/LexerParser/cmDependsJavaLexer.in.l b/Source/LexerParser/cmDependsJavaLexer.in.l
index 8cb42b17a..01a0fa302 100644
--- a/Source/LexerParser/cmDependsJavaLexer.in.l
+++ b/Source/LexerParser/cmDependsJavaLexer.in.l
@@ -7,13 +7,12 @@ This file must be translated to C++ and modified to build everywhere.
Run flex >= 2.6 like this:
- flex --nounistd -DFLEXINT_H --prefix=cmDependsJava_yy --header-file=cmDependsJavaLexer.h -ocmDependsJavaLexer.cxx cmDependsJavaLexer.in.l
+ flex --nounistd -DFLEXINT_H --noline --header-file=cmDependsJavaLexer.h -ocmDependsJavaLexer.cxx cmDependsJavaLexer.in.l
Modify cmDependsJavaLexer.cxx:
- - remove trailing whitespace: sed -i 's/\s*$//' cmDependsJavaLexer.h cmDependsJavaLexer.cxx
- - remove blank lines at end of file
- - #include "cmStandardLexer.h" at the top
- - add cast in yy_scan_bytes for loop condition of _yybytes_len to size_t
+ - remove trailing whitespace: sed -i 's/\s*$//' cmDependsJavaLexer.h cmDependsJavaLexer.cxx
+ - remove blank lines at end of file: sed -i '${/^$/d;}' cmDependsJavaLexer.h cmDependsJavaLexer.cxx
+ - #include "cmStandardLexer.h" at the top: sed -i '1i#include "cmStandardLexer.h"' cmDependsJavaLexer.cxx
*/
@@ -38,6 +37,8 @@ Modify cmDependsJavaLexer.cxx:
/*--------------------------------------------------------------------------*/
%}
+%option prefix="cmDependsJava_yy"
+
%option reentrant
%option noyywrap
%pointer
diff --git a/Source/LexerParser/cmExprLexer.cxx b/Source/LexerParser/cmExprLexer.cxx
index fb6f0db98..81a1ec502 100644
--- a/Source/LexerParser/cmExprLexer.cxx
+++ b/Source/LexerParser/cmExprLexer.cxx
@@ -1,7 +1,4 @@
#include "cmStandardLexer.h"
-#line 2 "cmExprLexer.cxx"
-
-#line 4 "cmExprLexer.cxx"
#define FLEXINT_H 1
#define YY_INT_ALIGNED short int
@@ -11,11 +8,221 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
-#define YY_FLEX_SUBMINOR_VERSION 1
+#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
+#ifdef yy_create_buffer
+#define cmExpr_yy_create_buffer_ALREADY_DEFINED
+#else
+#define yy_create_buffer cmExpr_yy_create_buffer
+#endif
+
+#ifdef yy_delete_buffer
+#define cmExpr_yy_delete_buffer_ALREADY_DEFINED
+#else
+#define yy_delete_buffer cmExpr_yy_delete_buffer
+#endif
+
+#ifdef yy_scan_buffer
+#define cmExpr_yy_scan_buffer_ALREADY_DEFINED
+#else
+#define yy_scan_buffer cmExpr_yy_scan_buffer
+#endif
+
+#ifdef yy_scan_string
+#define cmExpr_yy_scan_string_ALREADY_DEFINED
+#else
+#define yy_scan_string cmExpr_yy_scan_string
+#endif
+
+#ifdef yy_scan_bytes
+#define cmExpr_yy_scan_bytes_ALREADY_DEFINED
+#else
+#define yy_scan_bytes cmExpr_yy_scan_bytes
+#endif
+
+#ifdef yy_init_buffer
+#define cmExpr_yy_init_buffer_ALREADY_DEFINED
+#else
+#define yy_init_buffer cmExpr_yy_init_buffer
+#endif
+
+#ifdef yy_flush_buffer
+#define cmExpr_yy_flush_buffer_ALREADY_DEFINED
+#else
+#define yy_flush_buffer cmExpr_yy_flush_buffer
+#endif
+
+#ifdef yy_load_buffer_state
+#define cmExpr_yy_load_buffer_state_ALREADY_DEFINED
+#else
+#define yy_load_buffer_state cmExpr_yy_load_buffer_state
+#endif
+
+#ifdef yy_switch_to_buffer
+#define cmExpr_yy_switch_to_buffer_ALREADY_DEFINED
+#else
+#define yy_switch_to_buffer cmExpr_yy_switch_to_buffer
+#endif
+
+#ifdef yypush_buffer_state
+#define cmExpr_yypush_buffer_state_ALREADY_DEFINED
+#else
+#define yypush_buffer_state cmExpr_yypush_buffer_state
+#endif
+
+#ifdef yypop_buffer_state
+#define cmExpr_yypop_buffer_state_ALREADY_DEFINED
+#else
+#define yypop_buffer_state cmExpr_yypop_buffer_state
+#endif
+
+#ifdef yyensure_buffer_stack
+#define cmExpr_yyensure_buffer_stack_ALREADY_DEFINED
+#else
+#define yyensure_buffer_stack cmExpr_yyensure_buffer_stack
+#endif
+
+#ifdef yylex
+#define cmExpr_yylex_ALREADY_DEFINED
+#else
+#define yylex cmExpr_yylex
+#endif
+
+#ifdef yyrestart
+#define cmExpr_yyrestart_ALREADY_DEFINED
+#else
+#define yyrestart cmExpr_yyrestart
+#endif
+
+#ifdef yylex_init
+#define cmExpr_yylex_init_ALREADY_DEFINED
+#else
+#define yylex_init cmExpr_yylex_init
+#endif
+
+#ifdef yylex_init_extra
+#define cmExpr_yylex_init_extra_ALREADY_DEFINED
+#else
+#define yylex_init_extra cmExpr_yylex_init_extra
+#endif
+
+#ifdef yylex_destroy
+#define cmExpr_yylex_destroy_ALREADY_DEFINED
+#else
+#define yylex_destroy cmExpr_yylex_destroy
+#endif
+
+#ifdef yyget_debug
+#define cmExpr_yyget_debug_ALREADY_DEFINED
+#else
+#define yyget_debug cmExpr_yyget_debug
+#endif
+
+#ifdef yyset_debug
+#define cmExpr_yyset_debug_ALREADY_DEFINED
+#else
+#define yyset_debug cmExpr_yyset_debug
+#endif
+
+#ifdef yyget_extra
+#define cmExpr_yyget_extra_ALREADY_DEFINED
+#else
+#define yyget_extra cmExpr_yyget_extra
+#endif
+
+#ifdef yyset_extra
+#define cmExpr_yyset_extra_ALREADY_DEFINED
+#else
+#define yyset_extra cmExpr_yyset_extra
+#endif
+
+#ifdef yyget_in
+#define cmExpr_yyget_in_ALREADY_DEFINED
+#else
+#define yyget_in cmExpr_yyget_in
+#endif
+
+#ifdef yyset_in
+#define cmExpr_yyset_in_ALREADY_DEFINED
+#else
+#define yyset_in cmExpr_yyset_in
+#endif
+
+#ifdef yyget_out
+#define cmExpr_yyget_out_ALREADY_DEFINED
+#else
+#define yyget_out cmExpr_yyget_out
+#endif
+
+#ifdef yyset_out
+#define cmExpr_yyset_out_ALREADY_DEFINED
+#else
+#define yyset_out cmExpr_yyset_out
+#endif
+
+#ifdef yyget_leng
+#define cmExpr_yyget_leng_ALREADY_DEFINED
+#else
+#define yyget_leng cmExpr_yyget_leng
+#endif
+
+#ifdef yyget_text
+#define cmExpr_yyget_text_ALREADY_DEFINED
+#else
+#define yyget_text cmExpr_yyget_text
+#endif
+
+#ifdef yyget_lineno
+#define cmExpr_yyget_lineno_ALREADY_DEFINED
+#else
+#define yyget_lineno cmExpr_yyget_lineno
+#endif
+
+#ifdef yyset_lineno
+#define cmExpr_yyset_lineno_ALREADY_DEFINED
+#else
+#define yyset_lineno cmExpr_yyset_lineno
+#endif
+
+#ifdef yyget_column
+#define cmExpr_yyget_column_ALREADY_DEFINED
+#else
+#define yyget_column cmExpr_yyget_column
+#endif
+
+#ifdef yyset_column
+#define cmExpr_yyset_column_ALREADY_DEFINED
+#else
+#define yyset_column cmExpr_yyset_column
+#endif
+
+#ifdef yywrap
+#define cmExpr_yywrap_ALREADY_DEFINED
+#else
+#define yywrap cmExpr_yywrap
+#endif
+
+#ifdef yyalloc
+#define cmExpr_yyalloc_ALREADY_DEFINED
+#else
+#define yyalloc cmExpr_yyalloc
+#endif
+
+#ifdef yyrealloc
+#define cmExpr_yyrealloc_ALREADY_DEFINED
+#else
+#define yyrealloc cmExpr_yyrealloc
+#endif
+
+#ifdef yyfree
+#define cmExpr_yyfree_ALREADY_DEFINED
+#else
+#define yyfree cmExpr_yyfree
+#endif
+
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
@@ -86,10 +293,16 @@ typedef unsigned int flex_uint32_t;
#define UINT32_MAX (4294967295U)
#endif
+#ifndef SIZE_MAX
+#define SIZE_MAX (~(size_t)0)
+#endif
+
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
+/* begin standard C++ headers. */
+
/* TODO: this is always defined, so inline it */
#define yyconst const
@@ -102,12 +315,10 @@ typedef unsigned int flex_uint32_t;
/* Returned upon end-of-file. */
#define YY_NULL 0
-/* Promotes a possibly negative, possibly signed char to an unsigned
- * integer for use as an array index. If the signed char is negative,
- * we want to instead treat it as an 8-bit unsigned char, hence the
- * double cast.
+/* Promotes a possibly negative, possibly signed char to an
+ * integer in range [0..255] for use as an array index.
*/
-#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
+#define YY_SC_TO_UI(c) ((YY_CHAR) (c))
/* An opaque pointer. */
#ifndef YY_TYPEDEF_YY_SCANNER_T
@@ -131,20 +342,16 @@ typedef void* yyscan_t;
* definition of BEGIN.
*/
#define BEGIN yyg->yy_start = 1 + 2 *
-
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START ((yyg->yy_start - 1) / 2)
#define YYSTATE YY_START
-
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
-
/* Special action meaning "start processing a new file". */
-#define YY_NEW_FILE cmExpr_yyrestart(yyin ,yyscanner )
-
+#define YY_NEW_FILE yyrestart( yyin , yyscanner )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
@@ -194,7 +401,6 @@ typedef size_t yy_size_t;
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
-
#define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
#ifndef YY_STRUCT_YY_BUFFER_STATE
@@ -254,7 +460,7 @@ struct yy_buffer_state
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
- * (via cmExpr_yyrestart()), so that the user can continue scanning by
+ * (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
@@ -271,73 +477,67 @@ struct yy_buffer_state
#define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \
? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \
: NULL)
-
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top]
-void cmExpr_yyrestart (FILE *input_file ,yyscan_t yyscanner );
-void cmExpr_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmExpr_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
-void cmExpr_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmExpr_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmExpr_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-void cmExpr_yypop_buffer_state (yyscan_t yyscanner );
-
-static void cmExpr_yyensure_buffer_stack (yyscan_t yyscanner );
-static void cmExpr_yy_load_buffer_state (yyscan_t yyscanner );
-static void cmExpr_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner );
+void yyrestart ( FILE *input_file , yyscan_t yyscanner );
+void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size , yyscan_t yyscanner );
+void yy_delete_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yy_flush_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yypush_buffer_state ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+void yypop_buffer_state ( yyscan_t yyscanner );
-#define YY_FLUSH_BUFFER cmExpr_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner)
+static void yyensure_buffer_stack ( yyscan_t yyscanner );
+static void yy_load_buffer_state ( yyscan_t yyscanner );
+static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file , yyscan_t yyscanner );
+#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER , yyscanner)
-YY_BUFFER_STATE cmExpr_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmExpr_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmExpr_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_string ( const char *yy_str , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len , yyscan_t yyscanner );
-void *cmExpr_yyalloc (yy_size_t ,yyscan_t yyscanner );
-void *cmExpr_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
-void cmExpr_yyfree (void * ,yyscan_t yyscanner );
-
-#define yy_new_buffer cmExpr_yy_create_buffer
+void *yyalloc ( yy_size_t , yyscan_t yyscanner );
+void *yyrealloc ( void *, yy_size_t , yyscan_t yyscanner );
+void yyfree ( void * , yyscan_t yyscanner );
+#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
- cmExpr_yyensure_buffer_stack (yyscanner); \
+ yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
- cmExpr_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
-
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
- cmExpr_yyensure_buffer_stack (yyscanner); \
+ yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
- cmExpr_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
-
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define cmExpr_yywrap(yyscanner) (/*CONSTCOND*/1)
#define YY_SKIP_YYWRAP
-
-typedef unsigned char YY_CHAR;
+typedef flex_uint8_t YY_CHAR;
typedef int yy_state_type;
#define yytext_ptr yytext_r
-static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
-static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner);
-static int yy_get_next_buffer (yyscan_t yyscanner );
-static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
+static yy_state_type yy_get_previous_state ( yyscan_t yyscanner );
+static yy_state_type yy_try_NUL_trans ( yy_state_type current_state , yyscan_t yyscanner);
+static int yy_get_next_buffer ( yyscan_t yyscanner );
+static void yynoreturn yy_fatal_error ( const char* msg , yyscan_t yyscanner );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
@@ -348,7 +548,6 @@ static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
yyg->yy_hold_char = *yy_cp; \
*yy_cp = '\0'; \
yyg->yy_c_buf_p = yy_cp;
-
#define YY_NUM_RULES 15
#define YY_END_OF_BUFFER 16
/* This struct is not used in this scanner,
@@ -358,14 +557,14 @@ struct yy_trans_info
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
-static yyconst flex_int16_t yy_accept[23] =
+static const flex_int16_t yy_accept[23] =
{ 0,
0, 0, 16, 15, 6, 8, 13, 14, 4, 2,
3, 5, 1, 15, 15, 9, 7, 10, 1, 11,
12, 0
} ;
-static yyconst YY_CHAR yy_ec[256] =
+static const YY_CHAR yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
@@ -397,27 +596,27 @@ static yyconst YY_CHAR yy_ec[256] =
1, 1, 1, 1, 1
} ;
-static yyconst YY_CHAR yy_meta[16] =
+static const YY_CHAR yy_meta[16] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
-static yyconst flex_uint16_t yy_base[23] =
+static const flex_int16_t yy_base[23] =
{ 0,
0, 0, 20, 21, 21, 21, 21, 21, 21, 21,
21, 21, 9, 7, 5, 21, 21, 21, 6, 21,
21, 21
} ;
-static yyconst flex_int16_t yy_def[23] =
+static const flex_int16_t yy_def[23] =
{ 0,
22, 1, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 0
} ;
-static yyconst flex_uint16_t yy_nxt[37] =
+static const flex_int16_t yy_nxt[37] =
{ 0,
4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 21, 20, 19, 22,
@@ -425,7 +624,7 @@ static yyconst flex_uint16_t yy_nxt[37] =
22, 22, 22, 22, 22, 22
} ;
-static yyconst flex_int16_t yy_chk[37] =
+static const flex_int16_t yy_chk[37] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 19, 15, 14, 13, 3,
@@ -440,8 +639,6 @@ static yyconst flex_int16_t yy_chk[37] =
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
-#line 1 "cmExprLexer.in.l"
-#line 2 "cmExprLexer.in.l"
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
/*
@@ -450,13 +647,12 @@ This file must be translated to C++ and modified to build everywhere.
Run flex >= 2.6 like this:
- flex --nounistd -DFLEXINT_H --prefix=cmExpr_yy --header-file=cmExprLexer.h -ocmExprLexer.cxx cmExprLexer.in.l
+ flex --nounistd -DFLEXINT_H --noline --header-file=cmExprLexer.h -ocmExprLexer.cxx cmExprLexer.in.l
Modify cmExprLexer.cxx:
- - remove trailing whitespace: sed -i 's/\s*$//' cmExprLexer.h cmExprLexer.cxx
- - remove blank lines at end of file
- - #include "cmStandardLexer.h" at the top
- - add cast in cmExpr_yy_scan_bytes for loop condition of _yybytes_len to size_t
+ - remove trailing whitespace: sed -i 's/\s*$//' cmExprLexer.h cmExprLexer.cxx
+ - remove blank lines at end of file: sed -i '${/^$/d;}' cmExprLexer.h cmExprLexer.cxx
+ - #include "cmStandardLexer.h" at the top: sed -i '1i#include "cmStandardLexer.h"' cmExprLexer.cxx
*/
@@ -473,7 +669,6 @@ Modify cmExprLexer.cxx:
#include "cmExprParserTokens.h"
/*--------------------------------------------------------------------------*/
-#line 476 "cmExprLexer.cxx"
#define INITIAL 0
@@ -515,44 +710,44 @@ struct yyguts_t
}; /* end struct yyguts_t */
-static int yy_init_globals (yyscan_t yyscanner );
+static int yy_init_globals ( yyscan_t yyscanner );
-int cmExpr_yylex_init (yyscan_t* scanner);
+int yylex_init (yyscan_t* scanner);
-int cmExpr_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
-int cmExpr_yylex_destroy (yyscan_t yyscanner );
+int yylex_destroy ( yyscan_t yyscanner );
-int cmExpr_yyget_debug (yyscan_t yyscanner );
+int yyget_debug ( yyscan_t yyscanner );
-void cmExpr_yyset_debug (int debug_flag ,yyscan_t yyscanner );
+void yyset_debug ( int debug_flag , yyscan_t yyscanner );
-YY_EXTRA_TYPE cmExpr_yyget_extra (yyscan_t yyscanner );
+YY_EXTRA_TYPE yyget_extra ( yyscan_t yyscanner );
-void cmExpr_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
+void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t yyscanner );
-FILE *cmExpr_yyget_in (yyscan_t yyscanner );
+FILE *yyget_in ( yyscan_t yyscanner );
-void cmExpr_yyset_in (FILE * _in_str ,yyscan_t yyscanner );
+void yyset_in ( FILE * _in_str , yyscan_t yyscanner );
-FILE *cmExpr_yyget_out (yyscan_t yyscanner );
+FILE *yyget_out ( yyscan_t yyscanner );
-void cmExpr_yyset_out (FILE * _out_str ,yyscan_t yyscanner );
+void yyset_out ( FILE * _out_str , yyscan_t yyscanner );
- int cmExpr_yyget_leng (yyscan_t yyscanner );
+ int yyget_leng ( yyscan_t yyscanner );
-char *cmExpr_yyget_text (yyscan_t yyscanner );
+char *yyget_text ( yyscan_t yyscanner );
-int cmExpr_yyget_lineno (yyscan_t yyscanner );
+int yyget_lineno ( yyscan_t yyscanner );
-void cmExpr_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+void yyset_lineno ( int _line_number , yyscan_t yyscanner );
-int cmExpr_yyget_column (yyscan_t yyscanner );
+int yyget_column ( yyscan_t yyscanner );
-void cmExpr_yyset_column (int _column_no ,yyscan_t yyscanner );
+void yyset_column ( int _column_no , yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
@@ -560,32 +755,31 @@ void cmExpr_yyset_column (int _column_no ,yyscan_t yyscanner );
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
-extern "C" int cmExpr_yywrap (yyscan_t yyscanner );
+extern "C" int yywrap ( yyscan_t yyscanner );
#else
-extern int cmExpr_yywrap (yyscan_t yyscanner );
+extern int yywrap ( yyscan_t yyscanner );
#endif
#endif
#ifndef YY_NO_UNPUT
- static void yyunput (int c,char *buf_ptr ,yyscan_t yyscanner);
+ static void yyunput ( int c, char *buf_ptr , yyscan_t yyscanner);
#endif
#ifndef yytext_ptr
-static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
+static void yy_flex_strncpy ( char *, const char *, int , yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
+static int yy_flex_strlen ( const char * , yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
-
#ifdef __cplusplus
-static int yyinput (yyscan_t yyscanner );
+static int yyinput ( yyscan_t yyscanner );
#else
-static int input (yyscan_t yyscanner );
+static int input ( yyscan_t yyscanner );
#endif
#endif
@@ -616,7 +810,7 @@ static int input (yyscan_t yyscanner );
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
- size_t n; \
+ int n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
@@ -629,7 +823,7 @@ static int input (yyscan_t yyscanner );
else \
{ \
errno=0; \
- while ( (result = (int) fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+ while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
@@ -670,9 +864,9 @@ static int input (yyscan_t yyscanner );
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
-extern int cmExpr_yylex (yyscan_t yyscanner);
+extern int yylex (yyscan_t yyscanner);
-#define YY_DECL int cmExpr_yylex (yyscan_t yyscanner)
+#define YY_DECL int yylex (yyscan_t yyscanner)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
@@ -717,19 +911,15 @@ YY_DECL
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
- cmExpr_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
- cmExpr_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner);
}
- cmExpr_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
}
{
-#line 39 "cmExprLexer.in.l"
-
-
-#line 732 "cmExprLexer.cxx"
while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */
{
@@ -757,9 +947,9 @@ yy_match:
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 23 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
++yy_cp;
}
while ( yy_base[yy_current_state] != 21 );
@@ -788,80 +978,64 @@ do_action: /* This label is used only to access EOF actions. */
case 1:
YY_RULE_SETUP
-#line 41 "cmExprLexer.in.l"
{ yylvalp->Number = atoi(yytext); return exp_NUMBER; }
YY_BREAK
case 2:
YY_RULE_SETUP
-#line 43 "cmExprLexer.in.l"
{ return exp_PLUS; }
YY_BREAK
case 3:
YY_RULE_SETUP
-#line 44 "cmExprLexer.in.l"
{ return exp_MINUS; }
YY_BREAK
case 4:
YY_RULE_SETUP
-#line 45 "cmExprLexer.in.l"
{ return exp_TIMES; }
YY_BREAK
case 5:
YY_RULE_SETUP
-#line 46 "cmExprLexer.in.l"
{ return exp_DIVIDE; }
YY_BREAK
case 6:
YY_RULE_SETUP
-#line 47 "cmExprLexer.in.l"
{ return exp_MOD; }
YY_BREAK
case 7:
YY_RULE_SETUP
-#line 48 "cmExprLexer.in.l"
{ return exp_OR; }
YY_BREAK
case 8:
YY_RULE_SETUP
-#line 49 "cmExprLexer.in.l"
{ return exp_AND; }
YY_BREAK
case 9:
YY_RULE_SETUP
-#line 50 "cmExprLexer.in.l"
{ return exp_XOR; }
YY_BREAK
case 10:
YY_RULE_SETUP
-#line 51 "cmExprLexer.in.l"
{ return exp_NOT; }
YY_BREAK
case 11:
YY_RULE_SETUP
-#line 52 "cmExprLexer.in.l"
{ return exp_SHIFTLEFT; }
YY_BREAK
case 12:
YY_RULE_SETUP
-#line 53 "cmExprLexer.in.l"
{ return exp_SHIFTRIGHT; }
YY_BREAK
case 13:
YY_RULE_SETUP
-#line 54 "cmExprLexer.in.l"
{ return exp_OPENPARENT; }
YY_BREAK
case 14:
YY_RULE_SETUP
-#line 55 "cmExprLexer.in.l"
{ return exp_CLOSEPARENT; }
YY_BREAK
case 15:
YY_RULE_SETUP
-#line 57 "cmExprLexer.in.l"
ECHO;
YY_BREAK
-#line 864 "cmExprLexer.cxx"
case YY_STATE_EOF(INITIAL):
yyterminate();
@@ -879,7 +1053,7 @@ case YY_STATE_EOF(INITIAL):
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
- * cmExpr_yylex(). If so, then we have to assure
+ * yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
@@ -939,7 +1113,7 @@ case YY_STATE_EOF(INITIAL):
{
yyg->yy_did_buffer_switch_on_eof = 0;
- if ( cmExpr_yywrap(yyscanner ) )
+ if ( yywrap( yyscanner ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
@@ -993,7 +1167,7 @@ case YY_STATE_EOF(INITIAL):
} /* end of action switch */
} /* end of scanning one token */
} /* end of user's declarations */
-} /* end of cmExpr_yylex */
+} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
@@ -1007,7 +1181,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
char *source = yyg->yytext_ptr;
- yy_size_t number_to_move, i;
+ int number_to_move, i;
int ret_val;
if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
@@ -1036,7 +1210,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
/* Try to read more data. */
/* First move last chars to start of buffer. */
- number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
+ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr - 1);
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
@@ -1072,7 +1246,8 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
- cmExpr_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
+ yyrealloc( (void *) b->yy_ch_buf,
+ (yy_size_t) (b->yy_buf_size + 2) , yyscanner );
}
else
/* Can't grow it, we don't own it. */
@@ -1104,7 +1279,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
- cmExpr_yyrestart(yyin ,yyscanner);
+ yyrestart( yyin , yyscanner);
}
else
@@ -1118,12 +1293,15 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
else
ret_val = EOB_ACT_CONTINUE_SCAN;
- if ((int) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
+ if ((yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
- YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) cmExpr_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
+ YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc(
+ (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size , yyscanner );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+ /* "- 2" to take care of EOB's */
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2);
}
yyg->yy_n_chars += number_to_move;
@@ -1157,9 +1335,9 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 23 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
}
return yy_current_state;
@@ -1186,9 +1364,9 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 23 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
yy_is_jam = (yy_current_state == 22);
(void)yyg;
@@ -1262,7 +1440,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
else
{ /* need more input */
- int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
+ int offset = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr);
++yyg->yy_c_buf_p;
switch ( yy_get_next_buffer( yyscanner ) )
@@ -1279,13 +1457,13 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
*/
/* Reset buffer status. */
- cmExpr_yyrestart(yyin ,yyscanner);
+ yyrestart( yyin , yyscanner);
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
- if ( cmExpr_yywrap(yyscanner ) )
+ if ( yywrap( yyscanner ) )
return 0;
if ( ! yyg->yy_did_buffer_switch_on_eof )
@@ -1317,34 +1495,34 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @note This function does not reset the start condition to @c INITIAL .
*/
- void cmExpr_yyrestart (FILE * input_file , yyscan_t yyscanner)
+ void yyrestart (FILE * input_file , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! YY_CURRENT_BUFFER ){
- cmExpr_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
- cmExpr_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner);
}
- cmExpr_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
- cmExpr_yy_load_buffer_state(yyscanner );
+ yy_init_buffer( YY_CURRENT_BUFFER, input_file , yyscanner);
+ yy_load_buffer_state( yyscanner );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
* @param yyscanner The scanner object.
*/
- void cmExpr_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
+ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* TODO. We should be able to replace this entire function body
* with
- * cmExpr_yypop_buffer_state();
- * cmExpr_yypush_buffer_state(new_buffer);
+ * yypop_buffer_state();
+ * yypush_buffer_state(new_buffer);
*/
- cmExpr_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
if ( YY_CURRENT_BUFFER == new_buffer )
return;
@@ -1357,17 +1535,17 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
- cmExpr_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
/* We don't actually know whether we did this switch during
- * EOF (cmExpr_yywrap()) processing, but the only time this flag
- * is looked at is after cmExpr_yywrap() is called, so it's safe
+ * EOF (yywrap()) processing, but the only time this flag
+ * is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
yyg->yy_did_buffer_switch_on_eof = 1;
}
-static void cmExpr_yy_load_buffer_state (yyscan_t yyscanner)
+static void yy_load_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
@@ -1382,35 +1560,35 @@ static void cmExpr_yy_load_buffer_state (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @return the allocated buffer state.
*/
- YY_BUFFER_STATE cmExpr_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
+ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
- b = (YY_BUFFER_STATE) cmExpr_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+ b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner );
if ( ! b )
- YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yy_create_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
- b->yy_buf_size = (yy_size_t)size;
+ b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
- b->yy_ch_buf = (char *) cmExpr_yyalloc(b->yy_buf_size + 2 ,yyscanner );
+ b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) , yyscanner );
if ( ! b->yy_ch_buf )
- YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yy_create_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
- cmExpr_yy_init_buffer(b,file ,yyscanner);
+ yy_init_buffer( b, file , yyscanner);
return b;
}
/** Destroy the buffer.
- * @param b a buffer created with cmExpr_yy_create_buffer()
+ * @param b a buffer created with yy_create_buffer()
* @param yyscanner The scanner object.
*/
- void cmExpr_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
+ void yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -1421,28 +1599,28 @@ static void cmExpr_yy_load_buffer_state (yyscan_t yyscanner)
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
- cmExpr_yyfree((void *) b->yy_ch_buf ,yyscanner );
+ yyfree( (void *) b->yy_ch_buf , yyscanner );
- cmExpr_yyfree((void *) b ,yyscanner );
+ yyfree( (void *) b , yyscanner );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
- * such as during a cmExpr_yyrestart() or at EOF.
+ * such as during a yyrestart() or at EOF.
*/
- static void cmExpr_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
+ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
{
int oerrno = errno;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
- cmExpr_yy_flush_buffer(b ,yyscanner);
+ yy_flush_buffer( b , yyscanner);
b->yy_input_file = file;
b->yy_fill_buffer = 1;
- /* If b is the current buffer, then cmExpr_yy_init_buffer was _probably_
- * called from cmExpr_yyrestart() or through yy_get_next_buffer.
+ /* If b is the current buffer, then yy_init_buffer was _probably_
+ * called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
@@ -1459,7 +1637,7 @@ static void cmExpr_yy_load_buffer_state (yyscan_t yyscanner)
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
* @param yyscanner The scanner object.
*/
- void cmExpr_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
+ void yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
@@ -1480,7 +1658,7 @@ static void cmExpr_yy_load_buffer_state (yyscan_t yyscanner)
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
- cmExpr_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
}
/** Pushes the new state onto the stack. The new state becomes
@@ -1489,15 +1667,15 @@ static void cmExpr_yy_load_buffer_state (yyscan_t yyscanner)
* @param new_buffer The new state.
* @param yyscanner The scanner object.
*/
-void cmExpr_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
+void yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (new_buffer == NULL)
return;
- cmExpr_yyensure_buffer_stack(yyscanner);
+ yyensure_buffer_stack(yyscanner);
- /* This block is copied from cmExpr_yy_switch_to_buffer. */
+ /* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
@@ -1511,8 +1689,8 @@ void cmExpr_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner
yyg->yy_buffer_stack_top++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
- /* copied from cmExpr_yy_switch_to_buffer. */
- cmExpr_yy_load_buffer_state(yyscanner );
+ /* copied from yy_switch_to_buffer. */
+ yy_load_buffer_state( yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
@@ -1520,19 +1698,19 @@ void cmExpr_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner
* The next element becomes the new top.
* @param yyscanner The scanner object.
*/
-void cmExpr_yypop_buffer_state (yyscan_t yyscanner)
+void yypop_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER)
return;
- cmExpr_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
+ yy_delete_buffer(YY_CURRENT_BUFFER , yyscanner);
YY_CURRENT_BUFFER_LVALUE = NULL;
if (yyg->yy_buffer_stack_top > 0)
--yyg->yy_buffer_stack_top;
if (YY_CURRENT_BUFFER) {
- cmExpr_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
}
@@ -1540,9 +1718,9 @@ void cmExpr_yypop_buffer_state (yyscan_t yyscanner)
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
-static void cmExpr_yyensure_buffer_stack (yyscan_t yyscanner)
+static void yyensure_buffer_stack (yyscan_t yyscanner)
{
- int num_to_alloc;
+ yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
@@ -1552,11 +1730,11 @@ static void cmExpr_yyensure_buffer_stack (yyscan_t yyscanner)
* immediate realloc on the next call.
*/
num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
- yyg->yy_buffer_stack = (struct yy_buffer_state**)cmExpr_yyalloc
+ yyg->yy_buffer_stack = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
- YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yyensure_buffer_stack()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
@@ -1571,12 +1749,12 @@ static void cmExpr_yyensure_buffer_stack (yyscan_t yyscanner)
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
- yyg->yy_buffer_stack = (struct yy_buffer_state**)cmExpr_yyrealloc
+ yyg->yy_buffer_stack = (struct yy_buffer_state**)yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
- YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yyensure_buffer_stack()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
@@ -1590,7 +1768,7 @@ static void cmExpr_yyensure_buffer_stack (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
-YY_BUFFER_STATE cmExpr_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
@@ -1600,11 +1778,11 @@ YY_BUFFER_STATE cmExpr_yy_scan_buffer (char * base, yy_size_t size , yyscan_t
/* They forgot to leave room for the EOB's. */
return NULL;
- b = (YY_BUFFER_STATE) cmExpr_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+ b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner );
if ( ! b )
- YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yy_scan_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
- b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
+ b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = NULL;
@@ -1614,53 +1792,53 @@ YY_BUFFER_STATE cmExpr_yy_scan_buffer (char * base, yy_size_t size , yyscan_t
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
- cmExpr_yy_switch_to_buffer(b ,yyscanner );
+ yy_switch_to_buffer( b , yyscanner );
return b;
}
-/** Setup the input buffer state to scan a string. The next call to cmExpr_yylex() will
+/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
- * cmExpr_yy_scan_bytes() instead.
+ * yy_scan_bytes() instead.
*/
-YY_BUFFER_STATE cmExpr_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_string (const char * yystr , yyscan_t yyscanner)
{
- return cmExpr_yy_scan_bytes(yystr,(int) strlen(yystr) ,yyscanner);
+ return yy_scan_bytes( yystr, (int) strlen(yystr) , yyscanner);
}
-/** Setup the input buffer state to scan the given bytes. The next call to cmExpr_yylex() will
+/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
-YY_BUFFER_STATE cmExpr_yy_scan_bytes (yyconst char * yybytes, int _yybytes_len , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
- yy_size_t i;
+ int i;
/* Get memory for full buffer, including space for trailing EOB's. */
- n = (yy_size_t) _yybytes_len + 2;
- buf = (char *) cmExpr_yyalloc(n ,yyscanner );
+ n = (yy_size_t) (_yybytes_len + 2);
+ buf = (char *) yyalloc( n , yyscanner );
if ( ! buf )
- YY_FATAL_ERROR( "out of dynamic memory in cmExpr_yy_scan_bytes()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
- for ( i = 0; i < (size_t)_yybytes_len; ++i )
+ for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
- b = cmExpr_yy_scan_buffer(buf,n ,yyscanner);
+ b = yy_scan_buffer( buf, n , yyscanner);
if ( ! b )
- YY_FATAL_ERROR( "bad buffer in cmExpr_yy_scan_bytes()" );
+ YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
@@ -1674,11 +1852,11 @@ YY_BUFFER_STATE cmExpr_yy_scan_bytes (yyconst char * yybytes, int _yybytes_len
#define YY_EXIT_FAILURE 2
#endif
-static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
+static void yynoreturn yy_fatal_error (const char* msg , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
- (void) fprintf( stderr, "%s\n", msg );
+ fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
@@ -1704,7 +1882,7 @@ static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
/** Get the user-defined data for this scanner.
* @param yyscanner The scanner object.
*/
-YY_EXTRA_TYPE cmExpr_yyget_extra (yyscan_t yyscanner)
+YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyextra;
@@ -1713,7 +1891,7 @@ YY_EXTRA_TYPE cmExpr_yyget_extra (yyscan_t yyscanner)
/** Get the current line number.
* @param yyscanner The scanner object.
*/
-int cmExpr_yyget_lineno (yyscan_t yyscanner)
+int yyget_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -1726,7 +1904,7 @@ int cmExpr_yyget_lineno (yyscan_t yyscanner)
/** Get the current column number.
* @param yyscanner The scanner object.
*/
-int cmExpr_yyget_column (yyscan_t yyscanner)
+int yyget_column (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -1739,7 +1917,7 @@ int cmExpr_yyget_column (yyscan_t yyscanner)
/** Get the input stream.
* @param yyscanner The scanner object.
*/
-FILE *cmExpr_yyget_in (yyscan_t yyscanner)
+FILE *yyget_in (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyin;
@@ -1748,7 +1926,7 @@ FILE *cmExpr_yyget_in (yyscan_t yyscanner)
/** Get the output stream.
* @param yyscanner The scanner object.
*/
-FILE *cmExpr_yyget_out (yyscan_t yyscanner)
+FILE *yyget_out (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyout;
@@ -1757,7 +1935,7 @@ FILE *cmExpr_yyget_out (yyscan_t yyscanner)
/** Get the length of the current token.
* @param yyscanner The scanner object.
*/
-int cmExpr_yyget_leng (yyscan_t yyscanner)
+int yyget_leng (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyleng;
@@ -1767,7 +1945,7 @@ int cmExpr_yyget_leng (yyscan_t yyscanner)
* @param yyscanner The scanner object.
*/
-char *cmExpr_yyget_text (yyscan_t yyscanner)
+char *yyget_text (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yytext;
@@ -1777,7 +1955,7 @@ char *cmExpr_yyget_text (yyscan_t yyscanner)
* @param user_defined The data to be associated with this scanner.
* @param yyscanner The scanner object.
*/
-void cmExpr_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
+void yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyextra = user_defined ;
@@ -1787,13 +1965,13 @@ void cmExpr_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
* @param _line_number line number
* @param yyscanner The scanner object.
*/
-void cmExpr_yyset_lineno (int _line_number , yyscan_t yyscanner)
+void yyset_lineno (int _line_number , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* lineno is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
- YY_FATAL_ERROR( "cmExpr_yyset_lineno called with no buffer" );
+ YY_FATAL_ERROR( "yyset_lineno called with no buffer" );
yylineno = _line_number;
}
@@ -1802,13 +1980,13 @@ void cmExpr_yyset_lineno (int _line_number , yyscan_t yyscanner)
* @param _column_no column number
* @param yyscanner The scanner object.
*/
-void cmExpr_yyset_column (int _column_no , yyscan_t yyscanner)
+void yyset_column (int _column_no , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* column is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
- YY_FATAL_ERROR( "cmExpr_yyset_column called with no buffer" );
+ YY_FATAL_ERROR( "yyset_column called with no buffer" );
yycolumn = _column_no;
}
@@ -1817,27 +1995,27 @@ void cmExpr_yyset_column (int _column_no , yyscan_t yyscanner)
* input buffer.
* @param _in_str A readable stream.
* @param yyscanner The scanner object.
- * @see cmExpr_yy_switch_to_buffer
+ * @see yy_switch_to_buffer
*/
-void cmExpr_yyset_in (FILE * _in_str , yyscan_t yyscanner)
+void yyset_in (FILE * _in_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyin = _in_str ;
}
-void cmExpr_yyset_out (FILE * _out_str , yyscan_t yyscanner)
+void yyset_out (FILE * _out_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyout = _out_str ;
}
-int cmExpr_yyget_debug (yyscan_t yyscanner)
+int yyget_debug (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yy_flex_debug;
}
-void cmExpr_yyset_debug (int _bdebug , yyscan_t yyscanner)
+void yyset_debug (int _bdebug , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_flex_debug = _bdebug ;
@@ -1847,20 +2025,18 @@ void cmExpr_yyset_debug (int _bdebug , yyscan_t yyscanner)
/* User-visible API */
-/* cmExpr_yylex_init is special because it creates the scanner itself, so it is
+/* yylex_init is special because it creates the scanner itself, so it is
* the ONLY reentrant function that doesn't take the scanner as the last argument.
* That's why we explicitly handle the declaration, instead of using our macros.
*/
-
-int cmExpr_yylex_init(yyscan_t* ptr_yy_globals)
-
+int yylex_init(yyscan_t* ptr_yy_globals)
{
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
- *ptr_yy_globals = (yyscan_t) cmExpr_yyalloc ( sizeof( struct yyguts_t ), NULL );
+ *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), NULL );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
@@ -1873,27 +2049,25 @@ int cmExpr_yylex_init(yyscan_t* ptr_yy_globals)
return yy_init_globals ( *ptr_yy_globals );
}
-/* cmExpr_yylex_init_extra has the same functionality as cmExpr_yylex_init, but follows the
+/* yylex_init_extra has the same functionality as yylex_init, but follows the
* convention of taking the scanner as the last argument. Note however, that
* this is a *pointer* to a scanner, as it will be allocated by this call (and
* is the reason, too, why this function also must handle its own declaration).
- * The user defined value in the first argument will be available to cmExpr_yyalloc in
+ * The user defined value in the first argument will be available to yyalloc in
* the yyextra field.
*/
-
-int cmExpr_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )
-
+int yylex_init_extra( YY_EXTRA_TYPE yy_user_defined, yyscan_t* ptr_yy_globals )
{
struct yyguts_t dummy_yyguts;
- cmExpr_yyset_extra (yy_user_defined, &dummy_yyguts);
+ yyset_extra (yy_user_defined, &dummy_yyguts);
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
- *ptr_yy_globals = (yyscan_t) cmExpr_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
+ *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
@@ -1904,7 +2078,7 @@ int cmExpr_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globa
yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
- cmExpr_yyset_extra (yy_user_defined, *ptr_yy_globals);
+ yyset_extra (yy_user_defined, *ptr_yy_globals);
return yy_init_globals ( *ptr_yy_globals );
}
@@ -1913,7 +2087,7 @@ static int yy_init_globals (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Initialization is the same as for the non-reentrant scanner.
- * This function is called from cmExpr_yylex_destroy(), so don't allocate here.
+ * This function is called from yylex_destroy(), so don't allocate here.
*/
yyg->yy_buffer_stack = NULL;
@@ -1937,37 +2111,37 @@ static int yy_init_globals (yyscan_t yyscanner)
#endif
/* For future reference: Set errno on error, since we are called by
- * cmExpr_yylex_init()
+ * yylex_init()
*/
return 0;
}
-/* cmExpr_yylex_destroy is for both reentrant and non-reentrant scanners. */
-int cmExpr_yylex_destroy (yyscan_t yyscanner)
+/* yylex_destroy is for both reentrant and non-reentrant scanners. */
+int yylex_destroy (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
- cmExpr_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
+ yy_delete_buffer( YY_CURRENT_BUFFER , yyscanner );
YY_CURRENT_BUFFER_LVALUE = NULL;
- cmExpr_yypop_buffer_state(yyscanner);
+ yypop_buffer_state(yyscanner);
}
/* Destroy the stack itself. */
- cmExpr_yyfree(yyg->yy_buffer_stack ,yyscanner);
+ yyfree(yyg->yy_buffer_stack , yyscanner);
yyg->yy_buffer_stack = NULL;
/* Destroy the start condition stack. */
- cmExpr_yyfree(yyg->yy_start_stack ,yyscanner );
+ yyfree( yyg->yy_start_stack , yyscanner );
yyg->yy_start_stack = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
- * cmExpr_yylex() is called, initialization will occur. */
+ * yylex() is called, initialization will occur. */
yy_init_globals( yyscanner);
/* Destroy the main struct (reentrant only). */
- cmExpr_yyfree ( yyscanner , yyscanner );
+ yyfree ( yyscanner , yyscanner );
yyscanner = NULL;
return 0;
}
@@ -1977,7 +2151,7 @@ int cmExpr_yylex_destroy (yyscan_t yyscanner)
*/
#ifndef yytext_ptr
-static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner)
+static void yy_flex_strncpy (char* s1, const char * s2, int n , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
@@ -1989,7 +2163,7 @@ static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yysca
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
+static int yy_flex_strlen (const char * s , yyscan_t yyscanner)
{
int n;
for ( n = 0; s[n]; ++n )
@@ -1999,14 +2173,14 @@ static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
}
#endif
-void *cmExpr_yyalloc (yy_size_t size , yyscan_t yyscanner)
+void *yyalloc (yy_size_t size , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
return malloc(size);
}
-void *cmExpr_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
+void *yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
@@ -2021,13 +2195,11 @@ void *cmExpr_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
return realloc(ptr, size);
}
-void cmExpr_yyfree (void * ptr , yyscan_t yyscanner)
+void yyfree (void * ptr , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
- free( (char *) ptr ); /* see cmExpr_yyrealloc() for (char *) cast */
+ free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
-
-#line 57 "cmExprLexer.in.l"
diff --git a/Source/LexerParser/cmExprLexer.h b/Source/LexerParser/cmExprLexer.h
index 835a7a36a..b55ee92e5 100644
--- a/Source/LexerParser/cmExprLexer.h
+++ b/Source/LexerParser/cmExprLexer.h
@@ -2,10 +2,6 @@
#define cmExpr_yyHEADER_H 1
#define cmExpr_yyIN_HEADER 1
-#line 6 "cmExprLexer.h"
-
-#line 8 "cmExprLexer.h"
-
#define FLEXINT_H 1
#define YY_INT_ALIGNED short int
@@ -14,11 +10,221 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
-#define YY_FLEX_SUBMINOR_VERSION 1
+#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
+#ifdef yy_create_buffer
+#define cmExpr_yy_create_buffer_ALREADY_DEFINED
+#else
+#define yy_create_buffer cmExpr_yy_create_buffer
+#endif
+
+#ifdef yy_delete_buffer
+#define cmExpr_yy_delete_buffer_ALREADY_DEFINED
+#else
+#define yy_delete_buffer cmExpr_yy_delete_buffer
+#endif
+
+#ifdef yy_scan_buffer
+#define cmExpr_yy_scan_buffer_ALREADY_DEFINED
+#else
+#define yy_scan_buffer cmExpr_yy_scan_buffer
+#endif
+
+#ifdef yy_scan_string
+#define cmExpr_yy_scan_string_ALREADY_DEFINED
+#else
+#define yy_scan_string cmExpr_yy_scan_string
+#endif
+
+#ifdef yy_scan_bytes
+#define cmExpr_yy_scan_bytes_ALREADY_DEFINED
+#else
+#define yy_scan_bytes cmExpr_yy_scan_bytes
+#endif
+
+#ifdef yy_init_buffer
+#define cmExpr_yy_init_buffer_ALREADY_DEFINED
+#else
+#define yy_init_buffer cmExpr_yy_init_buffer
+#endif
+
+#ifdef yy_flush_buffer
+#define cmExpr_yy_flush_buffer_ALREADY_DEFINED
+#else
+#define yy_flush_buffer cmExpr_yy_flush_buffer
+#endif
+
+#ifdef yy_load_buffer_state
+#define cmExpr_yy_load_buffer_state_ALREADY_DEFINED
+#else
+#define yy_load_buffer_state cmExpr_yy_load_buffer_state
+#endif
+
+#ifdef yy_switch_to_buffer
+#define cmExpr_yy_switch_to_buffer_ALREADY_DEFINED
+#else
+#define yy_switch_to_buffer cmExpr_yy_switch_to_buffer
+#endif
+
+#ifdef yypush_buffer_state
+#define cmExpr_yypush_buffer_state_ALREADY_DEFINED
+#else
+#define yypush_buffer_state cmExpr_yypush_buffer_state
+#endif
+
+#ifdef yypop_buffer_state
+#define cmExpr_yypop_buffer_state_ALREADY_DEFINED
+#else
+#define yypop_buffer_state cmExpr_yypop_buffer_state
+#endif
+
+#ifdef yyensure_buffer_stack
+#define cmExpr_yyensure_buffer_stack_ALREADY_DEFINED
+#else
+#define yyensure_buffer_stack cmExpr_yyensure_buffer_stack
+#endif
+
+#ifdef yylex
+#define cmExpr_yylex_ALREADY_DEFINED
+#else
+#define yylex cmExpr_yylex
+#endif
+
+#ifdef yyrestart
+#define cmExpr_yyrestart_ALREADY_DEFINED
+#else
+#define yyrestart cmExpr_yyrestart
+#endif
+
+#ifdef yylex_init
+#define cmExpr_yylex_init_ALREADY_DEFINED
+#else
+#define yylex_init cmExpr_yylex_init
+#endif
+
+#ifdef yylex_init_extra
+#define cmExpr_yylex_init_extra_ALREADY_DEFINED
+#else
+#define yylex_init_extra cmExpr_yylex_init_extra
+#endif
+
+#ifdef yylex_destroy
+#define cmExpr_yylex_destroy_ALREADY_DEFINED
+#else
+#define yylex_destroy cmExpr_yylex_destroy
+#endif
+
+#ifdef yyget_debug
+#define cmExpr_yyget_debug_ALREADY_DEFINED
+#else
+#define yyget_debug cmExpr_yyget_debug
+#endif
+
+#ifdef yyset_debug
+#define cmExpr_yyset_debug_ALREADY_DEFINED
+#else
+#define yyset_debug cmExpr_yyset_debug
+#endif
+
+#ifdef yyget_extra
+#define cmExpr_yyget_extra_ALREADY_DEFINED
+#else
+#define yyget_extra cmExpr_yyget_extra
+#endif
+
+#ifdef yyset_extra
+#define cmExpr_yyset_extra_ALREADY_DEFINED
+#else
+#define yyset_extra cmExpr_yyset_extra
+#endif
+
+#ifdef yyget_in
+#define cmExpr_yyget_in_ALREADY_DEFINED
+#else
+#define yyget_in cmExpr_yyget_in
+#endif
+
+#ifdef yyset_in
+#define cmExpr_yyset_in_ALREADY_DEFINED
+#else
+#define yyset_in cmExpr_yyset_in
+#endif
+
+#ifdef yyget_out
+#define cmExpr_yyget_out_ALREADY_DEFINED
+#else
+#define yyget_out cmExpr_yyget_out
+#endif
+
+#ifdef yyset_out
+#define cmExpr_yyset_out_ALREADY_DEFINED
+#else
+#define yyset_out cmExpr_yyset_out
+#endif
+
+#ifdef yyget_leng
+#define cmExpr_yyget_leng_ALREADY_DEFINED
+#else
+#define yyget_leng cmExpr_yyget_leng
+#endif
+
+#ifdef yyget_text
+#define cmExpr_yyget_text_ALREADY_DEFINED
+#else
+#define yyget_text cmExpr_yyget_text
+#endif
+
+#ifdef yyget_lineno
+#define cmExpr_yyget_lineno_ALREADY_DEFINED
+#else
+#define yyget_lineno cmExpr_yyget_lineno
+#endif
+
+#ifdef yyset_lineno
+#define cmExpr_yyset_lineno_ALREADY_DEFINED
+#else
+#define yyset_lineno cmExpr_yyset_lineno
+#endif
+
+#ifdef yyget_column
+#define cmExpr_yyget_column_ALREADY_DEFINED
+#else
+#define yyget_column cmExpr_yyget_column
+#endif
+
+#ifdef yyset_column
+#define cmExpr_yyset_column_ALREADY_DEFINED
+#else
+#define yyset_column cmExpr_yyset_column
+#endif
+
+#ifdef yywrap
+#define cmExpr_yywrap_ALREADY_DEFINED
+#else
+#define yywrap cmExpr_yywrap
+#endif
+
+#ifdef yyalloc
+#define cmExpr_yyalloc_ALREADY_DEFINED
+#else
+#define yyalloc cmExpr_yyalloc
+#endif
+
+#ifdef yyrealloc
+#define cmExpr_yyrealloc_ALREADY_DEFINED
+#else
+#define yyrealloc cmExpr_yyrealloc
+#endif
+
+#ifdef yyfree
+#define cmExpr_yyfree_ALREADY_DEFINED
+#else
+#define yyfree cmExpr_yyfree
+#endif
+
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
@@ -89,10 +295,16 @@ typedef unsigned int flex_uint32_t;
#define UINT32_MAX (4294967295U)
#endif
+#ifndef SIZE_MAX
+#define SIZE_MAX (~(size_t)0)
+#endif
+
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
+/* begin standard C++ headers. */
+
/* TODO: this is always defined, so inline it */
#define yyconst const
@@ -193,21 +405,21 @@ struct yy_buffer_state
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
-void cmExpr_yyrestart (FILE *input_file ,yyscan_t yyscanner );
-void cmExpr_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmExpr_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
-void cmExpr_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmExpr_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmExpr_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-void cmExpr_yypop_buffer_state (yyscan_t yyscanner );
+void yyrestart ( FILE *input_file , yyscan_t yyscanner );
+void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size , yyscan_t yyscanner );
+void yy_delete_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yy_flush_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yypush_buffer_state ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+void yypop_buffer_state ( yyscan_t yyscanner );
-YY_BUFFER_STATE cmExpr_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmExpr_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmExpr_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_string ( const char *yy_str , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len , yyscan_t yyscanner );
-void *cmExpr_yyalloc (yy_size_t ,yyscan_t yyscanner );
-void *cmExpr_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
-void cmExpr_yyfree (void * ,yyscan_t yyscanner );
+void *yyalloc ( yy_size_t , yyscan_t yyscanner );
+void *yyrealloc ( void *, yy_size_t , yyscan_t yyscanner );
+void yyfree ( void * , yyscan_t yyscanner );
/* Begin user sect3 */
@@ -225,42 +437,42 @@ void cmExpr_yyfree (void * ,yyscan_t yyscanner );
#define YY_EXTRA_TYPE void *
#endif
-int cmExpr_yylex_init (yyscan_t* scanner);
+int yylex_init (yyscan_t* scanner);
-int cmExpr_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
-int cmExpr_yylex_destroy (yyscan_t yyscanner );
+int yylex_destroy ( yyscan_t yyscanner );
-int cmExpr_yyget_debug (yyscan_t yyscanner );
+int yyget_debug ( yyscan_t yyscanner );
-void cmExpr_yyset_debug (int debug_flag ,yyscan_t yyscanner );
+void yyset_debug ( int debug_flag , yyscan_t yyscanner );
-YY_EXTRA_TYPE cmExpr_yyget_extra (yyscan_t yyscanner );
+YY_EXTRA_TYPE yyget_extra ( yyscan_t yyscanner );
-void cmExpr_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
+void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t yyscanner );
-FILE *cmExpr_yyget_in (yyscan_t yyscanner );
+FILE *yyget_in ( yyscan_t yyscanner );
-void cmExpr_yyset_in (FILE * _in_str ,yyscan_t yyscanner );
+void yyset_in ( FILE * _in_str , yyscan_t yyscanner );
-FILE *cmExpr_yyget_out (yyscan_t yyscanner );
+FILE *yyget_out ( yyscan_t yyscanner );
-void cmExpr_yyset_out (FILE * _out_str ,yyscan_t yyscanner );
+void yyset_out ( FILE * _out_str , yyscan_t yyscanner );
- int cmExpr_yyget_leng (yyscan_t yyscanner );
+ int yyget_leng ( yyscan_t yyscanner );
-char *cmExpr_yyget_text (yyscan_t yyscanner );
+char *yyget_text ( yyscan_t yyscanner );
-int cmExpr_yyget_lineno (yyscan_t yyscanner );
+int yyget_lineno ( yyscan_t yyscanner );
-void cmExpr_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+void yyset_lineno ( int _line_number , yyscan_t yyscanner );
-int cmExpr_yyget_column (yyscan_t yyscanner );
+int yyget_column ( yyscan_t yyscanner );
-void cmExpr_yyset_column (int _column_no ,yyscan_t yyscanner );
+void yyset_column ( int _column_no , yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
@@ -268,18 +480,18 @@ void cmExpr_yyset_column (int _column_no ,yyscan_t yyscanner );
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
-extern "C" int cmExpr_yywrap (yyscan_t yyscanner );
+extern "C" int yywrap ( yyscan_t yyscanner );
#else
-extern int cmExpr_yywrap (yyscan_t yyscanner );
+extern int yywrap ( yyscan_t yyscanner );
#endif
#endif
#ifndef yytext_ptr
-static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
+static void yy_flex_strncpy ( char *, const char *, int , yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
+static int yy_flex_strlen ( const char * , yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
@@ -307,9 +519,9 @@ static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
-extern int cmExpr_yylex (yyscan_t yyscanner);
+extern int yylex (yyscan_t yyscanner);
-#define YY_DECL int cmExpr_yylex (yyscan_t yyscanner)
+#define YY_DECL int yylex (yyscan_t yyscanner)
#endif /* !YY_DECL */
/* yy_get_previous_state - get the state just before the EOB char was reached */
@@ -326,9 +538,150 @@ extern int cmExpr_yylex (yyscan_t yyscanner);
#undef YY_DECL
#endif
-#line 57 "cmExprLexer.in.l"
-
+#ifndef cmExpr_yy_create_buffer_ALREADY_DEFINED
+#undef yy_create_buffer
+#endif
+#ifndef cmExpr_yy_delete_buffer_ALREADY_DEFINED
+#undef yy_delete_buffer
+#endif
+#ifndef cmExpr_yy_scan_buffer_ALREADY_DEFINED
+#undef yy_scan_buffer
+#endif
+#ifndef cmExpr_yy_scan_string_ALREADY_DEFINED
+#undef yy_scan_string
+#endif
+#ifndef cmExpr_yy_scan_bytes_ALREADY_DEFINED
+#undef yy_scan_bytes
+#endif
+#ifndef cmExpr_yy_init_buffer_ALREADY_DEFINED
+#undef yy_init_buffer
+#endif
+#ifndef cmExpr_yy_flush_buffer_ALREADY_DEFINED
+#undef yy_flush_buffer
+#endif
+#ifndef cmExpr_yy_load_buffer_state_ALREADY_DEFINED
+#undef yy_load_buffer_state
+#endif
+#ifndef cmExpr_yy_switch_to_buffer_ALREADY_DEFINED
+#undef yy_switch_to_buffer
+#endif
+#ifndef cmExpr_yypush_buffer_state_ALREADY_DEFINED
+#undef yypush_buffer_state
+#endif
+#ifndef cmExpr_yypop_buffer_state_ALREADY_DEFINED
+#undef yypop_buffer_state
+#endif
+#ifndef cmExpr_yyensure_buffer_stack_ALREADY_DEFINED
+#undef yyensure_buffer_stack
+#endif
+#ifndef cmExpr_yylex_ALREADY_DEFINED
+#undef yylex
+#endif
+#ifndef cmExpr_yyrestart_ALREADY_DEFINED
+#undef yyrestart
+#endif
+#ifndef cmExpr_yylex_init_ALREADY_DEFINED
+#undef yylex_init
+#endif
+#ifndef cmExpr_yylex_init_extra_ALREADY_DEFINED
+#undef yylex_init_extra
+#endif
+#ifndef cmExpr_yylex_destroy_ALREADY_DEFINED
+#undef yylex_destroy
+#endif
+#ifndef cmExpr_yyget_debug_ALREADY_DEFINED
+#undef yyget_debug
+#endif
+#ifndef cmExpr_yyset_debug_ALREADY_DEFINED
+#undef yyset_debug
+#endif
+#ifndef cmExpr_yyget_extra_ALREADY_DEFINED
+#undef yyget_extra
+#endif
+#ifndef cmExpr_yyset_extra_ALREADY_DEFINED
+#undef yyset_extra
+#endif
+#ifndef cmExpr_yyget_in_ALREADY_DEFINED
+#undef yyget_in
+#endif
+#ifndef cmExpr_yyset_in_ALREADY_DEFINED
+#undef yyset_in
+#endif
+#ifndef cmExpr_yyget_out_ALREADY_DEFINED
+#undef yyget_out
+#endif
+#ifndef cmExpr_yyset_out_ALREADY_DEFINED
+#undef yyset_out
+#endif
+#ifndef cmExpr_yyget_leng_ALREADY_DEFINED
+#undef yyget_leng
+#endif
+#ifndef cmExpr_yyget_text_ALREADY_DEFINED
+#undef yyget_text
+#endif
+#ifndef cmExpr_yyget_lineno_ALREADY_DEFINED
+#undef yyget_lineno
+#endif
+#ifndef cmExpr_yyset_lineno_ALREADY_DEFINED
+#undef yyset_lineno
+#endif
+#ifndef cmExpr_yyget_column_ALREADY_DEFINED
+#undef yyget_column
+#endif
+#ifndef cmExpr_yyset_column_ALREADY_DEFINED
+#undef yyset_column
+#endif
+#ifndef cmExpr_yywrap_ALREADY_DEFINED
+#undef yywrap
+#endif
+#ifndef cmExpr_yyget_lval_ALREADY_DEFINED
+#undef yyget_lval
+#endif
+#ifndef cmExpr_yyset_lval_ALREADY_DEFINED
+#undef yyset_lval
+#endif
+#ifndef cmExpr_yyget_lloc_ALREADY_DEFINED
+#undef yyget_lloc
+#endif
+#ifndef cmExpr_yyset_lloc_ALREADY_DEFINED
+#undef yyset_lloc
+#endif
+#ifndef cmExpr_yyalloc_ALREADY_DEFINED
+#undef yyalloc
+#endif
+#ifndef cmExpr_yyrealloc_ALREADY_DEFINED
+#undef yyrealloc
+#endif
+#ifndef cmExpr_yyfree_ALREADY_DEFINED
+#undef yyfree
+#endif
+#ifndef cmExpr_yytext_ALREADY_DEFINED
+#undef yytext
+#endif
+#ifndef cmExpr_yyleng_ALREADY_DEFINED
+#undef yyleng
+#endif
+#ifndef cmExpr_yyin_ALREADY_DEFINED
+#undef yyin
+#endif
+#ifndef cmExpr_yyout_ALREADY_DEFINED
+#undef yyout
+#endif
+#ifndef cmExpr_yy_flex_debug_ALREADY_DEFINED
+#undef yy_flex_debug
+#endif
+#ifndef cmExpr_yylineno_ALREADY_DEFINED
+#undef yylineno
+#endif
+#ifndef cmExpr_yytables_fload_ALREADY_DEFINED
+#undef yytables_fload
+#endif
+#ifndef cmExpr_yytables_destroy_ALREADY_DEFINED
+#undef yytables_destroy
+#endif
+#ifndef cmExpr_yyTABLES_NAME_ALREADY_DEFINED
+#undef yyTABLES_NAME
+#endif
-#line 333 "cmExprLexer.h"
#undef cmExpr_yyIN_HEADER
#endif /* cmExpr_yyHEADER_H */
diff --git a/Source/LexerParser/cmExprLexer.in.l b/Source/LexerParser/cmExprLexer.in.l
index 25ddba460..e5f177a35 100644
--- a/Source/LexerParser/cmExprLexer.in.l
+++ b/Source/LexerParser/cmExprLexer.in.l
@@ -7,13 +7,12 @@ This file must be translated to C++ and modified to build everywhere.
Run flex >= 2.6 like this:
- flex --nounistd -DFLEXINT_H --prefix=cmExpr_yy --header-file=cmExprLexer.h -ocmExprLexer.cxx cmExprLexer.in.l
+ flex --nounistd -DFLEXINT_H --noline --header-file=cmExprLexer.h -ocmExprLexer.cxx cmExprLexer.in.l
Modify cmExprLexer.cxx:
- - remove trailing whitespace: sed -i 's/\s*$//' cmExprLexer.h cmExprLexer.cxx
- - remove blank lines at end of file
- - #include "cmStandardLexer.h" at the top
- - add cast in yy_scan_bytes for loop condition of _yybytes_len to size_t
+ - remove trailing whitespace: sed -i 's/\s*$//' cmExprLexer.h cmExprLexer.cxx
+ - remove blank lines at end of file: sed -i '${/^$/d;}' cmExprLexer.h cmExprLexer.cxx
+ - #include "cmStandardLexer.h" at the top: sed -i '1i#include "cmStandardLexer.h"' cmExprLexer.cxx
*/
@@ -32,6 +31,8 @@ Modify cmExprLexer.cxx:
/*--------------------------------------------------------------------------*/
%}
+%option prefix="cmExpr_yy"
+
%option reentrant
%option noyywrap
%pointer
diff --git a/Source/LexerParser/cmFortranLexer.cxx b/Source/LexerParser/cmFortranLexer.cxx
index 01c09acb7..dec0f5eb3 100644
--- a/Source/LexerParser/cmFortranLexer.cxx
+++ b/Source/LexerParser/cmFortranLexer.cxx
@@ -1,7 +1,4 @@
#include "cmStandardLexer.h"
-#line 2 "cmFortranLexer.cxx"
-
-#line 4 "cmFortranLexer.cxx"
#define FLEXINT_H 1
#define YY_INT_ALIGNED short int
@@ -11,11 +8,221 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
-#define YY_FLEX_SUBMINOR_VERSION 1
+#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
+#ifdef yy_create_buffer
+#define cmFortran_yy_create_buffer_ALREADY_DEFINED
+#else
+#define yy_create_buffer cmFortran_yy_create_buffer
+#endif
+
+#ifdef yy_delete_buffer
+#define cmFortran_yy_delete_buffer_ALREADY_DEFINED
+#else
+#define yy_delete_buffer cmFortran_yy_delete_buffer
+#endif
+
+#ifdef yy_scan_buffer
+#define cmFortran_yy_scan_buffer_ALREADY_DEFINED
+#else
+#define yy_scan_buffer cmFortran_yy_scan_buffer
+#endif
+
+#ifdef yy_scan_string
+#define cmFortran_yy_scan_string_ALREADY_DEFINED
+#else
+#define yy_scan_string cmFortran_yy_scan_string
+#endif
+
+#ifdef yy_scan_bytes
+#define cmFortran_yy_scan_bytes_ALREADY_DEFINED
+#else
+#define yy_scan_bytes cmFortran_yy_scan_bytes
+#endif
+
+#ifdef yy_init_buffer
+#define cmFortran_yy_init_buffer_ALREADY_DEFINED
+#else
+#define yy_init_buffer cmFortran_yy_init_buffer
+#endif
+
+#ifdef yy_flush_buffer
+#define cmFortran_yy_flush_buffer_ALREADY_DEFINED
+#else
+#define yy_flush_buffer cmFortran_yy_flush_buffer
+#endif
+
+#ifdef yy_load_buffer_state
+#define cmFortran_yy_load_buffer_state_ALREADY_DEFINED
+#else
+#define yy_load_buffer_state cmFortran_yy_load_buffer_state
+#endif
+
+#ifdef yy_switch_to_buffer
+#define cmFortran_yy_switch_to_buffer_ALREADY_DEFINED
+#else
+#define yy_switch_to_buffer cmFortran_yy_switch_to_buffer
+#endif
+
+#ifdef yypush_buffer_state
+#define cmFortran_yypush_buffer_state_ALREADY_DEFINED
+#else
+#define yypush_buffer_state cmFortran_yypush_buffer_state
+#endif
+
+#ifdef yypop_buffer_state
+#define cmFortran_yypop_buffer_state_ALREADY_DEFINED
+#else
+#define yypop_buffer_state cmFortran_yypop_buffer_state
+#endif
+
+#ifdef yyensure_buffer_stack
+#define cmFortran_yyensure_buffer_stack_ALREADY_DEFINED
+#else
+#define yyensure_buffer_stack cmFortran_yyensure_buffer_stack
+#endif
+
+#ifdef yylex
+#define cmFortran_yylex_ALREADY_DEFINED
+#else
+#define yylex cmFortran_yylex
+#endif
+
+#ifdef yyrestart
+#define cmFortran_yyrestart_ALREADY_DEFINED
+#else
+#define yyrestart cmFortran_yyrestart
+#endif
+
+#ifdef yylex_init
+#define cmFortran_yylex_init_ALREADY_DEFINED
+#else
+#define yylex_init cmFortran_yylex_init
+#endif
+
+#ifdef yylex_init_extra
+#define cmFortran_yylex_init_extra_ALREADY_DEFINED
+#else
+#define yylex_init_extra cmFortran_yylex_init_extra
+#endif
+
+#ifdef yylex_destroy
+#define cmFortran_yylex_destroy_ALREADY_DEFINED
+#else
+#define yylex_destroy cmFortran_yylex_destroy
+#endif
+
+#ifdef yyget_debug
+#define cmFortran_yyget_debug_ALREADY_DEFINED
+#else
+#define yyget_debug cmFortran_yyget_debug
+#endif
+
+#ifdef yyset_debug
+#define cmFortran_yyset_debug_ALREADY_DEFINED
+#else
+#define yyset_debug cmFortran_yyset_debug
+#endif
+
+#ifdef yyget_extra
+#define cmFortran_yyget_extra_ALREADY_DEFINED
+#else
+#define yyget_extra cmFortran_yyget_extra
+#endif
+
+#ifdef yyset_extra
+#define cmFortran_yyset_extra_ALREADY_DEFINED
+#else
+#define yyset_extra cmFortran_yyset_extra
+#endif
+
+#ifdef yyget_in
+#define cmFortran_yyget_in_ALREADY_DEFINED
+#else
+#define yyget_in cmFortran_yyget_in
+#endif
+
+#ifdef yyset_in
+#define cmFortran_yyset_in_ALREADY_DEFINED
+#else
+#define yyset_in cmFortran_yyset_in
+#endif
+
+#ifdef yyget_out
+#define cmFortran_yyget_out_ALREADY_DEFINED
+#else
+#define yyget_out cmFortran_yyget_out
+#endif
+
+#ifdef yyset_out
+#define cmFortran_yyset_out_ALREADY_DEFINED
+#else
+#define yyset_out cmFortran_yyset_out
+#endif
+
+#ifdef yyget_leng
+#define cmFortran_yyget_leng_ALREADY_DEFINED
+#else
+#define yyget_leng cmFortran_yyget_leng
+#endif
+
+#ifdef yyget_text
+#define cmFortran_yyget_text_ALREADY_DEFINED
+#else
+#define yyget_text cmFortran_yyget_text
+#endif
+
+#ifdef yyget_lineno
+#define cmFortran_yyget_lineno_ALREADY_DEFINED
+#else
+#define yyget_lineno cmFortran_yyget_lineno
+#endif
+
+#ifdef yyset_lineno
+#define cmFortran_yyset_lineno_ALREADY_DEFINED
+#else
+#define yyset_lineno cmFortran_yyset_lineno
+#endif
+
+#ifdef yyget_column
+#define cmFortran_yyget_column_ALREADY_DEFINED
+#else
+#define yyget_column cmFortran_yyget_column
+#endif
+
+#ifdef yyset_column
+#define cmFortran_yyset_column_ALREADY_DEFINED
+#else
+#define yyset_column cmFortran_yyset_column
+#endif
+
+#ifdef yywrap
+#define cmFortran_yywrap_ALREADY_DEFINED
+#else
+#define yywrap cmFortran_yywrap
+#endif
+
+#ifdef yyalloc
+#define cmFortran_yyalloc_ALREADY_DEFINED
+#else
+#define yyalloc cmFortran_yyalloc
+#endif
+
+#ifdef yyrealloc
+#define cmFortran_yyrealloc_ALREADY_DEFINED
+#else
+#define yyrealloc cmFortran_yyrealloc
+#endif
+
+#ifdef yyfree
+#define cmFortran_yyfree_ALREADY_DEFINED
+#else
+#define yyfree cmFortran_yyfree
+#endif
+
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
@@ -86,10 +293,16 @@ typedef unsigned int flex_uint32_t;
#define UINT32_MAX (4294967295U)
#endif
+#ifndef SIZE_MAX
+#define SIZE_MAX (~(size_t)0)
+#endif
+
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
+/* begin standard C++ headers. */
+
/* TODO: this is always defined, so inline it */
#define yyconst const
@@ -102,12 +315,10 @@ typedef unsigned int flex_uint32_t;
/* Returned upon end-of-file. */
#define YY_NULL 0
-/* Promotes a possibly negative, possibly signed char to an unsigned
- * integer for use as an array index. If the signed char is negative,
- * we want to instead treat it as an 8-bit unsigned char, hence the
- * double cast.
+/* Promotes a possibly negative, possibly signed char to an
+ * integer in range [0..255] for use as an array index.
*/
-#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
+#define YY_SC_TO_UI(c) ((YY_CHAR) (c))
/* An opaque pointer. */
#ifndef YY_TYPEDEF_YY_SCANNER_T
@@ -131,20 +342,16 @@ typedef void* yyscan_t;
* definition of BEGIN.
*/
#define BEGIN yyg->yy_start = 1 + 2 *
-
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START ((yyg->yy_start - 1) / 2)
#define YYSTATE YY_START
-
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
-
/* Special action meaning "start processing a new file". */
-#define YY_NEW_FILE cmFortran_yyrestart(yyin ,yyscanner )
-
+#define YY_NEW_FILE yyrestart( yyin , yyscanner )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
@@ -194,7 +401,6 @@ typedef size_t yy_size_t;
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
-
#define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
#ifndef YY_STRUCT_YY_BUFFER_STATE
@@ -254,7 +460,7 @@ struct yy_buffer_state
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
- * (via cmFortran_yyrestart()), so that the user can continue scanning by
+ * (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
@@ -271,73 +477,67 @@ struct yy_buffer_state
#define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \
? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \
: NULL)
-
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top]
-void cmFortran_yyrestart (FILE *input_file ,yyscan_t yyscanner );
-void cmFortran_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmFortran_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
-void cmFortran_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmFortran_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmFortran_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-void cmFortran_yypop_buffer_state (yyscan_t yyscanner );
+void yyrestart ( FILE *input_file , yyscan_t yyscanner );
+void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size , yyscan_t yyscanner );
+void yy_delete_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yy_flush_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yypush_buffer_state ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+void yypop_buffer_state ( yyscan_t yyscanner );
-static void cmFortran_yyensure_buffer_stack (yyscan_t yyscanner );
-static void cmFortran_yy_load_buffer_state (yyscan_t yyscanner );
-static void cmFortran_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner );
+static void yyensure_buffer_stack ( yyscan_t yyscanner );
+static void yy_load_buffer_state ( yyscan_t yyscanner );
+static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file , yyscan_t yyscanner );
+#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER , yyscanner)
-#define YY_FLUSH_BUFFER cmFortran_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner)
+YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_string ( const char *yy_str , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len , yyscan_t yyscanner );
-YY_BUFFER_STATE cmFortran_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmFortran_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmFortran_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
-
-void *cmFortran_yyalloc (yy_size_t ,yyscan_t yyscanner );
-void *cmFortran_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
-void cmFortran_yyfree (void * ,yyscan_t yyscanner );
-
-#define yy_new_buffer cmFortran_yy_create_buffer
+void *yyalloc ( yy_size_t , yyscan_t yyscanner );
+void *yyrealloc ( void *, yy_size_t , yyscan_t yyscanner );
+void yyfree ( void * , yyscan_t yyscanner );
+#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
- cmFortran_yyensure_buffer_stack (yyscanner); \
+ yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
- cmFortran_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
-
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
- cmFortran_yyensure_buffer_stack (yyscanner); \
+ yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
- cmFortran_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
-
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define cmFortran_yywrap(yyscanner) (/*CONSTCOND*/1)
#define YY_SKIP_YYWRAP
-
-typedef unsigned char YY_CHAR;
+typedef flex_uint8_t YY_CHAR;
typedef int yy_state_type;
#define yytext_ptr yytext_r
-static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
-static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner);
-static int yy_get_next_buffer (yyscan_t yyscanner );
-static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
+static yy_state_type yy_get_previous_state ( yyscan_t yyscanner );
+static yy_state_type yy_try_NUL_trans ( yy_state_type current_state , yyscan_t yyscanner);
+static int yy_get_next_buffer ( yyscan_t yyscanner );
+static void yynoreturn yy_fatal_error ( const char* msg , yyscan_t yyscanner );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
@@ -348,7 +548,6 @@ static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
yyg->yy_hold_char = *yy_cp; \
*yy_cp = '\0'; \
yyg->yy_c_buf_p = yy_cp;
-
#define YY_NUM_RULES 54
#define YY_END_OF_BUFFER 55
/* This struct is not used in this scanner,
@@ -358,7 +557,7 @@ struct yy_trans_info
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
-static yyconst flex_int16_t yy_accept[210] =
+static const flex_int16_t yy_accept[210] =
{ 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
55, 49, 51, 50, 53, 1, 49, 33, 2, 47,
@@ -368,16 +567,16 @@ static yyconst flex_int16_t yy_accept[210] =
0, 0, 33, 33, 34, 36, 39, 49, 46, 46,
46, 46, 46, 46, 0, 52, 46, 0, 0, 0,
12, 0, 0, 0, 0, 0, 0, 49, 0, 11,
- 46, 0, 0, 5, 0, 0, 0, 29, 0, 0,
+ 46, 0, 0, 5, 0, 0, 0, 0, 29, 0,
33, 33, 33, 33, 0, 0, 40, 46, 46, 46,
46, 45, 12, 12, 0, 0, 0, 23, 0, 0,
0, 0, 0, 0, 6, 0, 0, 0, 0, 0,
0, 0, 0, 0, 46, 46, 46, 46, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 30, 31, 0, 0, 0, 0, 0, 0, 46, 46,
+ 0, 30, 31, 0, 0, 0, 0, 0, 46, 46,
46, 46, 0, 24, 25, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 32, 27, 0, 0, 20, 0,
+ 0, 0, 0, 0, 20, 32, 27, 0, 0, 0,
46, 46, 43, 46, 0, 26, 21, 0, 0, 0,
19, 0, 0, 18, 28, 0, 0, 41, 46, 46,
17, 22, 0, 7, 38, 7, 15, 0, 46, 46,
@@ -385,7 +584,7 @@ static yyconst flex_int16_t yy_accept[210] =
14, 16, 42, 44, 0, 0, 0, 13, 0
} ;
-static yyconst YY_CHAR yy_ec[256] =
+static const YY_CHAR yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
1, 1, 4, 1, 1, 1, 1, 1, 1, 1,
@@ -394,13 +593,13 @@ static yyconst YY_CHAR yy_ec[256] =
13, 14, 1, 15, 1, 1, 1, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 17, 18, 19,
20, 21, 22, 1, 23, 24, 25, 26, 27, 28,
- 29, 29, 30, 29, 29, 31, 32, 33, 34, 29,
- 29, 35, 36, 37, 38, 29, 29, 29, 29, 29,
- 1, 39, 1, 1, 40, 1, 23, 24, 41, 42,
+ 24, 24, 29, 24, 24, 30, 31, 32, 33, 24,
+ 24, 34, 35, 36, 37, 24, 24, 24, 24, 24,
+ 1, 38, 1, 1, 39, 1, 23, 40, 41, 42,
- 43, 44, 29, 29, 45, 29, 29, 46, 32, 47,
- 34, 29, 29, 35, 48, 37, 49, 29, 29, 29,
- 29, 29, 1, 1, 1, 1, 1, 1, 1, 1,
+ 43, 44, 24, 24, 45, 24, 24, 46, 31, 47,
+ 33, 24, 24, 34, 48, 36, 49, 24, 24, 24,
+ 24, 24, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
@@ -417,49 +616,49 @@ static yyconst YY_CHAR yy_ec[256] =
1, 1, 1, 1, 1
} ;
-static yyconst YY_CHAR yy_meta[50] =
+static const YY_CHAR yy_meta[50] =
{ 0,
1, 2, 2, 3, 4, 3, 3, 1, 1, 3,
3, 3, 3, 1, 3, 5, 3, 3, 1, 3,
6, 1, 7, 7, 7, 7, 7, 7, 7, 7,
- 7, 7, 7, 7, 7, 7, 7, 7, 1, 5,
+ 7, 7, 7, 7, 7, 7, 7, 1, 5, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7
} ;
-static yyconst flex_uint16_t yy_base[219] =
+static const flex_int16_t yy_base[219] =
{ 0,
- 0, 48, 0, 49, 513, 56, 52, 57, 62, 68,
- 515, 0, 583, 583, 509, 583, 97, 74, 583, 583,
- 583, 583, 491, 583, 423, 421, 0, 19, 40, 392,
- 36, 47, 86, 146, 88, 186, 413, 235, 275, 583,
- 407, 98, 583, 583, 0, 386, 583, 323, 65, 73,
- 81, 74, 127, 146, 583, 583, 583, 108, 0, 89,
- 120, 92, 362, 116, 161, 583, 0, 167, 371, 0,
- 168, 131, 146, 171, 81, 89, 352, 420, 353, 583,
- 0, 349, 178, 196, 175, 197, 188, 208, 196, 197,
- 256, 262, 324, 330, 337, 143, 0, 151, 220, 56,
-
- 305, 0, 336, 139, 225, 315, 305, 322, 318, 163,
- 320, 268, 266, 369, 583, 340, 347, 350, 350, 351,
- 357, 350, 357, 363, 140, 235, 359, 218, 362, 375,
- 379, 380, 381, 385, 384, 404, 405, 243, 235, 213,
- 583, 583, 405, 407, 410, 171, 410, 409, 419, 418,
- 423, 426, 311, 583, 583, 428, 429, 431, 173, 462,
- 435, 166, 145, 438, 583, 583, 441, 444, 583, 433,
- 448, 89, 0, 438, 450, 583, 583, 452, 457, 487,
- 583, 114, 0, 583, 583, 457, 462, 0, 465, 463,
- 583, 583, 468, 583, 583, 583, 583, 470, 471, 474,
-
- 500, 583, 0, 0, 505, 0, 65, 583, 583, 524,
- 531, 537, 540, 547, 554, 561, 568, 575
+ 0, 48, 0, 49, 464, 56, 52, 57, 62, 68,
+ 466, 0, 468, 468, 462, 468, 74, 81, 468, 468,
+ 468, 468, 447, 468, 442, 440, 0, 41, 42, 428,
+ 43, 42, 91, 119, 97, 157, 455, 206, 245, 468,
+ 454, 101, 468, 468, 0, 455, 468, 105, 430, 424,
+ 62, 68, 119, 141, 468, 468, 468, 111, 0, 59,
+ 98, 88, 415, 109, 158, 468, 0, 162, 293, 0,
+ 163, 411, 107, 122, 408, 405, 446, 342, 447, 468,
+ 0, 444, 169, 173, 420, 421, 132, 404, 90, 404,
+ 179, 185, 191, 227, 295, 397, 0, 146, 178, 149,
+
+ 412, 0, 208, 206, 398, 171, 399, 170, 399, 391,
+ 387, 422, 417, 221, 468, 374, 365, 347, 347, 334,
+ 335, 335, 330, 334, 259, 340, 188, 340, 327, 327,
+ 327, 324, 325, 325, 320, 322, 319, 355, 354, 325,
+ 327, 468, 468, 310, 309, 309, 300, 301, 273, 273,
+ 275, 277, 297, 468, 468, 293, 289, 283, 275, 305,
+ 261, 238, 237, 214, 468, 468, 468, 196, 197, 189,
+ 277, 181, 0, 274, 112, 468, 468, 105, 103, 311,
+ 468, 233, 0, 468, 468, 83, 76, 0, 281, 282,
+ 468, 468, 52, 468, 468, 468, 468, 23, 287, 298,
+
+ 327, 468, 0, 0, 329, 0, 31, 468, 468, 381,
+ 388, 394, 397, 404, 411, 418, 425, 432
} ;
-static yyconst flex_int16_t yy_def[219] =
+static const flex_int16_t yy_def[219] =
{ 0,
209, 1, 1, 1, 1, 1, 210, 210, 210, 210,
209, 211, 209, 209, 212, 209, 211, 209, 209, 209,
209, 209, 209, 209, 209, 211, 213, 213, 213, 213,
- 213, 213, 211, 213, 209, 209, 209, 214, 209, 209,
+ 213, 213, 211, 213, 209, 211, 209, 214, 209, 209,
209, 209, 209, 209, 211, 212, 209, 209, 209, 209,
209, 209, 209, 215, 209, 209, 209, 211, 213, 213,
213, 213, 213, 213, 209, 209, 34, 209, 209, 69,
@@ -482,152 +681,126 @@ static yyconst flex_int16_t yy_def[219] =
209, 209, 209, 209, 209, 209, 209, 209
} ;
-static yyconst flex_uint16_t yy_nxt[633] =
+static const flex_int16_t yy_nxt[518] =
{ 0,
12, 13, 14, 13, 13, 15, 16, 12, 17, 18,
19, 20, 21, 12, 22, 12, 23, 24, 12, 25,
- 12, 26, 27, 27, 27, 27, 28, 27, 27, 29,
- 27, 30, 27, 27, 27, 31, 27, 32, 33, 34,
+ 12, 26, 27, 27, 27, 27, 28, 27, 29, 27,
+ 30, 27, 27, 27, 31, 27, 32, 33, 34, 27,
27, 27, 28, 27, 29, 27, 27, 31, 32, 35,
- 35, 60, 35, 35, 41, 36, 36, 35, 37, 41,
- 35, 42, 43, 36, 41, 60, 42, 43, 44, 38,
- 41, 42, 61, 63, 44, 53, 53, 42, 53, 54,
- 39, 39, 64, 55, 63, 208, 61, 65, 66, 68,
- 65, 85, 68, 127, 64, 69, 39, 39, 48, 83,
-
- 84, 48, 83, 86, 127, 87, 90, 85, 88, 95,
- 110, 189, 95, 89, 97, 195, 195, 100, 86, 87,
- 90, 111, 49, 50, 88, 110, 51, 89, 53, 53,
- 97, 53, 54, 100, 52, 111, 55, 96, 49, 50,
- 104, 51, 102, 104, 98, 52, 45, 92, 53, 183,
- 92, 93, 96, 45, 45, 94, 99, 105, 102, 45,
- 98, 67, 65, 66, 45, 65, 45, 45, 68, 104,
- 182, 68, 104, 105, 69, 124, 106, 149, 107, 83,
- 84, 125, 83, 71, 45, 67, 45, 70, 149, 124,
- 70, 106, 107, 45, 45, 136, 125, 114, 108, 45,
-
- 114, 71, 116, 109, 45, 115, 45, 45, 168, 136,
- 179, 72, 73, 119, 108, 74, 75, 109, 116, 168,
- 122, 179, 123, 76, 45, 45, 117, 72, 73, 119,
- 74, 75, 118, 120, 76, 78, 122, 80, 123, 163,
- 121, 117, 78, 78, 118, 164, 126, 162, 78, 120,
- 78, 152, 129, 78, 121, 78, 78, 92, 53, 164,
- 92, 93, 126, 92, 53, 94, 92, 93, 129, 150,
- 139, 94, 138, 78, 78, 79, 79, 80, 79, 79,
+ 35, 208, 35, 35, 41, 36, 36, 35, 37, 41,
+ 35, 42, 43, 36, 41, 202, 42, 43, 44, 38,
+ 41, 42, 60, 61, 44, 48, 64, 42, 48, 63,
+ 39, 39, 53, 53, 97, 53, 54, 60, 61, 64,
+ 55, 63, 65, 66, 201, 65, 39, 39, 68, 49,
+
+ 97, 68, 83, 84, 69, 83, 48, 87, 88, 48,
+ 50, 89, 95, 100, 90, 95, 51, 198, 52, 45,
+ 53, 53, 98, 53, 54, 197, 45, 45, 55, 100,
+ 49, 121, 45, 99, 67, 102, 122, 45, 98, 45,
+ 45, 50, 92, 53, 193, 92, 93, 51, 192, 52,
+ 94, 102, 106, 107, 191, 96, 45, 67, 70, 65,
+ 66, 70, 65, 68, 104, 108, 68, 104, 109, 69,
+ 83, 84, 71, 83, 114, 125, 118, 114, 71, 119,
+ 92, 53, 115, 92, 93, 127, 92, 53, 94, 92,
+ 93, 125, 92, 53, 94, 92, 93, 127, 72, 73,
+
+ 94, 74, 75, 189, 126, 76, 78, 104, 80, 104,
+ 104, 133, 104, 78, 78, 130, 134, 151, 131, 78,
+ 126, 78, 114, 103, 78, 114, 78, 78, 92, 53,
+ 115, 92, 93, 151, 195, 195, 94, 187, 186, 185,
+ 184, 183, 182, 78, 78, 79, 79, 80, 79, 79,
79, 79, 79, 79, 79, 79, 79, 79, 79, 79,
81, 79, 79, 79, 79, 79, 79, 81, 81, 81,
-
81, 81, 81, 81, 81, 81, 81, 81, 81, 81,
- 81, 81, 81, 79, 81, 81, 81, 81, 81, 81,
- 81, 81, 81, 81, 48, 92, 53, 48, 92, 93,
- 132, 92, 53, 94, 92, 93, 128, 104, 95, 94,
- 104, 95, 135, 175, 130, 137, 132, 133, 49, 50,
- 131, 103, 51, 113, 134, 80, 112, 175, 135, 130,
- 52, 137, 131, 133, 49, 50, 96, 51, 134, 140,
- 114, 52, 70, 114, 141, 70, 142, 144, 115, 143,
- 146, 96, 145, 147, 140, 101, 103, 148, 47, 151,
- 141, 153, 142, 144, 143, 146, 72, 73, 145, 147,
-
- 74, 75, 154, 148, 151, 155, 153, 157, 76, 156,
- 158, 82, 72, 73, 159, 74, 75, 77, 154, 76,
- 78, 155, 80, 157, 156, 62, 158, 78, 78, 159,
- 160, 161, 165, 78, 166, 78, 167, 169, 78, 170,
- 78, 78, 58, 57, 171, 172, 160, 161, 165, 173,
- 166, 174, 167, 169, 170, 176, 177, 178, 78, 78,
- 171, 172, 181, 180, 184, 173, 180, 174, 185, 186,
- 187, 176, 177, 178, 188, 190, 191, 103, 181, 192,
- 184, 187, 193, 197, 185, 186, 190, 198, 180, 199,
- 188, 180, 191, 200, 201, 192, 202, 203, 193, 197,
-
- 204, 205, 103, 198, 205, 199, 205, 56, 200, 205,
- 201, 47, 202, 203, 209, 37, 204, 209, 206, 209,
- 209, 209, 209, 206, 40, 40, 40, 40, 40, 40,
- 40, 45, 209, 209, 209, 45, 45, 46, 46, 46,
- 46, 46, 46, 46, 59, 209, 59, 79, 79, 79,
- 79, 79, 79, 79, 91, 91, 91, 91, 91, 91,
- 91, 194, 194, 194, 209, 194, 194, 194, 196, 209,
- 196, 209, 196, 196, 196, 207, 207, 207, 207, 207,
- 209, 207, 11, 209, 209, 209, 209, 209, 209, 209,
+ 81, 81, 79, 81, 81, 81, 81, 81, 81, 81,
+ 81, 81, 81, 81, 70, 149, 95, 70, 171, 95,
+
+ 172, 173, 174, 188, 181, 199, 180, 149, 103, 180,
+ 190, 200, 180, 203, 171, 180, 172, 173, 174, 188,
+ 103, 199, 190, 179, 204, 178, 103, 200, 205, 203,
+ 205, 205, 177, 205, 72, 73, 176, 74, 75, 96,
+ 204, 76, 78, 175, 80, 206, 170, 206, 169, 78,
+ 78, 168, 167, 166, 165, 78, 164, 78, 163, 162,
+ 78, 161, 78, 78, 160, 159, 158, 157, 156, 155,
+ 154, 153, 152, 150, 148, 147, 146, 145, 144, 78,
+ 78, 40, 40, 40, 40, 40, 40, 40, 45, 143,
+ 142, 141, 45, 45, 46, 46, 46, 46, 46, 46,
+
+ 46, 59, 140, 59, 79, 79, 79, 79, 79, 79,
+ 79, 91, 91, 91, 91, 91, 91, 91, 194, 194,
+ 194, 139, 194, 194, 194, 196, 138, 196, 137, 196,
+ 196, 196, 207, 207, 207, 207, 207, 136, 207, 135,
+ 132, 129, 128, 124, 123, 120, 117, 116, 113, 80,
+ 112, 111, 110, 105, 101, 86, 85, 47, 82, 77,
+ 62, 58, 57, 56, 47, 209, 37, 11, 209, 209,
209, 209, 209, 209, 209, 209, 209, 209, 209, 209,
-
209, 209, 209, 209, 209, 209, 209, 209, 209, 209,
209, 209, 209, 209, 209, 209, 209, 209, 209, 209,
+
209, 209, 209, 209, 209, 209, 209, 209, 209, 209,
- 209, 209
+ 209, 209, 209, 209, 209, 209, 209
} ;
-static yyconst flex_int16_t yy_chk[633] =
+static const flex_int16_t yy_chk[518] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
- 4, 28, 2, 4, 7, 2, 4, 6, 6, 8,
- 6, 7, 7, 6, 9, 28, 8, 8, 9, 6,
- 10, 9, 29, 31, 10, 18, 18, 10, 18, 18,
- 6, 6, 32, 18, 31, 207, 29, 33, 33, 35,
- 33, 49, 35, 100, 32, 35, 6, 6, 17, 42,
-
- 42, 17, 42, 50, 100, 50, 52, 49, 51, 58,
- 75, 172, 58, 51, 60, 182, 182, 62, 50, 50,
- 52, 76, 17, 17, 51, 75, 17, 51, 53, 53,
- 60, 53, 53, 62, 17, 76, 53, 58, 17, 17,
- 104, 17, 64, 104, 61, 17, 34, 54, 54, 163,
- 54, 54, 58, 34, 34, 54, 61, 72, 64, 34,
- 61, 34, 65, 65, 34, 65, 34, 34, 68, 71,
- 162, 68, 71, 72, 68, 96, 73, 125, 73, 83,
- 83, 98, 83, 71, 34, 34, 36, 36, 125, 96,
- 36, 73, 73, 36, 36, 110, 98, 84, 74, 36,
-
- 84, 36, 85, 74, 36, 84, 36, 36, 146, 110,
- 159, 36, 36, 87, 74, 36, 36, 74, 85, 146,
- 89, 159, 90, 36, 36, 36, 86, 36, 36, 87,
- 36, 36, 86, 88, 36, 38, 89, 38, 90, 139,
- 88, 86, 38, 38, 86, 140, 99, 138, 38, 88,
- 38, 128, 105, 38, 88, 38, 38, 91, 91, 140,
- 91, 91, 99, 92, 92, 91, 92, 92, 105, 126,
- 113, 92, 112, 38, 38, 39, 39, 39, 39, 39,
+ 4, 207, 2, 4, 7, 2, 4, 6, 6, 8,
+ 6, 7, 7, 6, 9, 198, 8, 8, 9, 6,
+ 10, 9, 28, 29, 10, 17, 32, 10, 17, 31,
+ 6, 6, 18, 18, 60, 18, 18, 28, 29, 32,
+ 18, 31, 33, 33, 193, 33, 6, 6, 35, 17,
+
+ 60, 35, 42, 42, 35, 42, 48, 51, 51, 48,
+ 17, 52, 58, 62, 52, 58, 17, 187, 17, 34,
+ 53, 53, 61, 53, 53, 186, 34, 34, 53, 62,
+ 48, 89, 34, 61, 34, 64, 89, 34, 61, 34,
+ 34, 48, 54, 54, 179, 54, 54, 48, 178, 48,
+ 54, 64, 73, 73, 175, 58, 34, 34, 36, 65,
+ 65, 36, 65, 68, 71, 74, 68, 71, 74, 68,
+ 83, 83, 36, 83, 84, 98, 87, 84, 71, 87,
+ 91, 91, 84, 91, 91, 100, 92, 92, 91, 92,
+ 92, 98, 93, 93, 92, 93, 93, 100, 36, 36,
+
+ 93, 36, 36, 172, 99, 36, 38, 104, 38, 103,
+ 104, 108, 103, 38, 38, 106, 108, 127, 106, 38,
+ 99, 38, 114, 103, 38, 114, 38, 38, 94, 94,
+ 114, 94, 94, 127, 182, 182, 94, 170, 169, 168,
+ 164, 163, 162, 38, 38, 39, 39, 39, 39, 39,
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
-
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
39, 39, 39, 39, 39, 39, 39, 39, 39, 39,
- 39, 39, 39, 39, 48, 93, 93, 48, 93, 93,
- 107, 94, 94, 93, 94, 94, 101, 103, 95, 94,
- 103, 95, 109, 153, 106, 111, 107, 108, 48, 48,
- 106, 103, 48, 82, 108, 79, 77, 153, 109, 106,
- 48, 111, 106, 108, 48, 48, 95, 48, 108, 116,
- 114, 48, 69, 114, 117, 69, 118, 120, 114, 119,
- 122, 95, 121, 123, 116, 63, 69, 124, 46, 127,
- 117, 129, 118, 120, 119, 122, 69, 69, 121, 123,
-
- 69, 69, 130, 124, 127, 131, 129, 133, 69, 132,
- 134, 41, 69, 69, 135, 69, 69, 37, 130, 69,
- 78, 131, 78, 133, 132, 30, 134, 78, 78, 135,
- 136, 137, 143, 78, 144, 78, 145, 147, 78, 148,
- 78, 78, 26, 25, 149, 150, 136, 137, 143, 151,
- 144, 152, 145, 147, 148, 156, 157, 158, 78, 78,
- 149, 150, 161, 160, 164, 151, 160, 152, 167, 168,
- 170, 156, 157, 158, 171, 174, 175, 160, 161, 178,
- 164, 170, 179, 186, 167, 168, 174, 187, 180, 189,
- 171, 180, 175, 190, 193, 178, 198, 199, 179, 186,
-
- 200, 201, 180, 187, 201, 189, 205, 23, 190, 205,
- 193, 15, 198, 199, 11, 5, 200, 0, 201, 0,
- 0, 0, 0, 205, 210, 210, 210, 210, 210, 210,
- 210, 211, 0, 0, 0, 211, 211, 212, 212, 212,
- 212, 212, 212, 212, 213, 0, 213, 214, 214, 214,
- 214, 214, 214, 214, 215, 215, 215, 215, 215, 215,
- 215, 216, 216, 216, 0, 216, 216, 216, 217, 0,
- 217, 0, 217, 217, 217, 218, 218, 218, 218, 218,
- 0, 218, 209, 209, 209, 209, 209, 209, 209, 209,
+ 39, 39, 39, 39, 69, 125, 95, 69, 149, 95,
+
+ 150, 151, 152, 171, 161, 189, 160, 125, 69, 160,
+ 174, 190, 180, 199, 149, 180, 150, 151, 152, 171,
+ 160, 189, 174, 159, 200, 158, 180, 190, 201, 199,
+ 205, 201, 157, 205, 69, 69, 156, 69, 69, 95,
+ 200, 69, 78, 153, 78, 201, 148, 205, 147, 78,
+ 78, 146, 145, 144, 141, 78, 140, 78, 139, 138,
+ 78, 137, 78, 78, 136, 135, 134, 133, 132, 131,
+ 130, 129, 128, 126, 124, 123, 122, 121, 120, 78,
+ 78, 210, 210, 210, 210, 210, 210, 210, 211, 119,
+ 118, 117, 211, 211, 212, 212, 212, 212, 212, 212,
+
+ 212, 213, 116, 213, 214, 214, 214, 214, 214, 214,
+ 214, 215, 215, 215, 215, 215, 215, 215, 216, 216,
+ 216, 113, 216, 216, 216, 217, 112, 217, 111, 217,
+ 217, 217, 218, 218, 218, 218, 218, 110, 218, 109,
+ 107, 105, 101, 96, 90, 88, 86, 85, 82, 79,
+ 77, 76, 75, 72, 63, 50, 49, 46, 41, 37,
+ 30, 26, 25, 23, 15, 11, 5, 209, 209, 209,
209, 209, 209, 209, 209, 209, 209, 209, 209, 209,
-
209, 209, 209, 209, 209, 209, 209, 209, 209, 209,
209, 209, 209, 209, 209, 209, 209, 209, 209, 209,
+
209, 209, 209, 209, 209, 209, 209, 209, 209, 209,
- 209, 209
+ 209, 209, 209, 209, 209, 209, 209
} ;
/* The intent behind this definition is that it'll catch
@@ -637,8 +810,6 @@ static yyconst flex_int16_t yy_chk[633] =
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
-#line 1 "cmFortranLexer.in.l"
-#line 2 "cmFortranLexer.in.l"
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
/*-------------------------------------------------------------------------
@@ -657,14 +828,12 @@ This file must be translated to C++ and modified to build everywhere.
Run flex >= 2.6 like this:
- flex -i --nounistd -DFLEXINT_H --prefix=cmFortran_yy --header-file=cmFortranLexer.h -ocmFortranLexer.cxx cmFortranLexer.in.l
+ flex -i --nounistd -DFLEXINT_H --noline --header-file=cmFortranLexer.h -ocmFortranLexer.cxx cmFortranLexer.in.l
Modify cmFortranLexer.cxx:
- - remove trailing whitespace: sed -i 's/\s*$//' cmFortranLexer.h cmFortranLexer.cxx
- - remove blank lines at end of file
- - #include "cmStandardLexer.h" at the top
- - add cast in cmFortran_yy_scan_bytes for loop condition of _yybytes_len to size_t
-
+ - remove trailing whitespace: sed -i 's/\s*$//' cmFortranLexer.h cmFortranLexer.cxx
+ - remove blank lines at end of file: sed -i '${/^$/d;}' cmFortranLexer.h cmFortranLexer.cxx
+ - #include "cmStandardLexer.h" at the top: sed -i '1i#include "cmStandardLexer.h"' cmFortranLexer.cxx
*/
/* IWYU pragma: no_forward_declare yyguts_t */
@@ -684,9 +853,6 @@ Modify cmFortranLexer.cxx:
/*--------------------------------------------------------------------------*/
-
-#line 688 "cmFortranLexer.cxx"
-
#define INITIAL 0
#define free_fmt 1
#define fixed_fmt 2
@@ -731,44 +897,44 @@ struct yyguts_t
}; /* end struct yyguts_t */
-static int yy_init_globals (yyscan_t yyscanner );
+static int yy_init_globals ( yyscan_t yyscanner );
-int cmFortran_yylex_init (yyscan_t* scanner);
+int yylex_init (yyscan_t* scanner);
-int cmFortran_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
-int cmFortran_yylex_destroy (yyscan_t yyscanner );
+int yylex_destroy ( yyscan_t yyscanner );
-int cmFortran_yyget_debug (yyscan_t yyscanner );
+int yyget_debug ( yyscan_t yyscanner );
-void cmFortran_yyset_debug (int debug_flag ,yyscan_t yyscanner );
+void yyset_debug ( int debug_flag , yyscan_t yyscanner );
-YY_EXTRA_TYPE cmFortran_yyget_extra (yyscan_t yyscanner );
+YY_EXTRA_TYPE yyget_extra ( yyscan_t yyscanner );
-void cmFortran_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
+void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t yyscanner );
-FILE *cmFortran_yyget_in (yyscan_t yyscanner );
+FILE *yyget_in ( yyscan_t yyscanner );
-void cmFortran_yyset_in (FILE * _in_str ,yyscan_t yyscanner );
+void yyset_in ( FILE * _in_str , yyscan_t yyscanner );
-FILE *cmFortran_yyget_out (yyscan_t yyscanner );
+FILE *yyget_out ( yyscan_t yyscanner );
-void cmFortran_yyset_out (FILE * _out_str ,yyscan_t yyscanner );
+void yyset_out ( FILE * _out_str , yyscan_t yyscanner );
- int cmFortran_yyget_leng (yyscan_t yyscanner );
+ int yyget_leng ( yyscan_t yyscanner );
-char *cmFortran_yyget_text (yyscan_t yyscanner );
+char *yyget_text ( yyscan_t yyscanner );
-int cmFortran_yyget_lineno (yyscan_t yyscanner );
+int yyget_lineno ( yyscan_t yyscanner );
-void cmFortran_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+void yyset_lineno ( int _line_number , yyscan_t yyscanner );
-int cmFortran_yyget_column (yyscan_t yyscanner );
+int yyget_column ( yyscan_t yyscanner );
-void cmFortran_yyset_column (int _column_no ,yyscan_t yyscanner );
+void yyset_column ( int _column_no , yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
@@ -776,32 +942,31 @@ void cmFortran_yyset_column (int _column_no ,yyscan_t yyscanner );
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
-extern "C" int cmFortran_yywrap (yyscan_t yyscanner );
+extern "C" int yywrap ( yyscan_t yyscanner );
#else
-extern int cmFortran_yywrap (yyscan_t yyscanner );
+extern int yywrap ( yyscan_t yyscanner );
#endif
#endif
#ifndef YY_NO_UNPUT
- static void yyunput (int c,char *buf_ptr ,yyscan_t yyscanner);
+ static void yyunput ( int c, char *buf_ptr , yyscan_t yyscanner);
#endif
#ifndef yytext_ptr
-static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
+static void yy_flex_strncpy ( char *, const char *, int , yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
+static int yy_flex_strlen ( const char * , yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
-
#ifdef __cplusplus
-static int yyinput (yyscan_t yyscanner );
+static int yyinput ( yyscan_t yyscanner );
#else
-static int input (yyscan_t yyscanner );
+static int input ( yyscan_t yyscanner );
#endif
#endif
@@ -832,7 +997,7 @@ static int input (yyscan_t yyscanner );
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
- size_t n; \
+ int n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
@@ -845,7 +1010,7 @@ static int input (yyscan_t yyscanner );
else \
{ \
errno=0; \
- while ( (result = (int) fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+ while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
@@ -886,9 +1051,9 @@ static int input (yyscan_t yyscanner );
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
-extern int cmFortran_yylex (yyscan_t yyscanner);
+extern int yylex (yyscan_t yyscanner);
-#define YY_DECL int cmFortran_yylex (yyscan_t yyscanner)
+#define YY_DECL int yylex (yyscan_t yyscanner)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
@@ -936,19 +1101,15 @@ YY_DECL
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
- cmFortran_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
- cmFortran_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner);
}
- cmFortran_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
}
{
-#line 56 "cmFortranLexer.in.l"
-
-
-#line 951 "cmFortranLexer.cxx"
while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */
{
@@ -977,12 +1138,12 @@ yy_match:
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 210 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
++yy_cp;
}
- while ( yy_base[yy_current_state] != 583 );
+ while ( yy_base[yy_current_state] != 468 );
yy_find_action:
yy_act = yy_accept[yy_current_state];
@@ -1008,7 +1169,6 @@ do_action: /* This label is used only to access EOF actions. */
case 1:
YY_RULE_SETUP
-#line 58 "cmFortranLexer.in.l"
{
cmFortranParser_StringStart(yyextra);
cmFortranParser_SetOldStartcond(yyextra, YY_START);
@@ -1017,7 +1177,6 @@ YY_RULE_SETUP
YY_BREAK
case 2:
YY_RULE_SETUP
-#line 64 "cmFortranLexer.in.l"
{
cmFortranParser_StringStart(yyextra);
cmFortranParser_SetOldStartcond(yyextra, YY_START);
@@ -1025,10 +1184,8 @@ YY_RULE_SETUP
}
YY_BREAK
case 3:
-#line 71 "cmFortranLexer.in.l"
case 4:
YY_RULE_SETUP
-#line 71 "cmFortranLexer.in.l"
{
BEGIN(cmFortranParser_GetOldStartcond(yyextra) );
yylvalp->string = strdup(cmFortranParser_StringEnd(yyextra));
@@ -1037,17 +1194,14 @@ YY_RULE_SETUP
YY_BREAK
case 5:
/* rule 5 can match eol */
-#line 78 "cmFortranLexer.in.l"
case 6:
/* rule 6 can match eol */
YY_RULE_SETUP
-#line 78 "cmFortranLexer.in.l"
/* Ignore (continued strings, free fmt) */
YY_BREAK
case 7:
/* rule 7 can match eol */
YY_RULE_SETUP
-#line 80 "cmFortranLexer.in.l"
{
if (cmFortranParser_GetOldStartcond(yyextra) == fixed_fmt)
; /* Ignore (cont. strings, fixed fmt) */
@@ -1060,7 +1214,6 @@ YY_RULE_SETUP
case 8:
/* rule 8 can match eol */
YY_RULE_SETUP
-#line 90 "cmFortranLexer.in.l"
{
unput ('\n');
BEGIN(INITIAL);
@@ -1069,7 +1222,6 @@ YY_RULE_SETUP
YY_BREAK
case 9:
YY_RULE_SETUP
-#line 96 "cmFortranLexer.in.l"
{
cmFortranParser_StringAppend(yyextra, yytext[0]);
}
@@ -1077,24 +1229,20 @@ YY_RULE_SETUP
case 10:
/* rule 10 can match eol */
YY_RULE_SETUP
-#line 100 "cmFortranLexer.in.l"
{ return EOSTMT; } /* Treat comments like */
YY_BREAK
case 11:
/* rule 11 can match eol */
YY_RULE_SETUP
-#line 101 "cmFortranLexer.in.l"
{ return EOSTMT; } /* empty lines */
YY_BREAK
case 12:
YY_RULE_SETUP
-#line 103 "cmFortranLexer.in.l"
{ return CPP_LINE_DIRECTIVE; }
YY_BREAK
case 13:
/* rule 13 can match eol */
YY_RULE_SETUP
-#line 104 "cmFortranLexer.in.l"
{
yytext[yyleng-1] = 0;
yylvalp->string = strdup(strchr(yytext, '<')+1);
@@ -1103,171 +1251,138 @@ YY_RULE_SETUP
YY_BREAK
case 14:
YY_RULE_SETUP
-#line 109 "cmFortranLexer.in.l"
{ return CPP_INCLUDE; }
YY_BREAK
case 15:
YY_RULE_SETUP
-#line 110 "cmFortranLexer.in.l"
{ return F90PPR_INCLUDE; }
YY_BREAK
case 16:
YY_RULE_SETUP
-#line 111 "cmFortranLexer.in.l"
{ return COCO_INCLUDE; }
YY_BREAK
case 17:
YY_RULE_SETUP
-#line 113 "cmFortranLexer.in.l"
{ return CPP_DEFINE; }
YY_BREAK
case 18:
YY_RULE_SETUP
-#line 114 "cmFortranLexer.in.l"
{ return F90PPR_DEFINE; }
YY_BREAK
case 19:
YY_RULE_SETUP
-#line 116 "cmFortranLexer.in.l"
{ return CPP_UNDEF; }
YY_BREAK
case 20:
YY_RULE_SETUP
-#line 117 "cmFortranLexer.in.l"
{ return F90PPR_UNDEF; }
YY_BREAK
case 21:
YY_RULE_SETUP
-#line 119 "cmFortranLexer.in.l"
{ return CPP_IFDEF; }
YY_BREAK
case 22:
YY_RULE_SETUP
-#line 120 "cmFortranLexer.in.l"
{ return CPP_IFNDEF; }
YY_BREAK
case 23:
YY_RULE_SETUP
-#line 121 "cmFortranLexer.in.l"
{ return CPP_IF; }
YY_BREAK
case 24:
YY_RULE_SETUP
-#line 122 "cmFortranLexer.in.l"
{ return CPP_ELIF; }
YY_BREAK
case 25:
YY_RULE_SETUP
-#line 123 "cmFortranLexer.in.l"
{ return CPP_ELSE; }
YY_BREAK
case 26:
YY_RULE_SETUP
-#line 124 "cmFortranLexer.in.l"
{ return CPP_ENDIF; }
YY_BREAK
case 27:
YY_RULE_SETUP
-#line 126 "cmFortranLexer.in.l"
{ return F90PPR_IFDEF; }
YY_BREAK
case 28:
YY_RULE_SETUP
-#line 127 "cmFortranLexer.in.l"
{ return F90PPR_IFNDEF; }
YY_BREAK
case 29:
YY_RULE_SETUP
-#line 128 "cmFortranLexer.in.l"
{ return F90PPR_IF; }
YY_BREAK
case 30:
YY_RULE_SETUP
-#line 129 "cmFortranLexer.in.l"
{ return F90PPR_ELIF; }
YY_BREAK
case 31:
YY_RULE_SETUP
-#line 130 "cmFortranLexer.in.l"
{ return F90PPR_ELSE; }
YY_BREAK
case 32:
YY_RULE_SETUP
-#line 131 "cmFortranLexer.in.l"
{ return F90PPR_ENDIF; }
YY_BREAK
/* Line continuations, possible involving comments. */
case 33:
/* rule 33 can match eol */
YY_RULE_SETUP
-#line 134 "cmFortranLexer.in.l"
YY_BREAK
case 34:
/* rule 34 can match eol */
YY_RULE_SETUP
-#line 135 "cmFortranLexer.in.l"
YY_BREAK
case 35:
YY_RULE_SETUP
-#line 137 "cmFortranLexer.in.l"
{ return COMMA; }
YY_BREAK
case 36:
YY_RULE_SETUP
-#line 139 "cmFortranLexer.in.l"
{ return DCOLON; }
YY_BREAK
case 37:
YY_RULE_SETUP
-#line 140 "cmFortranLexer.in.l"
{ return COLON; }
YY_BREAK
case 38:
/* rule 38 can match eol */
YY_RULE_SETUP
-#line 142 "cmFortranLexer.in.l"
{ return GARBAGE; }
YY_BREAK
case 39:
YY_RULE_SETUP
-#line 144 "cmFortranLexer.in.l"
{ return ASSIGNMENT_OP; }
YY_BREAK
case 40:
YY_RULE_SETUP
-#line 146 "cmFortranLexer.in.l"
{ return END; }
YY_BREAK
case 41:
YY_RULE_SETUP
-#line 147 "cmFortranLexer.in.l"
{ return INCLUDE; }
YY_BREAK
case 42:
YY_RULE_SETUP
-#line 148 "cmFortranLexer.in.l"
{ return INTERFACE; }
YY_BREAK
case 43:
YY_RULE_SETUP
-#line 149 "cmFortranLexer.in.l"
{ return MODULE; }
YY_BREAK
case 44:
YY_RULE_SETUP
-#line 150 "cmFortranLexer.in.l"
{ return SUBMODULE; }
YY_BREAK
case 45:
YY_RULE_SETUP
-#line 151 "cmFortranLexer.in.l"
{ return USE; }
YY_BREAK
case 46:
YY_RULE_SETUP
-#line 153 "cmFortranLexer.in.l"
{
yylvalp->string = strdup(yytext);
return WORD;
@@ -1275,39 +1390,32 @@ YY_RULE_SETUP
YY_BREAK
case 47:
YY_RULE_SETUP
-#line 158 "cmFortranLexer.in.l"
{ return LPAREN; }
YY_BREAK
case 48:
YY_RULE_SETUP
-#line 159 "cmFortranLexer.in.l"
{ return RPAREN; }
YY_BREAK
case 49:
YY_RULE_SETUP
-#line 161 "cmFortranLexer.in.l"
{ return GARBAGE; }
YY_BREAK
case 50:
/* rule 50 can match eol */
YY_RULE_SETUP
-#line 163 "cmFortranLexer.in.l"
{ return EOSTMT; }
YY_BREAK
case 51:
YY_RULE_SETUP
-#line 166 "cmFortranLexer.in.l"
/* Ignore */
YY_BREAK
case 52:
/* rule 52 can match eol */
YY_RULE_SETUP
-#line 167 "cmFortranLexer.in.l"
/* Ignore line-endings preceded by \ */
YY_BREAK
case 53:
YY_RULE_SETUP
-#line 169 "cmFortranLexer.in.l"
{ return *yytext; }
YY_BREAK
case YY_STATE_EOF(INITIAL):
@@ -1315,7 +1423,6 @@ case YY_STATE_EOF(free_fmt):
case YY_STATE_EOF(fixed_fmt):
case YY_STATE_EOF(str_sq):
case YY_STATE_EOF(str_dq):
-#line 171 "cmFortranLexer.in.l"
{
if(!cmFortranParser_FilePop(yyextra) )
{
@@ -1325,10 +1432,8 @@ case YY_STATE_EOF(str_dq):
YY_BREAK
case 54:
YY_RULE_SETUP
-#line 178 "cmFortranLexer.in.l"
ECHO;
YY_BREAK
-#line 1331 "cmFortranLexer.cxx"
case YY_END_OF_BUFFER:
{
@@ -1344,7 +1449,7 @@ ECHO;
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
- * cmFortran_yylex(). If so, then we have to assure
+ * yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
@@ -1404,7 +1509,7 @@ ECHO;
{
yyg->yy_did_buffer_switch_on_eof = 0;
- if ( cmFortran_yywrap(yyscanner ) )
+ if ( yywrap( yyscanner ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
@@ -1458,7 +1563,7 @@ ECHO;
} /* end of action switch */
} /* end of scanning one token */
} /* end of user's declarations */
-} /* end of cmFortran_yylex */
+} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
@@ -1472,7 +1577,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
char *source = yyg->yytext_ptr;
- yy_size_t number_to_move, i;
+ int number_to_move, i;
int ret_val;
if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
@@ -1501,7 +1606,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
/* Try to read more data. */
/* First move last chars to start of buffer. */
- number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
+ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr - 1);
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
@@ -1537,7 +1642,8 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
- cmFortran_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
+ yyrealloc( (void *) b->yy_ch_buf,
+ (yy_size_t) (b->yy_buf_size + 2) , yyscanner );
}
else
/* Can't grow it, we don't own it. */
@@ -1569,7 +1675,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
- cmFortran_yyrestart(yyin ,yyscanner);
+ yyrestart( yyin , yyscanner);
}
else
@@ -1583,12 +1689,15 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
else
ret_val = EOB_ACT_CONTINUE_SCAN;
- if ((int) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
+ if ((yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
- YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) cmFortran_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
+ YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc(
+ (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size , yyscanner );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+ /* "- 2" to take care of EOB's */
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2);
}
yyg->yy_n_chars += number_to_move;
@@ -1623,9 +1732,9 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 210 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
}
return yy_current_state;
@@ -1652,9 +1761,9 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
{
yy_current_state = (int) yy_def[yy_current_state];
if ( yy_current_state >= 210 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
yy_is_jam = (yy_current_state == 209);
(void)yyg;
@@ -1728,7 +1837,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
else
{ /* need more input */
- int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
+ int offset = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr);
++yyg->yy_c_buf_p;
switch ( yy_get_next_buffer( yyscanner ) )
@@ -1745,13 +1854,13 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
*/
/* Reset buffer status. */
- cmFortran_yyrestart(yyin ,yyscanner);
+ yyrestart( yyin , yyscanner);
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
- if ( cmFortran_yywrap(yyscanner ) )
+ if ( yywrap( yyscanner ) )
return 0;
if ( ! yyg->yy_did_buffer_switch_on_eof )
@@ -1785,34 +1894,34 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @note This function does not reset the start condition to @c INITIAL .
*/
- void cmFortran_yyrestart (FILE * input_file , yyscan_t yyscanner)
+ void yyrestart (FILE * input_file , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! YY_CURRENT_BUFFER ){
- cmFortran_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
- cmFortran_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner);
}
- cmFortran_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
- cmFortran_yy_load_buffer_state(yyscanner );
+ yy_init_buffer( YY_CURRENT_BUFFER, input_file , yyscanner);
+ yy_load_buffer_state( yyscanner );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
* @param yyscanner The scanner object.
*/
- void cmFortran_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
+ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* TODO. We should be able to replace this entire function body
* with
- * cmFortran_yypop_buffer_state();
- * cmFortran_yypush_buffer_state(new_buffer);
+ * yypop_buffer_state();
+ * yypush_buffer_state(new_buffer);
*/
- cmFortran_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
if ( YY_CURRENT_BUFFER == new_buffer )
return;
@@ -1825,17 +1934,17 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
- cmFortran_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
/* We don't actually know whether we did this switch during
- * EOF (cmFortran_yywrap()) processing, but the only time this flag
- * is looked at is after cmFortran_yywrap() is called, so it's safe
+ * EOF (yywrap()) processing, but the only time this flag
+ * is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
yyg->yy_did_buffer_switch_on_eof = 1;
}
-static void cmFortran_yy_load_buffer_state (yyscan_t yyscanner)
+static void yy_load_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
@@ -1850,35 +1959,35 @@ static void cmFortran_yy_load_buffer_state (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @return the allocated buffer state.
*/
- YY_BUFFER_STATE cmFortran_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
+ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
- b = (YY_BUFFER_STATE) cmFortran_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+ b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner );
if ( ! b )
- YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yy_create_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
- b->yy_buf_size = (yy_size_t)size;
+ b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
- b->yy_ch_buf = (char *) cmFortran_yyalloc(b->yy_buf_size + 2 ,yyscanner );
+ b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) , yyscanner );
if ( ! b->yy_ch_buf )
- YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yy_create_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
- cmFortran_yy_init_buffer(b,file ,yyscanner);
+ yy_init_buffer( b, file , yyscanner);
return b;
}
/** Destroy the buffer.
- * @param b a buffer created with cmFortran_yy_create_buffer()
+ * @param b a buffer created with yy_create_buffer()
* @param yyscanner The scanner object.
*/
- void cmFortran_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
+ void yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -1889,28 +1998,28 @@ static void cmFortran_yy_load_buffer_state (yyscan_t yyscanner)
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
- cmFortran_yyfree((void *) b->yy_ch_buf ,yyscanner );
+ yyfree( (void *) b->yy_ch_buf , yyscanner );
- cmFortran_yyfree((void *) b ,yyscanner );
+ yyfree( (void *) b , yyscanner );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
- * such as during a cmFortran_yyrestart() or at EOF.
+ * such as during a yyrestart() or at EOF.
*/
- static void cmFortran_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
+ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
{
int oerrno = errno;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
- cmFortran_yy_flush_buffer(b ,yyscanner);
+ yy_flush_buffer( b , yyscanner);
b->yy_input_file = file;
b->yy_fill_buffer = 1;
- /* If b is the current buffer, then cmFortran_yy_init_buffer was _probably_
- * called from cmFortran_yyrestart() or through yy_get_next_buffer.
+ /* If b is the current buffer, then yy_init_buffer was _probably_
+ * called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
@@ -1927,7 +2036,7 @@ static void cmFortran_yy_load_buffer_state (yyscan_t yyscanner)
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
* @param yyscanner The scanner object.
*/
- void cmFortran_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
+ void yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
@@ -1948,7 +2057,7 @@ static void cmFortran_yy_load_buffer_state (yyscan_t yyscanner)
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
- cmFortran_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
}
/** Pushes the new state onto the stack. The new state becomes
@@ -1957,15 +2066,15 @@ static void cmFortran_yy_load_buffer_state (yyscan_t yyscanner)
* @param new_buffer The new state.
* @param yyscanner The scanner object.
*/
-void cmFortran_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
+void yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (new_buffer == NULL)
return;
- cmFortran_yyensure_buffer_stack(yyscanner);
+ yyensure_buffer_stack(yyscanner);
- /* This block is copied from cmFortran_yy_switch_to_buffer. */
+ /* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
@@ -1979,8 +2088,8 @@ void cmFortran_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscan
yyg->yy_buffer_stack_top++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
- /* copied from cmFortran_yy_switch_to_buffer. */
- cmFortran_yy_load_buffer_state(yyscanner );
+ /* copied from yy_switch_to_buffer. */
+ yy_load_buffer_state( yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
@@ -1988,19 +2097,19 @@ void cmFortran_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscan
* The next element becomes the new top.
* @param yyscanner The scanner object.
*/
-void cmFortran_yypop_buffer_state (yyscan_t yyscanner)
+void yypop_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER)
return;
- cmFortran_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
+ yy_delete_buffer(YY_CURRENT_BUFFER , yyscanner);
YY_CURRENT_BUFFER_LVALUE = NULL;
if (yyg->yy_buffer_stack_top > 0)
--yyg->yy_buffer_stack_top;
if (YY_CURRENT_BUFFER) {
- cmFortran_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
}
@@ -2008,9 +2117,9 @@ void cmFortran_yypop_buffer_state (yyscan_t yyscanner)
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
-static void cmFortran_yyensure_buffer_stack (yyscan_t yyscanner)
+static void yyensure_buffer_stack (yyscan_t yyscanner)
{
- int num_to_alloc;
+ yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
@@ -2020,11 +2129,11 @@ static void cmFortran_yyensure_buffer_stack (yyscan_t yyscanner)
* immediate realloc on the next call.
*/
num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
- yyg->yy_buffer_stack = (struct yy_buffer_state**)cmFortran_yyalloc
+ yyg->yy_buffer_stack = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
- YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yyensure_buffer_stack()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
@@ -2039,12 +2148,12 @@ static void cmFortran_yyensure_buffer_stack (yyscan_t yyscanner)
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
- yyg->yy_buffer_stack = (struct yy_buffer_state**)cmFortran_yyrealloc
+ yyg->yy_buffer_stack = (struct yy_buffer_state**)yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
- YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yyensure_buffer_stack()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
@@ -2058,7 +2167,7 @@ static void cmFortran_yyensure_buffer_stack (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
-YY_BUFFER_STATE cmFortran_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
@@ -2068,11 +2177,11 @@ YY_BUFFER_STATE cmFortran_yy_scan_buffer (char * base, yy_size_t size , yyscan
/* They forgot to leave room for the EOB's. */
return NULL;
- b = (YY_BUFFER_STATE) cmFortran_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+ b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner );
if ( ! b )
- YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yy_scan_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
- b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
+ b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = NULL;
@@ -2082,53 +2191,53 @@ YY_BUFFER_STATE cmFortran_yy_scan_buffer (char * base, yy_size_t size , yyscan
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
- cmFortran_yy_switch_to_buffer(b ,yyscanner );
+ yy_switch_to_buffer( b , yyscanner );
return b;
}
-/** Setup the input buffer state to scan a string. The next call to cmFortran_yylex() will
+/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
- * cmFortran_yy_scan_bytes() instead.
+ * yy_scan_bytes() instead.
*/
-YY_BUFFER_STATE cmFortran_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_string (const char * yystr , yyscan_t yyscanner)
{
- return cmFortran_yy_scan_bytes(yystr,(int) strlen(yystr) ,yyscanner);
+ return yy_scan_bytes( yystr, (int) strlen(yystr) , yyscanner);
}
-/** Setup the input buffer state to scan the given bytes. The next call to cmFortran_yylex() will
+/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
-YY_BUFFER_STATE cmFortran_yy_scan_bytes (yyconst char * yybytes, int _yybytes_len , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
- yy_size_t i;
+ int i;
/* Get memory for full buffer, including space for trailing EOB's. */
- n = (yy_size_t) _yybytes_len + 2;
- buf = (char *) cmFortran_yyalloc(n ,yyscanner );
+ n = (yy_size_t) (_yybytes_len + 2);
+ buf = (char *) yyalloc( n , yyscanner );
if ( ! buf )
- YY_FATAL_ERROR( "out of dynamic memory in cmFortran_yy_scan_bytes()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
- for ( i = 0; i < (size_t)_yybytes_len; ++i )
+ for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
- b = cmFortran_yy_scan_buffer(buf,n ,yyscanner);
+ b = yy_scan_buffer( buf, n , yyscanner);
if ( ! b )
- YY_FATAL_ERROR( "bad buffer in cmFortran_yy_scan_bytes()" );
+ YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
@@ -2142,11 +2251,11 @@ YY_BUFFER_STATE cmFortran_yy_scan_bytes (yyconst char * yybytes, int _yybytes_
#define YY_EXIT_FAILURE 2
#endif
-static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
+static void yynoreturn yy_fatal_error (const char* msg , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
- (void) fprintf( stderr, "%s\n", msg );
+ fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
@@ -2172,7 +2281,7 @@ static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
/** Get the user-defined data for this scanner.
* @param yyscanner The scanner object.
*/
-YY_EXTRA_TYPE cmFortran_yyget_extra (yyscan_t yyscanner)
+YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyextra;
@@ -2181,7 +2290,7 @@ YY_EXTRA_TYPE cmFortran_yyget_extra (yyscan_t yyscanner)
/** Get the current line number.
* @param yyscanner The scanner object.
*/
-int cmFortran_yyget_lineno (yyscan_t yyscanner)
+int yyget_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -2194,7 +2303,7 @@ int cmFortran_yyget_lineno (yyscan_t yyscanner)
/** Get the current column number.
* @param yyscanner The scanner object.
*/
-int cmFortran_yyget_column (yyscan_t yyscanner)
+int yyget_column (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -2207,7 +2316,7 @@ int cmFortran_yyget_column (yyscan_t yyscanner)
/** Get the input stream.
* @param yyscanner The scanner object.
*/
-FILE *cmFortran_yyget_in (yyscan_t yyscanner)
+FILE *yyget_in (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyin;
@@ -2216,7 +2325,7 @@ FILE *cmFortran_yyget_in (yyscan_t yyscanner)
/** Get the output stream.
* @param yyscanner The scanner object.
*/
-FILE *cmFortran_yyget_out (yyscan_t yyscanner)
+FILE *yyget_out (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyout;
@@ -2225,7 +2334,7 @@ FILE *cmFortran_yyget_out (yyscan_t yyscanner)
/** Get the length of the current token.
* @param yyscanner The scanner object.
*/
-int cmFortran_yyget_leng (yyscan_t yyscanner)
+int yyget_leng (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyleng;
@@ -2235,7 +2344,7 @@ int cmFortran_yyget_leng (yyscan_t yyscanner)
* @param yyscanner The scanner object.
*/
-char *cmFortran_yyget_text (yyscan_t yyscanner)
+char *yyget_text (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yytext;
@@ -2245,7 +2354,7 @@ char *cmFortran_yyget_text (yyscan_t yyscanner)
* @param user_defined The data to be associated with this scanner.
* @param yyscanner The scanner object.
*/
-void cmFortran_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
+void yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyextra = user_defined ;
@@ -2255,13 +2364,13 @@ void cmFortran_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
* @param _line_number line number
* @param yyscanner The scanner object.
*/
-void cmFortran_yyset_lineno (int _line_number , yyscan_t yyscanner)
+void yyset_lineno (int _line_number , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* lineno is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
- YY_FATAL_ERROR( "cmFortran_yyset_lineno called with no buffer" );
+ YY_FATAL_ERROR( "yyset_lineno called with no buffer" );
yylineno = _line_number;
}
@@ -2270,13 +2379,13 @@ void cmFortran_yyset_lineno (int _line_number , yyscan_t yyscanner)
* @param _column_no column number
* @param yyscanner The scanner object.
*/
-void cmFortran_yyset_column (int _column_no , yyscan_t yyscanner)
+void yyset_column (int _column_no , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* column is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
- YY_FATAL_ERROR( "cmFortran_yyset_column called with no buffer" );
+ YY_FATAL_ERROR( "yyset_column called with no buffer" );
yycolumn = _column_no;
}
@@ -2285,27 +2394,27 @@ void cmFortran_yyset_column (int _column_no , yyscan_t yyscanner)
* input buffer.
* @param _in_str A readable stream.
* @param yyscanner The scanner object.
- * @see cmFortran_yy_switch_to_buffer
+ * @see yy_switch_to_buffer
*/
-void cmFortran_yyset_in (FILE * _in_str , yyscan_t yyscanner)
+void yyset_in (FILE * _in_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyin = _in_str ;
}
-void cmFortran_yyset_out (FILE * _out_str , yyscan_t yyscanner)
+void yyset_out (FILE * _out_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyout = _out_str ;
}
-int cmFortran_yyget_debug (yyscan_t yyscanner)
+int yyget_debug (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yy_flex_debug;
}
-void cmFortran_yyset_debug (int _bdebug , yyscan_t yyscanner)
+void yyset_debug (int _bdebug , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_flex_debug = _bdebug ;
@@ -2315,20 +2424,18 @@ void cmFortran_yyset_debug (int _bdebug , yyscan_t yyscanner)
/* User-visible API */
-/* cmFortran_yylex_init is special because it creates the scanner itself, so it is
+/* yylex_init is special because it creates the scanner itself, so it is
* the ONLY reentrant function that doesn't take the scanner as the last argument.
* That's why we explicitly handle the declaration, instead of using our macros.
*/
-
-int cmFortran_yylex_init(yyscan_t* ptr_yy_globals)
-
+int yylex_init(yyscan_t* ptr_yy_globals)
{
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
- *ptr_yy_globals = (yyscan_t) cmFortran_yyalloc ( sizeof( struct yyguts_t ), NULL );
+ *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), NULL );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
@@ -2341,27 +2448,25 @@ int cmFortran_yylex_init(yyscan_t* ptr_yy_globals)
return yy_init_globals ( *ptr_yy_globals );
}
-/* cmFortran_yylex_init_extra has the same functionality as cmFortran_yylex_init, but follows the
+/* yylex_init_extra has the same functionality as yylex_init, but follows the
* convention of taking the scanner as the last argument. Note however, that
* this is a *pointer* to a scanner, as it will be allocated by this call (and
* is the reason, too, why this function also must handle its own declaration).
- * The user defined value in the first argument will be available to cmFortran_yyalloc in
+ * The user defined value in the first argument will be available to yyalloc in
* the yyextra field.
*/
-
-int cmFortran_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )
-
+int yylex_init_extra( YY_EXTRA_TYPE yy_user_defined, yyscan_t* ptr_yy_globals )
{
struct yyguts_t dummy_yyguts;
- cmFortran_yyset_extra (yy_user_defined, &dummy_yyguts);
+ yyset_extra (yy_user_defined, &dummy_yyguts);
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
- *ptr_yy_globals = (yyscan_t) cmFortran_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
+ *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
@@ -2372,7 +2477,7 @@ int cmFortran_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_gl
yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
- cmFortran_yyset_extra (yy_user_defined, *ptr_yy_globals);
+ yyset_extra (yy_user_defined, *ptr_yy_globals);
return yy_init_globals ( *ptr_yy_globals );
}
@@ -2381,7 +2486,7 @@ static int yy_init_globals (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Initialization is the same as for the non-reentrant scanner.
- * This function is called from cmFortran_yylex_destroy(), so don't allocate here.
+ * This function is called from yylex_destroy(), so don't allocate here.
*/
yyg->yy_buffer_stack = NULL;
@@ -2405,37 +2510,37 @@ static int yy_init_globals (yyscan_t yyscanner)
#endif
/* For future reference: Set errno on error, since we are called by
- * cmFortran_yylex_init()
+ * yylex_init()
*/
return 0;
}
-/* cmFortran_yylex_destroy is for both reentrant and non-reentrant scanners. */
-int cmFortran_yylex_destroy (yyscan_t yyscanner)
+/* yylex_destroy is for both reentrant and non-reentrant scanners. */
+int yylex_destroy (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
- cmFortran_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
+ yy_delete_buffer( YY_CURRENT_BUFFER , yyscanner );
YY_CURRENT_BUFFER_LVALUE = NULL;
- cmFortran_yypop_buffer_state(yyscanner);
+ yypop_buffer_state(yyscanner);
}
/* Destroy the stack itself. */
- cmFortran_yyfree(yyg->yy_buffer_stack ,yyscanner);
+ yyfree(yyg->yy_buffer_stack , yyscanner);
yyg->yy_buffer_stack = NULL;
/* Destroy the start condition stack. */
- cmFortran_yyfree(yyg->yy_start_stack ,yyscanner );
+ yyfree( yyg->yy_start_stack , yyscanner );
yyg->yy_start_stack = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
- * cmFortran_yylex() is called, initialization will occur. */
+ * yylex() is called, initialization will occur. */
yy_init_globals( yyscanner);
/* Destroy the main struct (reentrant only). */
- cmFortran_yyfree ( yyscanner , yyscanner );
+ yyfree ( yyscanner , yyscanner );
yyscanner = NULL;
return 0;
}
@@ -2445,7 +2550,7 @@ int cmFortran_yylex_destroy (yyscan_t yyscanner)
*/
#ifndef yytext_ptr
-static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner)
+static void yy_flex_strncpy (char* s1, const char * s2, int n , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
@@ -2457,7 +2562,7 @@ static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yysca
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
+static int yy_flex_strlen (const char * s , yyscan_t yyscanner)
{
int n;
for ( n = 0; s[n]; ++n )
@@ -2467,14 +2572,14 @@ static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
}
#endif
-void *cmFortran_yyalloc (yy_size_t size , yyscan_t yyscanner)
+void *yyalloc (yy_size_t size , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
return malloc(size);
}
-void *cmFortran_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
+void *yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
@@ -2489,19 +2594,15 @@ void *cmFortran_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
return realloc(ptr, size);
}
-void cmFortran_yyfree (void * ptr , yyscan_t yyscanner)
+void yyfree (void * ptr , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
- free( (char *) ptr ); /* see cmFortran_yyrealloc() for (char *) cast */
+ free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
-#line 178 "cmFortranLexer.in.l"
-
-
-
/*--------------------------------------------------------------------------*/
YY_BUFFER_STATE cmFortranLexer_GetCurrentBuffer(yyscan_t yyscanner)
{
diff --git a/Source/LexerParser/cmFortranLexer.h b/Source/LexerParser/cmFortranLexer.h
index ddda91965..7bb9b4434 100644
--- a/Source/LexerParser/cmFortranLexer.h
+++ b/Source/LexerParser/cmFortranLexer.h
@@ -2,10 +2,6 @@
#define cmFortran_yyHEADER_H 1
#define cmFortran_yyIN_HEADER 1
-#line 6 "cmFortranLexer.h"
-
-#line 8 "cmFortranLexer.h"
-
#define FLEXINT_H 1
#define YY_INT_ALIGNED short int
@@ -14,11 +10,221 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
-#define YY_FLEX_SUBMINOR_VERSION 1
+#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
+#ifdef yy_create_buffer
+#define cmFortran_yy_create_buffer_ALREADY_DEFINED
+#else
+#define yy_create_buffer cmFortran_yy_create_buffer
+#endif
+
+#ifdef yy_delete_buffer
+#define cmFortran_yy_delete_buffer_ALREADY_DEFINED
+#else
+#define yy_delete_buffer cmFortran_yy_delete_buffer
+#endif
+
+#ifdef yy_scan_buffer
+#define cmFortran_yy_scan_buffer_ALREADY_DEFINED
+#else
+#define yy_scan_buffer cmFortran_yy_scan_buffer
+#endif
+
+#ifdef yy_scan_string
+#define cmFortran_yy_scan_string_ALREADY_DEFINED
+#else
+#define yy_scan_string cmFortran_yy_scan_string
+#endif
+
+#ifdef yy_scan_bytes
+#define cmFortran_yy_scan_bytes_ALREADY_DEFINED
+#else
+#define yy_scan_bytes cmFortran_yy_scan_bytes
+#endif
+
+#ifdef yy_init_buffer
+#define cmFortran_yy_init_buffer_ALREADY_DEFINED
+#else
+#define yy_init_buffer cmFortran_yy_init_buffer
+#endif
+
+#ifdef yy_flush_buffer
+#define cmFortran_yy_flush_buffer_ALREADY_DEFINED
+#else
+#define yy_flush_buffer cmFortran_yy_flush_buffer
+#endif
+
+#ifdef yy_load_buffer_state
+#define cmFortran_yy_load_buffer_state_ALREADY_DEFINED
+#else
+#define yy_load_buffer_state cmFortran_yy_load_buffer_state
+#endif
+
+#ifdef yy_switch_to_buffer
+#define cmFortran_yy_switch_to_buffer_ALREADY_DEFINED
+#else
+#define yy_switch_to_buffer cmFortran_yy_switch_to_buffer
+#endif
+
+#ifdef yypush_buffer_state
+#define cmFortran_yypush_buffer_state_ALREADY_DEFINED
+#else
+#define yypush_buffer_state cmFortran_yypush_buffer_state
+#endif
+
+#ifdef yypop_buffer_state
+#define cmFortran_yypop_buffer_state_ALREADY_DEFINED
+#else
+#define yypop_buffer_state cmFortran_yypop_buffer_state
+#endif
+
+#ifdef yyensure_buffer_stack
+#define cmFortran_yyensure_buffer_stack_ALREADY_DEFINED
+#else
+#define yyensure_buffer_stack cmFortran_yyensure_buffer_stack
+#endif
+
+#ifdef yylex
+#define cmFortran_yylex_ALREADY_DEFINED
+#else
+#define yylex cmFortran_yylex
+#endif
+
+#ifdef yyrestart
+#define cmFortran_yyrestart_ALREADY_DEFINED
+#else
+#define yyrestart cmFortran_yyrestart
+#endif
+
+#ifdef yylex_init
+#define cmFortran_yylex_init_ALREADY_DEFINED
+#else
+#define yylex_init cmFortran_yylex_init
+#endif
+
+#ifdef yylex_init_extra
+#define cmFortran_yylex_init_extra_ALREADY_DEFINED
+#else
+#define yylex_init_extra cmFortran_yylex_init_extra
+#endif
+
+#ifdef yylex_destroy
+#define cmFortran_yylex_destroy_ALREADY_DEFINED
+#else
+#define yylex_destroy cmFortran_yylex_destroy
+#endif
+
+#ifdef yyget_debug
+#define cmFortran_yyget_debug_ALREADY_DEFINED
+#else
+#define yyget_debug cmFortran_yyget_debug
+#endif
+
+#ifdef yyset_debug
+#define cmFortran_yyset_debug_ALREADY_DEFINED
+#else
+#define yyset_debug cmFortran_yyset_debug
+#endif
+
+#ifdef yyget_extra
+#define cmFortran_yyget_extra_ALREADY_DEFINED
+#else
+#define yyget_extra cmFortran_yyget_extra
+#endif
+
+#ifdef yyset_extra
+#define cmFortran_yyset_extra_ALREADY_DEFINED
+#else
+#define yyset_extra cmFortran_yyset_extra
+#endif
+
+#ifdef yyget_in
+#define cmFortran_yyget_in_ALREADY_DEFINED
+#else
+#define yyget_in cmFortran_yyget_in
+#endif
+
+#ifdef yyset_in
+#define cmFortran_yyset_in_ALREADY_DEFINED
+#else
+#define yyset_in cmFortran_yyset_in
+#endif
+
+#ifdef yyget_out
+#define cmFortran_yyget_out_ALREADY_DEFINED
+#else
+#define yyget_out cmFortran_yyget_out
+#endif
+
+#ifdef yyset_out
+#define cmFortran_yyset_out_ALREADY_DEFINED
+#else
+#define yyset_out cmFortran_yyset_out
+#endif
+
+#ifdef yyget_leng
+#define cmFortran_yyget_leng_ALREADY_DEFINED
+#else
+#define yyget_leng cmFortran_yyget_leng
+#endif
+
+#ifdef yyget_text
+#define cmFortran_yyget_text_ALREADY_DEFINED
+#else
+#define yyget_text cmFortran_yyget_text
+#endif
+
+#ifdef yyget_lineno
+#define cmFortran_yyget_lineno_ALREADY_DEFINED
+#else
+#define yyget_lineno cmFortran_yyget_lineno
+#endif
+
+#ifdef yyset_lineno
+#define cmFortran_yyset_lineno_ALREADY_DEFINED
+#else
+#define yyset_lineno cmFortran_yyset_lineno
+#endif
+
+#ifdef yyget_column
+#define cmFortran_yyget_column_ALREADY_DEFINED
+#else
+#define yyget_column cmFortran_yyget_column
+#endif
+
+#ifdef yyset_column
+#define cmFortran_yyset_column_ALREADY_DEFINED
+#else
+#define yyset_column cmFortran_yyset_column
+#endif
+
+#ifdef yywrap
+#define cmFortran_yywrap_ALREADY_DEFINED
+#else
+#define yywrap cmFortran_yywrap
+#endif
+
+#ifdef yyalloc
+#define cmFortran_yyalloc_ALREADY_DEFINED
+#else
+#define yyalloc cmFortran_yyalloc
+#endif
+
+#ifdef yyrealloc
+#define cmFortran_yyrealloc_ALREADY_DEFINED
+#else
+#define yyrealloc cmFortran_yyrealloc
+#endif
+
+#ifdef yyfree
+#define cmFortran_yyfree_ALREADY_DEFINED
+#else
+#define yyfree cmFortran_yyfree
+#endif
+
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
@@ -89,10 +295,16 @@ typedef unsigned int flex_uint32_t;
#define UINT32_MAX (4294967295U)
#endif
+#ifndef SIZE_MAX
+#define SIZE_MAX (~(size_t)0)
+#endif
+
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
+/* begin standard C++ headers. */
+
/* TODO: this is always defined, so inline it */
#define yyconst const
@@ -193,21 +405,21 @@ struct yy_buffer_state
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
-void cmFortran_yyrestart (FILE *input_file ,yyscan_t yyscanner );
-void cmFortran_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmFortran_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
-void cmFortran_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmFortran_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmFortran_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-void cmFortran_yypop_buffer_state (yyscan_t yyscanner );
+void yyrestart ( FILE *input_file , yyscan_t yyscanner );
+void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size , yyscan_t yyscanner );
+void yy_delete_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yy_flush_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yypush_buffer_state ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+void yypop_buffer_state ( yyscan_t yyscanner );
-YY_BUFFER_STATE cmFortran_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmFortran_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmFortran_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_string ( const char *yy_str , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len , yyscan_t yyscanner );
-void *cmFortran_yyalloc (yy_size_t ,yyscan_t yyscanner );
-void *cmFortran_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
-void cmFortran_yyfree (void * ,yyscan_t yyscanner );
+void *yyalloc ( yy_size_t , yyscan_t yyscanner );
+void *yyrealloc ( void *, yy_size_t , yyscan_t yyscanner );
+void yyfree ( void * , yyscan_t yyscanner );
/* Begin user sect3 */
@@ -229,42 +441,42 @@ void cmFortran_yyfree (void * ,yyscan_t yyscanner );
#define YY_EXTRA_TYPE void *
#endif
-int cmFortran_yylex_init (yyscan_t* scanner);
+int yylex_init (yyscan_t* scanner);
-int cmFortran_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
-int cmFortran_yylex_destroy (yyscan_t yyscanner );
+int yylex_destroy ( yyscan_t yyscanner );
-int cmFortran_yyget_debug (yyscan_t yyscanner );
+int yyget_debug ( yyscan_t yyscanner );
-void cmFortran_yyset_debug (int debug_flag ,yyscan_t yyscanner );
+void yyset_debug ( int debug_flag , yyscan_t yyscanner );
-YY_EXTRA_TYPE cmFortran_yyget_extra (yyscan_t yyscanner );
+YY_EXTRA_TYPE yyget_extra ( yyscan_t yyscanner );
-void cmFortran_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
+void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t yyscanner );
-FILE *cmFortran_yyget_in (yyscan_t yyscanner );
+FILE *yyget_in ( yyscan_t yyscanner );
-void cmFortran_yyset_in (FILE * _in_str ,yyscan_t yyscanner );
+void yyset_in ( FILE * _in_str , yyscan_t yyscanner );
-FILE *cmFortran_yyget_out (yyscan_t yyscanner );
+FILE *yyget_out ( yyscan_t yyscanner );
-void cmFortran_yyset_out (FILE * _out_str ,yyscan_t yyscanner );
+void yyset_out ( FILE * _out_str , yyscan_t yyscanner );
- int cmFortran_yyget_leng (yyscan_t yyscanner );
+ int yyget_leng ( yyscan_t yyscanner );
-char *cmFortran_yyget_text (yyscan_t yyscanner );
+char *yyget_text ( yyscan_t yyscanner );
-int cmFortran_yyget_lineno (yyscan_t yyscanner );
+int yyget_lineno ( yyscan_t yyscanner );
-void cmFortran_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+void yyset_lineno ( int _line_number , yyscan_t yyscanner );
-int cmFortran_yyget_column (yyscan_t yyscanner );
+int yyget_column ( yyscan_t yyscanner );
-void cmFortran_yyset_column (int _column_no ,yyscan_t yyscanner );
+void yyset_column ( int _column_no , yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
@@ -272,18 +484,18 @@ void cmFortran_yyset_column (int _column_no ,yyscan_t yyscanner );
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
-extern "C" int cmFortran_yywrap (yyscan_t yyscanner );
+extern "C" int yywrap ( yyscan_t yyscanner );
#else
-extern int cmFortran_yywrap (yyscan_t yyscanner );
+extern int yywrap ( yyscan_t yyscanner );
#endif
#endif
#ifndef yytext_ptr
-static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
+static void yy_flex_strncpy ( char *, const char *, int , yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
+static int yy_flex_strlen ( const char * , yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
@@ -311,9 +523,9 @@ static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
-extern int cmFortran_yylex (yyscan_t yyscanner);
+extern int yylex (yyscan_t yyscanner);
-#define YY_DECL int cmFortran_yylex (yyscan_t yyscanner)
+#define YY_DECL int yylex (yyscan_t yyscanner)
#endif /* !YY_DECL */
/* yy_get_previous_state - get the state just before the EOB char was reached */
@@ -330,9 +542,150 @@ extern int cmFortran_yylex (yyscan_t yyscanner);
#undef YY_DECL
#endif
-#line 178 "cmFortranLexer.in.l"
-
+#ifndef cmFortran_yy_create_buffer_ALREADY_DEFINED
+#undef yy_create_buffer
+#endif
+#ifndef cmFortran_yy_delete_buffer_ALREADY_DEFINED
+#undef yy_delete_buffer
+#endif
+#ifndef cmFortran_yy_scan_buffer_ALREADY_DEFINED
+#undef yy_scan_buffer
+#endif
+#ifndef cmFortran_yy_scan_string_ALREADY_DEFINED
+#undef yy_scan_string
+#endif
+#ifndef cmFortran_yy_scan_bytes_ALREADY_DEFINED
+#undef yy_scan_bytes
+#endif
+#ifndef cmFortran_yy_init_buffer_ALREADY_DEFINED
+#undef yy_init_buffer
+#endif
+#ifndef cmFortran_yy_flush_buffer_ALREADY_DEFINED
+#undef yy_flush_buffer
+#endif
+#ifndef cmFortran_yy_load_buffer_state_ALREADY_DEFINED
+#undef yy_load_buffer_state
+#endif
+#ifndef cmFortran_yy_switch_to_buffer_ALREADY_DEFINED
+#undef yy_switch_to_buffer
+#endif
+#ifndef cmFortran_yypush_buffer_state_ALREADY_DEFINED
+#undef yypush_buffer_state
+#endif
+#ifndef cmFortran_yypop_buffer_state_ALREADY_DEFINED
+#undef yypop_buffer_state
+#endif
+#ifndef cmFortran_yyensure_buffer_stack_ALREADY_DEFINED
+#undef yyensure_buffer_stack
+#endif
+#ifndef cmFortran_yylex_ALREADY_DEFINED
+#undef yylex
+#endif
+#ifndef cmFortran_yyrestart_ALREADY_DEFINED
+#undef yyrestart
+#endif
+#ifndef cmFortran_yylex_init_ALREADY_DEFINED
+#undef yylex_init
+#endif
+#ifndef cmFortran_yylex_init_extra_ALREADY_DEFINED
+#undef yylex_init_extra
+#endif
+#ifndef cmFortran_yylex_destroy_ALREADY_DEFINED
+#undef yylex_destroy
+#endif
+#ifndef cmFortran_yyget_debug_ALREADY_DEFINED
+#undef yyget_debug
+#endif
+#ifndef cmFortran_yyset_debug_ALREADY_DEFINED
+#undef yyset_debug
+#endif
+#ifndef cmFortran_yyget_extra_ALREADY_DEFINED
+#undef yyget_extra
+#endif
+#ifndef cmFortran_yyset_extra_ALREADY_DEFINED
+#undef yyset_extra
+#endif
+#ifndef cmFortran_yyget_in_ALREADY_DEFINED
+#undef yyget_in
+#endif
+#ifndef cmFortran_yyset_in_ALREADY_DEFINED
+#undef yyset_in
+#endif
+#ifndef cmFortran_yyget_out_ALREADY_DEFINED
+#undef yyget_out
+#endif
+#ifndef cmFortran_yyset_out_ALREADY_DEFINED
+#undef yyset_out
+#endif
+#ifndef cmFortran_yyget_leng_ALREADY_DEFINED
+#undef yyget_leng
+#endif
+#ifndef cmFortran_yyget_text_ALREADY_DEFINED
+#undef yyget_text
+#endif
+#ifndef cmFortran_yyget_lineno_ALREADY_DEFINED
+#undef yyget_lineno
+#endif
+#ifndef cmFortran_yyset_lineno_ALREADY_DEFINED
+#undef yyset_lineno
+#endif
+#ifndef cmFortran_yyget_column_ALREADY_DEFINED
+#undef yyget_column
+#endif
+#ifndef cmFortran_yyset_column_ALREADY_DEFINED
+#undef yyset_column
+#endif
+#ifndef cmFortran_yywrap_ALREADY_DEFINED
+#undef yywrap
+#endif
+#ifndef cmFortran_yyget_lval_ALREADY_DEFINED
+#undef yyget_lval
+#endif
+#ifndef cmFortran_yyset_lval_ALREADY_DEFINED
+#undef yyset_lval
+#endif
+#ifndef cmFortran_yyget_lloc_ALREADY_DEFINED
+#undef yyget_lloc
+#endif
+#ifndef cmFortran_yyset_lloc_ALREADY_DEFINED
+#undef yyset_lloc
+#endif
+#ifndef cmFortran_yyalloc_ALREADY_DEFINED
+#undef yyalloc
+#endif
+#ifndef cmFortran_yyrealloc_ALREADY_DEFINED
+#undef yyrealloc
+#endif
+#ifndef cmFortran_yyfree_ALREADY_DEFINED
+#undef yyfree
+#endif
+#ifndef cmFortran_yytext_ALREADY_DEFINED
+#undef yytext
+#endif
+#ifndef cmFortran_yyleng_ALREADY_DEFINED
+#undef yyleng
+#endif
+#ifndef cmFortran_yyin_ALREADY_DEFINED
+#undef yyin
+#endif
+#ifndef cmFortran_yyout_ALREADY_DEFINED
+#undef yyout
+#endif
+#ifndef cmFortran_yy_flex_debug_ALREADY_DEFINED
+#undef yy_flex_debug
+#endif
+#ifndef cmFortran_yylineno_ALREADY_DEFINED
+#undef yylineno
+#endif
+#ifndef cmFortran_yytables_fload_ALREADY_DEFINED
+#undef yytables_fload
+#endif
+#ifndef cmFortran_yytables_destroy_ALREADY_DEFINED
+#undef yytables_destroy
+#endif
+#ifndef cmFortran_yyTABLES_NAME_ALREADY_DEFINED
+#undef yyTABLES_NAME
+#endif
-#line 337 "cmFortranLexer.h"
#undef cmFortran_yyIN_HEADER
#endif /* cmFortran_yyHEADER_H */
diff --git a/Source/LexerParser/cmFortranLexer.in.l b/Source/LexerParser/cmFortranLexer.in.l
index 112121037..9acba4c1f 100644
--- a/Source/LexerParser/cmFortranLexer.in.l
+++ b/Source/LexerParser/cmFortranLexer.in.l
@@ -17,14 +17,12 @@ This file must be translated to C++ and modified to build everywhere.
Run flex >= 2.6 like this:
- flex -i --nounistd -DFLEXINT_H --prefix=cmFortran_yy --header-file=cmFortranLexer.h -ocmFortranLexer.cxx cmFortranLexer.in.l
+ flex -i --nounistd -DFLEXINT_H --noline --header-file=cmFortranLexer.h -ocmFortranLexer.cxx cmFortranLexer.in.l
Modify cmFortranLexer.cxx:
- - remove trailing whitespace: sed -i 's/\s*$//' cmFortranLexer.h cmFortranLexer.cxx
- - remove blank lines at end of file
- - #include "cmStandardLexer.h" at the top
- - add cast in yy_scan_bytes for loop condition of _yybytes_len to size_t
-
+ - remove trailing whitespace: sed -i 's/\s*$//' cmFortranLexer.h cmFortranLexer.cxx
+ - remove blank lines at end of file: sed -i '${/^$/d;}' cmFortranLexer.h cmFortranLexer.cxx
+ - #include "cmStandardLexer.h" at the top: sed -i '1i#include "cmStandardLexer.h"' cmFortranLexer.cxx
*/
/* IWYU pragma: no_forward_declare yyguts_t */
@@ -45,6 +43,7 @@ Modify cmFortranLexer.cxx:
/*--------------------------------------------------------------------------*/
%}
+%option prefix="cmFortran_yy"
%option reentrant
%option noyywrap
diff --git a/Source/LexerParser/cmListFileLexer.c b/Source/LexerParser/cmListFileLexer.c
index 3dd3b85b9..c6f524c6b 100644
--- a/Source/LexerParser/cmListFileLexer.c
+++ b/Source/LexerParser/cmListFileLexer.c
@@ -1,7 +1,4 @@
#include "cmStandardLexer.h"
-#line 2 "cmListFileLexer.c"
-
-#line 4 "cmListFileLexer.c"
#define FLEXINT_H 1
#define YY_INT_ALIGNED short int
@@ -11,11 +8,221 @@
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
-#define YY_FLEX_SUBMINOR_VERSION 1
+#define YY_FLEX_SUBMINOR_VERSION 4
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
+#ifdef yy_create_buffer
+#define cmListFileLexer_yy_create_buffer_ALREADY_DEFINED
+#else
+#define yy_create_buffer cmListFileLexer_yy_create_buffer
+#endif
+
+#ifdef yy_delete_buffer
+#define cmListFileLexer_yy_delete_buffer_ALREADY_DEFINED
+#else
+#define yy_delete_buffer cmListFileLexer_yy_delete_buffer
+#endif
+
+#ifdef yy_scan_buffer
+#define cmListFileLexer_yy_scan_buffer_ALREADY_DEFINED
+#else
+#define yy_scan_buffer cmListFileLexer_yy_scan_buffer
+#endif
+
+#ifdef yy_scan_string
+#define cmListFileLexer_yy_scan_string_ALREADY_DEFINED
+#else
+#define yy_scan_string cmListFileLexer_yy_scan_string
+#endif
+
+#ifdef yy_scan_bytes
+#define cmListFileLexer_yy_scan_bytes_ALREADY_DEFINED
+#else
+#define yy_scan_bytes cmListFileLexer_yy_scan_bytes
+#endif
+
+#ifdef yy_init_buffer
+#define cmListFileLexer_yy_init_buffer_ALREADY_DEFINED
+#else
+#define yy_init_buffer cmListFileLexer_yy_init_buffer
+#endif
+
+#ifdef yy_flush_buffer
+#define cmListFileLexer_yy_flush_buffer_ALREADY_DEFINED
+#else
+#define yy_flush_buffer cmListFileLexer_yy_flush_buffer
+#endif
+
+#ifdef yy_load_buffer_state
+#define cmListFileLexer_yy_load_buffer_state_ALREADY_DEFINED
+#else
+#define yy_load_buffer_state cmListFileLexer_yy_load_buffer_state
+#endif
+
+#ifdef yy_switch_to_buffer
+#define cmListFileLexer_yy_switch_to_buffer_ALREADY_DEFINED
+#else
+#define yy_switch_to_buffer cmListFileLexer_yy_switch_to_buffer
+#endif
+
+#ifdef yypush_buffer_state
+#define cmListFileLexer_yypush_buffer_state_ALREADY_DEFINED
+#else
+#define yypush_buffer_state cmListFileLexer_yypush_buffer_state
+#endif
+
+#ifdef yypop_buffer_state
+#define cmListFileLexer_yypop_buffer_state_ALREADY_DEFINED
+#else
+#define yypop_buffer_state cmListFileLexer_yypop_buffer_state
+#endif
+
+#ifdef yyensure_buffer_stack
+#define cmListFileLexer_yyensure_buffer_stack_ALREADY_DEFINED
+#else
+#define yyensure_buffer_stack cmListFileLexer_yyensure_buffer_stack
+#endif
+
+#ifdef yylex
+#define cmListFileLexer_yylex_ALREADY_DEFINED
+#else
+#define yylex cmListFileLexer_yylex
+#endif
+
+#ifdef yyrestart
+#define cmListFileLexer_yyrestart_ALREADY_DEFINED
+#else
+#define yyrestart cmListFileLexer_yyrestart
+#endif
+
+#ifdef yylex_init
+#define cmListFileLexer_yylex_init_ALREADY_DEFINED
+#else
+#define yylex_init cmListFileLexer_yylex_init
+#endif
+
+#ifdef yylex_init_extra
+#define cmListFileLexer_yylex_init_extra_ALREADY_DEFINED
+#else
+#define yylex_init_extra cmListFileLexer_yylex_init_extra
+#endif
+
+#ifdef yylex_destroy
+#define cmListFileLexer_yylex_destroy_ALREADY_DEFINED
+#else
+#define yylex_destroy cmListFileLexer_yylex_destroy
+#endif
+
+#ifdef yyget_debug
+#define cmListFileLexer_yyget_debug_ALREADY_DEFINED
+#else
+#define yyget_debug cmListFileLexer_yyget_debug
+#endif
+
+#ifdef yyset_debug
+#define cmListFileLexer_yyset_debug_ALREADY_DEFINED
+#else
+#define yyset_debug cmListFileLexer_yyset_debug
+#endif
+
+#ifdef yyget_extra
+#define cmListFileLexer_yyget_extra_ALREADY_DEFINED
+#else
+#define yyget_extra cmListFileLexer_yyget_extra
+#endif
+
+#ifdef yyset_extra
+#define cmListFileLexer_yyset_extra_ALREADY_DEFINED
+#else
+#define yyset_extra cmListFileLexer_yyset_extra
+#endif
+
+#ifdef yyget_in
+#define cmListFileLexer_yyget_in_ALREADY_DEFINED
+#else
+#define yyget_in cmListFileLexer_yyget_in
+#endif
+
+#ifdef yyset_in
+#define cmListFileLexer_yyset_in_ALREADY_DEFINED
+#else
+#define yyset_in cmListFileLexer_yyset_in
+#endif
+
+#ifdef yyget_out
+#define cmListFileLexer_yyget_out_ALREADY_DEFINED
+#else
+#define yyget_out cmListFileLexer_yyget_out
+#endif
+
+#ifdef yyset_out
+#define cmListFileLexer_yyset_out_ALREADY_DEFINED
+#else
+#define yyset_out cmListFileLexer_yyset_out
+#endif
+
+#ifdef yyget_leng
+#define cmListFileLexer_yyget_leng_ALREADY_DEFINED
+#else
+#define yyget_leng cmListFileLexer_yyget_leng
+#endif
+
+#ifdef yyget_text
+#define cmListFileLexer_yyget_text_ALREADY_DEFINED
+#else
+#define yyget_text cmListFileLexer_yyget_text
+#endif
+
+#ifdef yyget_lineno
+#define cmListFileLexer_yyget_lineno_ALREADY_DEFINED
+#else
+#define yyget_lineno cmListFileLexer_yyget_lineno
+#endif
+
+#ifdef yyset_lineno
+#define cmListFileLexer_yyset_lineno_ALREADY_DEFINED
+#else
+#define yyset_lineno cmListFileLexer_yyset_lineno
+#endif
+
+#ifdef yyget_column
+#define cmListFileLexer_yyget_column_ALREADY_DEFINED
+#else
+#define yyget_column cmListFileLexer_yyget_column
+#endif
+
+#ifdef yyset_column
+#define cmListFileLexer_yyset_column_ALREADY_DEFINED
+#else
+#define yyset_column cmListFileLexer_yyset_column
+#endif
+
+#ifdef yywrap
+#define cmListFileLexer_yywrap_ALREADY_DEFINED
+#else
+#define yywrap cmListFileLexer_yywrap
+#endif
+
+#ifdef yyalloc
+#define cmListFileLexer_yyalloc_ALREADY_DEFINED
+#else
+#define yyalloc cmListFileLexer_yyalloc
+#endif
+
+#ifdef yyrealloc
+#define cmListFileLexer_yyrealloc_ALREADY_DEFINED
+#else
+#define yyrealloc cmListFileLexer_yyrealloc
+#endif
+
+#ifdef yyfree
+#define cmListFileLexer_yyfree_ALREADY_DEFINED
+#else
+#define yyfree cmListFileLexer_yyfree
+#endif
+
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
@@ -86,10 +293,16 @@ typedef unsigned int flex_uint32_t;
#define UINT32_MAX (4294967295U)
#endif
+#ifndef SIZE_MAX
+#define SIZE_MAX (~(size_t)0)
+#endif
+
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
+/* begin standard C++ headers. */
+
/* TODO: this is always defined, so inline it */
#define yyconst const
@@ -102,12 +315,10 @@ typedef unsigned int flex_uint32_t;
/* Returned upon end-of-file. */
#define YY_NULL 0
-/* Promotes a possibly negative, possibly signed char to an unsigned
- * integer for use as an array index. If the signed char is negative,
- * we want to instead treat it as an 8-bit unsigned char, hence the
- * double cast.
+/* Promotes a possibly negative, possibly signed char to an
+ * integer in range [0..255] for use as an array index.
*/
-#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
+#define YY_SC_TO_UI(c) ((YY_CHAR) (c))
/* An opaque pointer. */
#ifndef YY_TYPEDEF_YY_SCANNER_T
@@ -131,20 +342,16 @@ typedef void* yyscan_t;
* definition of BEGIN.
*/
#define BEGIN yyg->yy_start = 1 + 2 *
-
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START ((yyg->yy_start - 1) / 2)
#define YYSTATE YY_START
-
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
-
/* Special action meaning "start processing a new file". */
-#define YY_NEW_FILE cmListFileLexer_yyrestart(yyin ,yyscanner )
-
+#define YY_NEW_FILE yyrestart( yyin , yyscanner )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
@@ -180,7 +387,7 @@ typedef size_t yy_size_t;
/* Note: We specifically omit the test for yy_rule_can_match_eol because it requires
* access to the local variable yy_act. Since yyless() is a macro, it would break
- * existing scanners that call yyless() from OUTSIDE cmListFileLexer_yylex.
+ * existing scanners that call yyless() from OUTSIDE yylex.
* One obvious solution it to make yy_act a global. I tried that, and saw
* a 5% performance hit in a non-yylineno scanner, because yy_act is
* normally declared as a register variable-- so it is not worth it.
@@ -213,7 +420,6 @@ typedef size_t yy_size_t;
YY_DO_BEFORE_ACTION; /* set up yytext again */ \
} \
while ( 0 )
-
#define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner )
#ifndef YY_STRUCT_YY_BUFFER_STATE
@@ -273,7 +479,7 @@ struct yy_buffer_state
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
- * (via cmListFileLexer_yyrestart()), so that the user can continue scanning by
+ * (via yyrestart()), so that the user can continue scanning by
* just pointing yyin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
@@ -290,73 +496,67 @@ struct yy_buffer_state
#define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \
? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \
: NULL)
-
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top]
-void cmListFileLexer_yyrestart (FILE *input_file ,yyscan_t yyscanner );
-void cmListFileLexer_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmListFileLexer_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
-void cmListFileLexer_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmListFileLexer_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
-void cmListFileLexer_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
-void cmListFileLexer_yypop_buffer_state (yyscan_t yyscanner );
+void yyrestart ( FILE *input_file , yyscan_t yyscanner );
+void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_create_buffer ( FILE *file, int size , yyscan_t yyscanner );
+void yy_delete_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yy_flush_buffer ( YY_BUFFER_STATE b , yyscan_t yyscanner );
+void yypush_buffer_state ( YY_BUFFER_STATE new_buffer , yyscan_t yyscanner );
+void yypop_buffer_state ( yyscan_t yyscanner );
-static void cmListFileLexer_yyensure_buffer_stack (yyscan_t yyscanner );
-static void cmListFileLexer_yy_load_buffer_state (yyscan_t yyscanner );
-static void cmListFileLexer_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner );
+static void yyensure_buffer_stack ( yyscan_t yyscanner );
+static void yy_load_buffer_state ( yyscan_t yyscanner );
+static void yy_init_buffer ( YY_BUFFER_STATE b, FILE *file , yyscan_t yyscanner );
+#define YY_FLUSH_BUFFER yy_flush_buffer( YY_CURRENT_BUFFER , yyscanner)
-#define YY_FLUSH_BUFFER cmListFileLexer_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner)
+YY_BUFFER_STATE yy_scan_buffer ( char *base, yy_size_t size , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_string ( const char *yy_str , yyscan_t yyscanner );
+YY_BUFFER_STATE yy_scan_bytes ( const char *bytes, int len , yyscan_t yyscanner );
-YY_BUFFER_STATE cmListFileLexer_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmListFileLexer_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner );
-YY_BUFFER_STATE cmListFileLexer_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner );
-
-void *cmListFileLexer_yyalloc (yy_size_t ,yyscan_t yyscanner );
-void *cmListFileLexer_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner );
-void cmListFileLexer_yyfree (void * ,yyscan_t yyscanner );
-
-#define yy_new_buffer cmListFileLexer_yy_create_buffer
+void *yyalloc ( yy_size_t , yyscan_t yyscanner );
+void *yyrealloc ( void *, yy_size_t , yyscan_t yyscanner );
+void yyfree ( void * , yyscan_t yyscanner );
+#define yy_new_buffer yy_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
- cmListFileLexer_yyensure_buffer_stack (yyscanner); \
+ yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
- cmListFileLexer_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
-
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
- cmListFileLexer_yyensure_buffer_stack (yyscanner); \
+ yyensure_buffer_stack (yyscanner); \
YY_CURRENT_BUFFER_LVALUE = \
- cmListFileLexer_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
-
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define cmListFileLexer_yywrap(yyscanner) (/*CONSTCOND*/1)
#define YY_SKIP_YYWRAP
-
-typedef unsigned char YY_CHAR;
+typedef flex_uint8_t YY_CHAR;
typedef int yy_state_type;
#define yytext_ptr yytext_r
-static yy_state_type yy_get_previous_state (yyscan_t yyscanner );
-static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner);
-static int yy_get_next_buffer (yyscan_t yyscanner );
-static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
+static yy_state_type yy_get_previous_state ( yyscan_t yyscanner );
+static yy_state_type yy_try_NUL_trans ( yy_state_type current_state , yyscan_t yyscanner);
+static int yy_get_next_buffer ( yyscan_t yyscanner );
+static void yynoreturn yy_fatal_error ( const char* msg , yyscan_t yyscanner );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up yytext.
@@ -367,7 +567,6 @@ static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner );
yyg->yy_hold_char = *yy_cp; \
*yy_cp = '\0'; \
yyg->yy_c_buf_p = yy_cp;
-
#define YY_NUM_RULES 24
#define YY_END_OF_BUFFER 25
/* This struct is not used in this scanner,
@@ -377,19 +576,19 @@ struct yy_trans_info
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
-static yyconst flex_int16_t yy_accept[77] =
+static const flex_int16_t yy_accept[81] =
{ 0,
0, 0, 0, 0, 0, 0, 0, 0, 4, 4,
25, 13, 22, 1, 16, 3, 13, 5, 6, 7,
- 15, 23, 17, 19, 20, 21, 10, 11, 8, 12,
- 9, 4, 13, 0, 13, 0, 22, 0, 0, 7,
- 13, 0, 13, 0, 2, 0, 13, 17, 0, 18,
- 10, 8, 4, 0, 14, 0, 0, 0, 0, 14,
- 0, 0, 14, 0, 0, 0, 2, 14, 0, 0,
- 0, 0, 0, 0, 0, 0
+ 15, 23, 23, 17, 19, 20, 21, 17, 10, 11,
+ 8, 10, 12, 9, 24, 4, 13, 0, 13, 0,
+ 22, 0, 0, 7, 13, 0, 13, 0, 2, 0,
+ 13, 17, 0, 18, 10, 8, 4, 0, 14, 0,
+ 0, 0, 0, 14, 0, 0, 14, 0, 0, 0,
+ 2, 14, 0, 0, 0, 0, 0, 0, 0, 0
} ;
-static yyconst YY_CHAR yy_ec[256] =
+static const YY_CHAR yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
1, 1, 4, 1, 1, 1, 1, 1, 1, 1,
@@ -421,108 +620,126 @@ static yyconst YY_CHAR yy_ec[256] =
1, 1, 1, 1, 1
} ;
-static yyconst YY_CHAR yy_meta[16] =
+static const YY_CHAR yy_meta[17] =
{ 0,
1, 1, 2, 3, 4, 3, 1, 3, 5, 6,
- 1, 6, 1, 1, 7
+ 1, 6, 1, 1, 7, 8
} ;
-static yyconst flex_uint16_t yy_base[95] =
+static const flex_int16_t yy_base[99] =
{ 0,
- 0, 0, 13, 25, 14, 16, 17, 18, 90, 88,
- 88, 39, 20, 237, 237, 74, 78, 237, 237, 13,
- 54, 0, 71, 237, 237, 31, 0, 237, 73, 237,
- 237, 0, 0, 65, 75, 0, 33, 30, 72, 0,
- 0, 75, 70, 0, 74, 0, 0, 62, 70, 237,
- 0, 63, 0, 85, 99, 65, 111, 62, 34, 0,
- 54, 116, 0, 54, 127, 51, 237, 50, 0, 48,
- 47, 39, 33, 29, 17, 237, 136, 143, 150, 157,
- 164, 171, 178, 184, 191, 198, 201, 207, 214, 217,
- 219, 225, 228, 230
+ 0, 0, 14, 28, 42, 56, 70, 84, 18, 19,
+ 69, 100, 16, 323, 323, 55, 59, 323, 323, 13,
+ 115, 0, 323, 52, 323, 323, 21, 51, 0, 323,
+ 53, 0, 323, 323, 323, 0, 0, 126, 55, 0,
+ 25, 25, 53, 0, 0, 136, 53, 0, 57, 0,
+ 0, 42, 50, 323, 0, 43, 0, 146, 160, 45,
+ 172, 43, 26, 0, 42, 184, 0, 42, 195, 40,
+ 323, 40, 0, 38, 37, 34, 32, 31, 23, 323,
+ 211, 219, 227, 235, 243, 251, 259, 267, 274, 281,
+ 285, 291, 298, 302, 304, 310, 314, 316
} ;
-static yyconst flex_int16_t yy_def[95] =
+static const flex_int16_t yy_def[99] =
{ 0,
- 76, 1, 77, 77, 78, 78, 79, 79, 80, 80,
- 76, 76, 76, 76, 76, 76, 12, 76, 76, 12,
- 76, 81, 82, 76, 76, 82, 83, 76, 76, 76,
- 76, 84, 12, 85, 12, 86, 76, 76, 87, 20,
- 12, 88, 12, 21, 76, 89, 12, 82, 82, 76,
- 83, 76, 84, 85, 76, 54, 85, 90, 76, 55,
- 87, 88, 55, 62, 88, 91, 76, 55, 92, 93,
- 90, 94, 91, 93, 94, 0, 76, 76, 76, 76,
- 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
- 76, 76, 76, 76
+ 80, 1, 81, 81, 82, 82, 83, 83, 84, 84,
+ 80, 80, 80, 80, 80, 80, 12, 80, 80, 12,
+ 80, 85, 80, 86, 80, 80, 86, 86, 87, 80,
+ 80, 87, 80, 80, 80, 88, 12, 89, 12, 90,
+ 80, 80, 91, 20, 12, 92, 12, 21, 80, 93,
+ 12, 86, 86, 80, 87, 80, 88, 89, 80, 58,
+ 89, 94, 80, 59, 91, 92, 59, 66, 92, 95,
+ 80, 59, 96, 97, 94, 98, 95, 97, 98, 0,
+ 80, 80, 80, 80, 80, 80, 80, 80, 80, 80,
+ 80, 80, 80, 80, 80, 80, 80, 80
} ;
-static yyconst flex_uint16_t yy_nxt[253] =
+static const flex_int16_t yy_nxt[340] =
{ 0,
12, 13, 14, 13, 15, 16, 17, 18, 19, 12,
- 12, 20, 21, 22, 12, 24, 28, 25, 28, 28,
- 28, 37, 40, 37, 40, 62, 26, 24, 29, 25,
- 29, 31, 31, 50, 37, 48, 37, 54, 26, 33,
- 59, 63, 45, 34, 59, 35, 45, 62, 33, 33,
- 33, 33, 36, 33, 41, 55, 54, 58, 42, 63,
- 43, 72, 60, 41, 44, 41, 45, 46, 41, 55,
- 55, 56, 70, 52, 48, 49, 67, 66, 57, 63,
- 60, 64, 58, 52, 49, 39, 38, 76, 65, 55,
- 14, 56, 14, 76, 76, 76, 76, 76, 57, 55,
-
- 76, 76, 76, 34, 76, 68, 76, 76, 55, 55,
- 55, 55, 69, 55, 54, 76, 54, 76, 54, 54,
- 63, 76, 64, 76, 76, 76, 76, 76, 76, 65,
- 62, 76, 62, 76, 62, 62, 23, 23, 23, 23,
- 23, 23, 23, 27, 27, 27, 27, 27, 27, 27,
- 30, 30, 30, 30, 30, 30, 30, 32, 32, 32,
- 32, 32, 32, 32, 47, 76, 47, 47, 47, 47,
- 47, 48, 76, 48, 76, 48, 48, 48, 51, 76,
- 51, 51, 51, 51, 53, 76, 53, 53, 53, 53,
- 53, 54, 76, 76, 54, 76, 54, 54, 33, 76,
-
- 33, 33, 33, 33, 33, 61, 61, 62, 76, 76,
- 62, 76, 62, 62, 41, 76, 41, 41, 41, 41,
- 41, 71, 71, 73, 73, 55, 76, 55, 55, 55,
- 55, 55, 74, 74, 75, 75, 11, 76, 76, 76,
- 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
- 76, 76
+ 12, 20, 21, 22, 12, 23, 25, 41, 26, 41,
+ 14, 14, 44, 54, 44, 52, 41, 27, 41, 28,
+ 25, 66, 26, 35, 35, 63, 63, 49, 49, 58,
+ 67, 27, 66, 28, 30, 59, 58, 62, 67, 76,
+ 64, 59, 74, 56, 52, 53, 31, 32, 30, 71,
+ 70, 64, 62, 56, 53, 53, 43, 42, 80, 80,
+ 31, 32, 30, 80, 80, 80, 80, 80, 80, 80,
+ 80, 80, 80, 80, 34, 35, 30, 80, 80, 80,
+ 80, 80, 80, 80, 80, 80, 80, 80, 34, 35,
+
+ 37, 80, 80, 80, 38, 80, 39, 80, 80, 37,
+ 37, 37, 37, 40, 37, 45, 80, 80, 80, 46,
+ 80, 47, 80, 80, 45, 48, 45, 49, 50, 45,
+ 59, 80, 60, 80, 80, 80, 80, 80, 80, 61,
+ 67, 80, 68, 80, 80, 80, 80, 80, 80, 69,
+ 59, 80, 60, 80, 80, 80, 80, 80, 80, 61,
+ 59, 80, 80, 80, 38, 80, 72, 80, 80, 59,
+ 59, 59, 59, 73, 59, 58, 80, 58, 80, 58,
+ 58, 80, 80, 80, 80, 80, 80, 58, 67, 80,
+ 68, 80, 80, 80, 80, 80, 80, 69, 66, 80,
+
+ 66, 80, 66, 66, 80, 80, 80, 80, 80, 80,
+ 66, 24, 24, 24, 24, 24, 24, 24, 24, 29,
+ 29, 29, 29, 29, 29, 29, 29, 33, 33, 33,
+ 33, 33, 33, 33, 33, 36, 36, 36, 36, 36,
+ 36, 36, 36, 51, 80, 51, 51, 51, 51, 51,
+ 51, 52, 80, 52, 80, 52, 52, 52, 52, 55,
+ 80, 55, 55, 55, 55, 80, 55, 57, 80, 57,
+ 57, 57, 57, 57, 58, 80, 80, 58, 80, 58,
+ 58, 37, 80, 37, 37, 37, 37, 37, 37, 65,
+ 65, 66, 80, 80, 66, 80, 66, 66, 45, 80,
+
+ 45, 45, 45, 45, 45, 45, 75, 75, 77, 77,
+ 59, 80, 59, 59, 59, 59, 59, 59, 78, 78,
+ 79, 79, 11, 80, 80, 80, 80, 80, 80, 80,
+ 80, 80, 80, 80, 80, 80, 80, 80, 80
} ;
-static yyconst flex_int16_t yy_chk[253] =
+static const flex_int16_t yy_chk[340] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 3, 5, 3, 6, 7,
- 8, 13, 20, 13, 20, 75, 3, 4, 5, 4,
- 6, 7, 8, 26, 37, 26, 37, 74, 4, 12,
- 38, 73, 38, 12, 59, 12, 59, 72, 12, 12,
- 12, 12, 12, 12, 21, 71, 70, 68, 21, 66,
- 21, 64, 61, 21, 21, 21, 21, 21, 21, 34,
- 58, 34, 56, 52, 49, 48, 45, 43, 34, 42,
- 39, 42, 35, 29, 23, 17, 16, 11, 42, 54,
- 10, 54, 9, 0, 0, 0, 0, 0, 54, 55,
-
- 0, 0, 0, 55, 0, 55, 0, 0, 55, 55,
- 55, 55, 55, 55, 57, 0, 57, 0, 57, 57,
- 62, 0, 62, 0, 0, 0, 0, 0, 0, 62,
- 65, 0, 65, 0, 65, 65, 77, 77, 77, 77,
- 77, 77, 77, 78, 78, 78, 78, 78, 78, 78,
- 79, 79, 79, 79, 79, 79, 79, 80, 80, 80,
- 80, 80, 80, 80, 81, 0, 81, 81, 81, 81,
- 81, 82, 0, 82, 0, 82, 82, 82, 83, 0,
- 83, 83, 83, 83, 84, 0, 84, 84, 84, 84,
- 84, 85, 0, 0, 85, 0, 85, 85, 86, 0,
-
- 86, 86, 86, 86, 86, 87, 87, 88, 0, 0,
- 88, 0, 88, 88, 89, 0, 89, 89, 89, 89,
- 89, 90, 90, 91, 91, 92, 0, 92, 92, 92,
- 92, 92, 93, 93, 94, 94, 76, 76, 76, 76,
- 76, 76, 76, 76, 76, 76, 76, 76, 76, 76,
- 76, 76
+ 1, 1, 1, 1, 1, 1, 3, 13, 3, 13,
+ 9, 10, 20, 27, 20, 27, 41, 3, 41, 3,
+ 4, 79, 4, 9, 10, 42, 63, 42, 63, 78,
+ 77, 4, 76, 4, 5, 75, 74, 72, 70, 68,
+ 65, 62, 60, 56, 53, 52, 5, 5, 6, 49,
+ 47, 43, 39, 31, 28, 24, 17, 16, 11, 0,
+ 6, 6, 7, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 7, 7, 8, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 8, 8,
+
+ 12, 0, 0, 0, 12, 0, 12, 0, 0, 12,
+ 12, 12, 12, 12, 12, 21, 0, 0, 0, 21,
+ 0, 21, 0, 0, 21, 21, 21, 21, 21, 21,
+ 38, 0, 38, 0, 0, 0, 0, 0, 0, 38,
+ 46, 0, 46, 0, 0, 0, 0, 0, 0, 46,
+ 58, 0, 58, 0, 0, 0, 0, 0, 0, 58,
+ 59, 0, 0, 0, 59, 0, 59, 0, 0, 59,
+ 59, 59, 59, 59, 59, 61, 0, 61, 0, 61,
+ 61, 0, 0, 0, 0, 0, 0, 61, 66, 0,
+ 66, 0, 0, 0, 0, 0, 0, 66, 69, 0,
+
+ 69, 0, 69, 69, 0, 0, 0, 0, 0, 0,
+ 69, 81, 81, 81, 81, 81, 81, 81, 81, 82,
+ 82, 82, 82, 82, 82, 82, 82, 83, 83, 83,
+ 83, 83, 83, 83, 83, 84, 84, 84, 84, 84,
+ 84, 84, 84, 85, 0, 85, 85, 85, 85, 85,
+ 85, 86, 0, 86, 0, 86, 86, 86, 86, 87,
+ 0, 87, 87, 87, 87, 0, 87, 88, 0, 88,
+ 88, 88, 88, 88, 89, 0, 0, 89, 0, 89,
+ 89, 90, 0, 90, 90, 90, 90, 90, 90, 91,
+ 91, 92, 0, 0, 92, 0, 92, 92, 93, 0,
+
+ 93, 93, 93, 93, 93, 93, 94, 94, 95, 95,
+ 96, 0, 96, 96, 96, 96, 96, 96, 97, 97,
+ 98, 98, 80, 80, 80, 80, 80, 80, 80, 80,
+ 80, 80, 80, 80, 80, 80, 80, 80, 80
} ;
/* Table of booleans, true if rule could match eol. */
-static yyconst flex_int32_t yy_rule_can_match_eol[25] =
+static const flex_int32_t yy_rule_can_match_eol[25] =
{ 0,
1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1,
0, 0, 0, 0, 0, };
@@ -534,8 +751,6 @@ static yyconst flex_int32_t yy_rule_can_match_eol[25] =
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
-#line 1 "cmListFileLexer.in.l"
-#line 2 "cmListFileLexer.in.l"
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
/*
@@ -544,14 +759,12 @@ This file must be translated to C and modified to build everywhere.
Run flex >= 2.6 like this:
- flex --nounistd -DFLEXINT_H --prefix=cmListFileLexer_yy -ocmListFileLexer.c cmListFileLexer.in.l
+ flex --nounistd -DFLEXINT_H --noline -ocmListFileLexer.c cmListFileLexer.in.l
Modify cmListFileLexer.c:
- - remove trailing whitespace: sed -i 's/\s*$//' cmListFileLexer.c
- - remove blank lines at end of file
- - #include "cmStandardLexer.h" at the top
- - add cast in cmListFileLexer_yy_scan_bytes for loop condition of _yybytes_len to size_t
- - change type of variable yyl under yy_find_action from yy_size_t to int
+ - remove trailing whitespace: sed -i 's/\s*$//' cmListFileLexer.c
+ - remove blank lines at end of file: sed -i '${/^$/d;}' cmListFileLexer.c
+ - #include "cmStandardLexer.h" at the top: sed -i '1i#include "cmStandardLexer.h"' cmListFileLexer.c
*/
@@ -600,11 +813,6 @@ static void cmListFileLexerDestroy(cmListFileLexer* lexer);
/*--------------------------------------------------------------------------*/
-
-
-
-#line 606 "cmListFileLexer.c"
-
#define INITIAL 0
#define STRING 1
#define BRACKET 2
@@ -649,44 +857,44 @@ struct yyguts_t
}; /* end struct yyguts_t */
-static int yy_init_globals (yyscan_t yyscanner );
+static int yy_init_globals ( yyscan_t yyscanner );
-int cmListFileLexer_yylex_init (yyscan_t* scanner);
+int yylex_init (yyscan_t* scanner);
-int cmListFileLexer_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner);
+int yylex_init_extra ( YY_EXTRA_TYPE user_defined, yyscan_t* scanner);
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
-int cmListFileLexer_yylex_destroy (yyscan_t yyscanner );
+int yylex_destroy ( yyscan_t yyscanner );
-int cmListFileLexer_yyget_debug (yyscan_t yyscanner );
+int yyget_debug ( yyscan_t yyscanner );
-void cmListFileLexer_yyset_debug (int debug_flag ,yyscan_t yyscanner );
+void yyset_debug ( int debug_flag , yyscan_t yyscanner );
-YY_EXTRA_TYPE cmListFileLexer_yyget_extra (yyscan_t yyscanner );
+YY_EXTRA_TYPE yyget_extra ( yyscan_t yyscanner );
-void cmListFileLexer_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner );
+void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t yyscanner );
-FILE *cmListFileLexer_yyget_in (yyscan_t yyscanner );
+FILE *yyget_in ( yyscan_t yyscanner );
-void cmListFileLexer_yyset_in (FILE * _in_str ,yyscan_t yyscanner );
+void yyset_in ( FILE * _in_str , yyscan_t yyscanner );
-FILE *cmListFileLexer_yyget_out (yyscan_t yyscanner );
+FILE *yyget_out ( yyscan_t yyscanner );
-void cmListFileLexer_yyset_out (FILE * _out_str ,yyscan_t yyscanner );
+void yyset_out ( FILE * _out_str , yyscan_t yyscanner );
- int cmListFileLexer_yyget_leng (yyscan_t yyscanner );
+ int yyget_leng ( yyscan_t yyscanner );
-char *cmListFileLexer_yyget_text (yyscan_t yyscanner );
+char *yyget_text ( yyscan_t yyscanner );
-int cmListFileLexer_yyget_lineno (yyscan_t yyscanner );
+int yyget_lineno ( yyscan_t yyscanner );
-void cmListFileLexer_yyset_lineno (int _line_number ,yyscan_t yyscanner );
+void yyset_lineno ( int _line_number , yyscan_t yyscanner );
-int cmListFileLexer_yyget_column (yyscan_t yyscanner );
+int yyget_column ( yyscan_t yyscanner );
-void cmListFileLexer_yyset_column (int _column_no ,yyscan_t yyscanner );
+void yyset_column ( int _column_no , yyscan_t yyscanner );
/* Macros after this point can all be overridden by user definitions in
* section 1.
@@ -694,32 +902,31 @@ void cmListFileLexer_yyset_column (int _column_no ,yyscan_t yyscanner );
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
-extern "C" int cmListFileLexer_yywrap (yyscan_t yyscanner );
+extern "C" int yywrap ( yyscan_t yyscanner );
#else
-extern int cmListFileLexer_yywrap (yyscan_t yyscanner );
+extern int yywrap ( yyscan_t yyscanner );
#endif
#endif
#ifndef YY_NO_UNPUT
- static void yyunput (int c,char *buf_ptr ,yyscan_t yyscanner);
+ static void yyunput ( int c, char *buf_ptr , yyscan_t yyscanner);
#endif
#ifndef yytext_ptr
-static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner);
+static void yy_flex_strncpy ( char *, const char *, int , yyscan_t yyscanner);
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner);
+static int yy_flex_strlen ( const char * , yyscan_t yyscanner);
#endif
#ifndef YY_NO_INPUT
-
#ifdef __cplusplus
-static int yyinput (yyscan_t yyscanner );
+static int yyinput ( yyscan_t yyscanner );
#else
-static int input (yyscan_t yyscanner );
+static int input ( yyscan_t yyscanner );
#endif
#endif
@@ -750,7 +957,7 @@ static int input (yyscan_t yyscanner );
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
- size_t n; \
+ int n; \
for ( n = 0; n < max_size && \
(c = getc( yyin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
@@ -763,7 +970,7 @@ static int input (yyscan_t yyscanner );
else \
{ \
errno=0; \
- while ( (result = (int) fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+ while ( (result = (int) fread(buf, 1, (yy_size_t) max_size, yyin)) == 0 && ferror(yyin)) \
{ \
if( errno != EINTR) \
{ \
@@ -804,9 +1011,9 @@ static int input (yyscan_t yyscanner );
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
-extern int cmListFileLexer_yylex (yyscan_t yyscanner);
+extern int yylex (yyscan_t yyscanner);
-#define YY_DECL int cmListFileLexer_yylex (yyscan_t yyscanner)
+#define YY_DECL int yylex (yyscan_t yyscanner)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after yytext and yyleng
@@ -851,19 +1058,15 @@ YY_DECL
yyout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
- cmListFileLexer_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
- cmListFileLexer_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner);
}
- cmListFileLexer_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
}
{
-#line 80 "cmListFileLexer.in.l"
-
-
-#line 866 "cmListFileLexer.c"
while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */
{
@@ -890,13 +1093,13 @@ yy_match:
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
- if ( yy_current_state >= 77 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ if ( yy_current_state >= 81 )
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
++yy_cp;
}
- while ( yy_base[yy_current_state] != 237 );
+ while ( yy_base[yy_current_state] != 323 );
yy_find_action:
yy_act = yy_accept[yy_current_state];
@@ -935,7 +1138,6 @@ do_action: /* This label is used only to access EOF actions. */
case 1:
/* rule 1 can match eol */
YY_RULE_SETUP
-#line 82 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_Newline;
cmListFileLexerSetToken(lexer, yytext, yyleng);
@@ -948,7 +1150,6 @@ YY_RULE_SETUP
case 2:
/* rule 2 can match eol */
YY_RULE_SETUP
-#line 91 "cmListFileLexer.in.l"
{
const char* bracket = yytext;
lexer->comment = yytext[0] == '#';
@@ -971,7 +1172,6 @@ YY_RULE_SETUP
YY_BREAK
case 3:
YY_RULE_SETUP
-#line 111 "cmListFileLexer.in.l"
{
lexer->column += yyleng;
BEGIN(COMMENT);
@@ -979,14 +1179,12 @@ YY_RULE_SETUP
YY_BREAK
case 4:
YY_RULE_SETUP
-#line 116 "cmListFileLexer.in.l"
{
lexer->column += yyleng;
}
YY_BREAK
case 5:
YY_RULE_SETUP
-#line 120 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_ParenLeft;
cmListFileLexerSetToken(lexer, yytext, yyleng);
@@ -996,7 +1194,6 @@ YY_RULE_SETUP
YY_BREAK
case 6:
YY_RULE_SETUP
-#line 127 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_ParenRight;
cmListFileLexerSetToken(lexer, yytext, yyleng);
@@ -1006,7 +1203,6 @@ YY_RULE_SETUP
YY_BREAK
case 7:
YY_RULE_SETUP
-#line 134 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_Identifier;
cmListFileLexerSetToken(lexer, yytext, yyleng);
@@ -1016,7 +1212,6 @@ YY_RULE_SETUP
YY_BREAK
case 8:
YY_RULE_SETUP
-#line 141 "cmListFileLexer.in.l"
{
/* Handle ]]====]=======]*/
cmListFileLexerAppend(lexer, yytext, yyleng);
@@ -1028,7 +1223,6 @@ YY_RULE_SETUP
YY_BREAK
case 9:
YY_RULE_SETUP
-#line 150 "cmListFileLexer.in.l"
{
lexer->column += yyleng;
/* Erase the partial bracket from the token. */
@@ -1040,7 +1234,6 @@ YY_RULE_SETUP
YY_BREAK
case 10:
YY_RULE_SETUP
-#line 159 "cmListFileLexer.in.l"
{
cmListFileLexerAppend(lexer, yytext, yyleng);
lexer->column += yyleng;
@@ -1049,7 +1242,6 @@ YY_RULE_SETUP
case 11:
/* rule 11 can match eol */
YY_RULE_SETUP
-#line 164 "cmListFileLexer.in.l"
{
cmListFileLexerAppend(lexer, yytext, yyleng);
++lexer->line;
@@ -1059,7 +1251,6 @@ YY_RULE_SETUP
YY_BREAK
case 12:
YY_RULE_SETUP
-#line 171 "cmListFileLexer.in.l"
{
cmListFileLexerAppend(lexer, yytext, yyleng);
lexer->column += yyleng;
@@ -1068,7 +1259,6 @@ YY_RULE_SETUP
YY_BREAK
case YY_STATE_EOF(BRACKET):
case YY_STATE_EOF(BRACKETEND):
-#line 177 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_BadBracket;
BEGIN(INITIAL);
@@ -1077,7 +1267,6 @@ case YY_STATE_EOF(BRACKETEND):
YY_BREAK
case 13:
YY_RULE_SETUP
-#line 183 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_ArgumentUnquoted;
cmListFileLexerSetToken(lexer, yytext, yyleng);
@@ -1087,7 +1276,6 @@ YY_RULE_SETUP
YY_BREAK
case 14:
YY_RULE_SETUP
-#line 190 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_ArgumentUnquoted;
cmListFileLexerSetToken(lexer, yytext, yyleng);
@@ -1097,7 +1285,6 @@ YY_RULE_SETUP
YY_BREAK
case 15:
YY_RULE_SETUP
-#line 197 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_ArgumentUnquoted;
cmListFileLexerSetToken(lexer, yytext, yyleng);
@@ -1107,7 +1294,6 @@ YY_RULE_SETUP
YY_BREAK
case 16:
YY_RULE_SETUP
-#line 204 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_ArgumentQuoted;
cmListFileLexerSetToken(lexer, "", 0);
@@ -1117,7 +1303,6 @@ YY_RULE_SETUP
YY_BREAK
case 17:
YY_RULE_SETUP
-#line 211 "cmListFileLexer.in.l"
{
cmListFileLexerAppend(lexer, yytext, yyleng);
lexer->column += yyleng;
@@ -1126,7 +1311,6 @@ YY_RULE_SETUP
case 18:
/* rule 18 can match eol */
YY_RULE_SETUP
-#line 216 "cmListFileLexer.in.l"
{
/* Continuation: text is not part of string */
++lexer->line;
@@ -1136,7 +1320,6 @@ YY_RULE_SETUP
case 19:
/* rule 19 can match eol */
YY_RULE_SETUP
-#line 222 "cmListFileLexer.in.l"
{
cmListFileLexerAppend(lexer, yytext, yyleng);
++lexer->line;
@@ -1145,7 +1328,6 @@ YY_RULE_SETUP
YY_BREAK
case 20:
YY_RULE_SETUP
-#line 228 "cmListFileLexer.in.l"
{
lexer->column += yyleng;
BEGIN(INITIAL);
@@ -1154,14 +1336,12 @@ YY_RULE_SETUP
YY_BREAK
case 21:
YY_RULE_SETUP
-#line 234 "cmListFileLexer.in.l"
{
cmListFileLexerAppend(lexer, yytext, yyleng);
lexer->column += yyleng;
}
YY_BREAK
case YY_STATE_EOF(STRING):
-#line 239 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_BadString;
BEGIN(INITIAL);
@@ -1170,7 +1350,6 @@ case YY_STATE_EOF(STRING):
YY_BREAK
case 22:
YY_RULE_SETUP
-#line 245 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_Space;
cmListFileLexerSetToken(lexer, yytext, yyleng);
@@ -1180,7 +1359,6 @@ YY_RULE_SETUP
YY_BREAK
case 23:
YY_RULE_SETUP
-#line 252 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_BadCharacter;
cmListFileLexerSetToken(lexer, yytext, yyleng);
@@ -1190,7 +1368,6 @@ YY_RULE_SETUP
YY_BREAK
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(COMMENT):
-#line 259 "cmListFileLexer.in.l"
{
lexer->token.type = cmListFileLexer_Token_None;
cmListFileLexerSetToken(lexer, 0, 0);
@@ -1199,10 +1376,8 @@ case YY_STATE_EOF(COMMENT):
YY_BREAK
case 24:
YY_RULE_SETUP
-#line 265 "cmListFileLexer.in.l"
ECHO;
YY_BREAK
-#line 1205 "cmListFileLexer.c"
case YY_END_OF_BUFFER:
{
@@ -1218,7 +1393,7 @@ ECHO;
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed yyin at a new source and called
- * cmListFileLexer_yylex(). If so, then we have to assure
+ * yylex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
@@ -1278,7 +1453,7 @@ ECHO;
{
yyg->yy_did_buffer_switch_on_eof = 0;
- if ( cmListFileLexer_yywrap(yyscanner ) )
+ if ( yywrap( yyscanner ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
@@ -1332,7 +1507,7 @@ ECHO;
} /* end of action switch */
} /* end of scanning one token */
} /* end of user's declarations */
-} /* end of cmListFileLexer_yylex */
+} /* end of yylex */
/* yy_get_next_buffer - try to read in a new buffer
*
@@ -1346,7 +1521,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
char *source = yyg->yytext_ptr;
- yy_size_t number_to_move, i;
+ int number_to_move, i;
int ret_val;
if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] )
@@ -1375,7 +1550,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
/* Try to read more data. */
/* First move last chars to start of buffer. */
- number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1;
+ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr - 1);
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
@@ -1411,7 +1586,8 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
- cmListFileLexer_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner );
+ yyrealloc( (void *) b->yy_ch_buf,
+ (yy_size_t) (b->yy_buf_size + 2) , yyscanner );
}
else
/* Can't grow it, we don't own it. */
@@ -1443,7 +1619,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
- cmListFileLexer_yyrestart(yyin ,yyscanner);
+ yyrestart( yyin , yyscanner);
}
else
@@ -1457,12 +1633,15 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
else
ret_val = EOB_ACT_CONTINUE_SCAN;
- if ((int) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
+ if ((yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1);
- YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) cmListFileLexer_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner );
+ YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc(
+ (void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf, (yy_size_t) new_size , yyscanner );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
+ /* "- 2" to take care of EOB's */
+ YY_CURRENT_BUFFER_LVALUE->yy_buf_size = (int) (new_size - 2);
}
yyg->yy_n_chars += number_to_move;
@@ -1486,7 +1665,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp )
{
- YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
+ YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 16);
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
@@ -1495,10 +1674,10 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
- if ( yy_current_state >= 77 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ if ( yy_current_state >= 81 )
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
}
return yy_current_state;
@@ -1515,7 +1694,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */
char *yy_cp = yyg->yy_c_buf_p;
- YY_CHAR yy_c = 1;
+ YY_CHAR yy_c = 16;
if ( yy_accept[yy_current_state] )
{
yyg->yy_last_accepting_state = yy_current_state;
@@ -1524,11 +1703,11 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
- if ( yy_current_state >= 77 )
- yy_c = yy_meta[(unsigned int) yy_c];
+ if ( yy_current_state >= 81 )
+ yy_c = yy_meta[yy_c];
}
- yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c];
- yy_is_jam = (yy_current_state == 76);
+ yy_current_state = yy_nxt[yy_base[yy_current_state] + yy_c];
+ yy_is_jam = (yy_current_state == 80);
(void)yyg;
return yy_is_jam ? 0 : yy_current_state;
@@ -1605,7 +1784,7 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
else
{ /* need more input */
- int offset = yyg->yy_c_buf_p - yyg->yytext_ptr;
+ int offset = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr);
++yyg->yy_c_buf_p;
switch ( yy_get_next_buffer( yyscanner ) )
@@ -1622,13 +1801,13 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
*/
/* Reset buffer status. */
- cmListFileLexer_yyrestart(yyin ,yyscanner);
+ yyrestart( yyin , yyscanner);
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
- if ( cmListFileLexer_yywrap(yyscanner ) )
+ if ( yywrap( yyscanner ) )
return 0;
if ( ! yyg->yy_did_buffer_switch_on_eof )
@@ -1667,34 +1846,34 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @note This function does not reset the start condition to @c INITIAL .
*/
- void cmListFileLexer_yyrestart (FILE * input_file , yyscan_t yyscanner)
+ void yyrestart (FILE * input_file , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! YY_CURRENT_BUFFER ){
- cmListFileLexer_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
YY_CURRENT_BUFFER_LVALUE =
- cmListFileLexer_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner);
+ yy_create_buffer( yyin, YY_BUF_SIZE , yyscanner);
}
- cmListFileLexer_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner);
- cmListFileLexer_yy_load_buffer_state(yyscanner );
+ yy_init_buffer( YY_CURRENT_BUFFER, input_file , yyscanner);
+ yy_load_buffer_state( yyscanner );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
* @param yyscanner The scanner object.
*/
- void cmListFileLexer_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
+ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* TODO. We should be able to replace this entire function body
* with
- * cmListFileLexer_yypop_buffer_state();
- * cmListFileLexer_yypush_buffer_state(new_buffer);
+ * yypop_buffer_state();
+ * yypush_buffer_state(new_buffer);
*/
- cmListFileLexer_yyensure_buffer_stack (yyscanner);
+ yyensure_buffer_stack (yyscanner);
if ( YY_CURRENT_BUFFER == new_buffer )
return;
@@ -1707,17 +1886,17 @@ static int yy_get_next_buffer (yyscan_t yyscanner)
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
- cmListFileLexer_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
/* We don't actually know whether we did this switch during
- * EOF (cmListFileLexer_yywrap()) processing, but the only time this flag
- * is looked at is after cmListFileLexer_yywrap() is called, so it's safe
+ * EOF (yywrap()) processing, but the only time this flag
+ * is looked at is after yywrap() is called, so it's safe
* to go ahead and always set it.
*/
yyg->yy_did_buffer_switch_on_eof = 1;
}
-static void cmListFileLexer_yy_load_buffer_state (yyscan_t yyscanner)
+static void yy_load_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
@@ -1732,35 +1911,35 @@ static void cmListFileLexer_yy_load_buffer_state (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @return the allocated buffer state.
*/
- YY_BUFFER_STATE cmListFileLexer_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
+ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
- b = (YY_BUFFER_STATE) cmListFileLexer_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+ b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner );
if ( ! b )
- YY_FATAL_ERROR( "out of dynamic memory in cmListFileLexer_yy_create_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
- b->yy_buf_size = (yy_size_t)size;
+ b->yy_buf_size = size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
- b->yy_ch_buf = (char *) cmListFileLexer_yyalloc(b->yy_buf_size + 2 ,yyscanner );
+ b->yy_ch_buf = (char *) yyalloc( (yy_size_t) (b->yy_buf_size + 2) , yyscanner );
if ( ! b->yy_ch_buf )
- YY_FATAL_ERROR( "out of dynamic memory in cmListFileLexer_yy_create_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
b->yy_is_our_buffer = 1;
- cmListFileLexer_yy_init_buffer(b,file ,yyscanner);
+ yy_init_buffer( b, file , yyscanner);
return b;
}
/** Destroy the buffer.
- * @param b a buffer created with cmListFileLexer_yy_create_buffer()
+ * @param b a buffer created with yy_create_buffer()
* @param yyscanner The scanner object.
*/
- void cmListFileLexer_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
+ void yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -1771,28 +1950,28 @@ static void cmListFileLexer_yy_load_buffer_state (yyscan_t yyscanner)
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
- cmListFileLexer_yyfree((void *) b->yy_ch_buf ,yyscanner );
+ yyfree( (void *) b->yy_ch_buf , yyscanner );
- cmListFileLexer_yyfree((void *) b ,yyscanner );
+ yyfree( (void *) b , yyscanner );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
- * such as during a cmListFileLexer_yyrestart() or at EOF.
+ * such as during a yyrestart() or at EOF.
*/
- static void cmListFileLexer_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
+ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner)
{
int oerrno = errno;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
- cmListFileLexer_yy_flush_buffer(b ,yyscanner);
+ yy_flush_buffer( b , yyscanner);
b->yy_input_file = file;
b->yy_fill_buffer = 1;
- /* If b is the current buffer, then cmListFileLexer_yy_init_buffer was _probably_
- * called from cmListFileLexer_yyrestart() or through yy_get_next_buffer.
+ /* If b is the current buffer, then yy_init_buffer was _probably_
+ * called from yyrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
@@ -1809,7 +1988,7 @@ static void cmListFileLexer_yy_load_buffer_state (yyscan_t yyscanner)
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
* @param yyscanner The scanner object.
*/
- void cmListFileLexer_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
+ void yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if ( ! b )
@@ -1830,7 +2009,7 @@ static void cmListFileLexer_yy_load_buffer_state (yyscan_t yyscanner)
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
- cmListFileLexer_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
}
/** Pushes the new state onto the stack. The new state becomes
@@ -1839,15 +2018,15 @@ static void cmListFileLexer_yy_load_buffer_state (yyscan_t yyscanner)
* @param new_buffer The new state.
* @param yyscanner The scanner object.
*/
-void cmListFileLexer_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
+void yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (new_buffer == NULL)
return;
- cmListFileLexer_yyensure_buffer_stack(yyscanner);
+ yyensure_buffer_stack(yyscanner);
- /* This block is copied from cmListFileLexer_yy_switch_to_buffer. */
+ /* This block is copied from yy_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
@@ -1861,8 +2040,8 @@ void cmListFileLexer_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t
yyg->yy_buffer_stack_top++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
- /* copied from cmListFileLexer_yy_switch_to_buffer. */
- cmListFileLexer_yy_load_buffer_state(yyscanner );
+ /* copied from yy_switch_to_buffer. */
+ yy_load_buffer_state( yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
@@ -1870,19 +2049,19 @@ void cmListFileLexer_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t
* The next element becomes the new top.
* @param yyscanner The scanner object.
*/
-void cmListFileLexer_yypop_buffer_state (yyscan_t yyscanner)
+void yypop_buffer_state (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!YY_CURRENT_BUFFER)
return;
- cmListFileLexer_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner);
+ yy_delete_buffer(YY_CURRENT_BUFFER , yyscanner);
YY_CURRENT_BUFFER_LVALUE = NULL;
if (yyg->yy_buffer_stack_top > 0)
--yyg->yy_buffer_stack_top;
if (YY_CURRENT_BUFFER) {
- cmListFileLexer_yy_load_buffer_state(yyscanner );
+ yy_load_buffer_state( yyscanner );
yyg->yy_did_buffer_switch_on_eof = 1;
}
}
@@ -1890,9 +2069,9 @@ void cmListFileLexer_yypop_buffer_state (yyscan_t yyscanner)
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
-static void cmListFileLexer_yyensure_buffer_stack (yyscan_t yyscanner)
+static void yyensure_buffer_stack (yyscan_t yyscanner)
{
- int num_to_alloc;
+ yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
@@ -1902,11 +2081,11 @@ static void cmListFileLexer_yyensure_buffer_stack (yyscan_t yyscanner)
* immediate realloc on the next call.
*/
num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
- yyg->yy_buffer_stack = (struct yy_buffer_state**)cmListFileLexer_yyalloc
+ yyg->yy_buffer_stack = (struct yy_buffer_state**)yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
- YY_FATAL_ERROR( "out of dynamic memory in cmListFileLexer_yyensure_buffer_stack()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
@@ -1921,12 +2100,12 @@ static void cmListFileLexer_yyensure_buffer_stack (yyscan_t yyscanner)
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
- yyg->yy_buffer_stack = (struct yy_buffer_state**)cmListFileLexer_yyrealloc
+ yyg->yy_buffer_stack = (struct yy_buffer_state**)yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
- YY_FATAL_ERROR( "out of dynamic memory in cmListFileLexer_yyensure_buffer_stack()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
@@ -1940,7 +2119,7 @@ static void cmListFileLexer_yyensure_buffer_stack (yyscan_t yyscanner)
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
-YY_BUFFER_STATE cmListFileLexer_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
@@ -1950,11 +2129,11 @@ YY_BUFFER_STATE cmListFileLexer_yy_scan_buffer (char * base, yy_size_t size ,
/* They forgot to leave room for the EOB's. */
return NULL;
- b = (YY_BUFFER_STATE) cmListFileLexer_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner );
+ b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) , yyscanner );
if ( ! b )
- YY_FATAL_ERROR( "out of dynamic memory in cmListFileLexer_yy_scan_buffer()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
- b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
+ b->yy_buf_size = (int) (size - 2); /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = NULL;
@@ -1964,53 +2143,53 @@ YY_BUFFER_STATE cmListFileLexer_yy_scan_buffer (char * base, yy_size_t size ,
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
- cmListFileLexer_yy_switch_to_buffer(b ,yyscanner );
+ yy_switch_to_buffer( b , yyscanner );
return b;
}
-/** Setup the input buffer state to scan a string. The next call to cmListFileLexer_yylex() will
+/** Setup the input buffer state to scan a string. The next call to yylex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
- * cmListFileLexer_yy_scan_bytes() instead.
+ * yy_scan_bytes() instead.
*/
-YY_BUFFER_STATE cmListFileLexer_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_string (const char * yystr , yyscan_t yyscanner)
{
- return cmListFileLexer_yy_scan_bytes(yystr,(int) strlen(yystr) ,yyscanner);
+ return yy_scan_bytes( yystr, (int) strlen(yystr) , yyscanner);
}
-/** Setup the input buffer state to scan the given bytes. The next call to cmListFileLexer_yylex() will
+/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
* @param yyscanner The scanner object.
* @return the newly allocated buffer state object.
*/
-YY_BUFFER_STATE cmListFileLexer_yy_scan_bytes (yyconst char * yybytes, int _yybytes_len , yyscan_t yyscanner)
+YY_BUFFER_STATE yy_scan_bytes (const char * yybytes, int _yybytes_len , yyscan_t yyscanner)
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
- yy_size_t i;
+ int i;
/* Get memory for full buffer, including space for trailing EOB's. */
- n = (yy_size_t) _yybytes_len + 2;
- buf = (char *) cmListFileLexer_yyalloc(n ,yyscanner );
+ n = (yy_size_t) (_yybytes_len + 2);
+ buf = (char *) yyalloc( n , yyscanner );
if ( ! buf )
- YY_FATAL_ERROR( "out of dynamic memory in cmListFileLexer_yy_scan_bytes()" );
+ YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
- for ( i = 0; i < (size_t)_yybytes_len; ++i )
+ for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
- b = cmListFileLexer_yy_scan_buffer(buf,n ,yyscanner);
+ b = yy_scan_buffer( buf, n , yyscanner);
if ( ! b )
- YY_FATAL_ERROR( "bad buffer in cmListFileLexer_yy_scan_bytes()" );
+ YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
@@ -2024,11 +2203,11 @@ YY_BUFFER_STATE cmListFileLexer_yy_scan_bytes (yyconst char * yybytes, int _yy
#define YY_EXIT_FAILURE 2
#endif
-static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
+static void yynoreturn yy_fatal_error (const char* msg , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
- (void) fprintf( stderr, "%s\n", msg );
+ fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
@@ -2054,7 +2233,7 @@ static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner)
/** Get the user-defined data for this scanner.
* @param yyscanner The scanner object.
*/
-YY_EXTRA_TYPE cmListFileLexer_yyget_extra (yyscan_t yyscanner)
+YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyextra;
@@ -2063,7 +2242,7 @@ YY_EXTRA_TYPE cmListFileLexer_yyget_extra (yyscan_t yyscanner)
/** Get the current line number.
* @param yyscanner The scanner object.
*/
-int cmListFileLexer_yyget_lineno (yyscan_t yyscanner)
+int yyget_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -2076,7 +2255,7 @@ int cmListFileLexer_yyget_lineno (yyscan_t yyscanner)
/** Get the current column number.
* @param yyscanner The scanner object.
*/
-int cmListFileLexer_yyget_column (yyscan_t yyscanner)
+int yyget_column (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
@@ -2089,7 +2268,7 @@ int cmListFileLexer_yyget_column (yyscan_t yyscanner)
/** Get the input stream.
* @param yyscanner The scanner object.
*/
-FILE *cmListFileLexer_yyget_in (yyscan_t yyscanner)
+FILE *yyget_in (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyin;
@@ -2098,7 +2277,7 @@ FILE *cmListFileLexer_yyget_in (yyscan_t yyscanner)
/** Get the output stream.
* @param yyscanner The scanner object.
*/
-FILE *cmListFileLexer_yyget_out (yyscan_t yyscanner)
+FILE *yyget_out (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyout;
@@ -2107,7 +2286,7 @@ FILE *cmListFileLexer_yyget_out (yyscan_t yyscanner)
/** Get the length of the current token.
* @param yyscanner The scanner object.
*/
-int cmListFileLexer_yyget_leng (yyscan_t yyscanner)
+int yyget_leng (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yyleng;
@@ -2117,7 +2296,7 @@ int cmListFileLexer_yyget_leng (yyscan_t yyscanner)
* @param yyscanner The scanner object.
*/
-char *cmListFileLexer_yyget_text (yyscan_t yyscanner)
+char *yyget_text (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yytext;
@@ -2127,7 +2306,7 @@ char *cmListFileLexer_yyget_text (yyscan_t yyscanner)
* @param user_defined The data to be associated with this scanner.
* @param yyscanner The scanner object.
*/
-void cmListFileLexer_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
+void yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyextra = user_defined ;
@@ -2137,13 +2316,13 @@ void cmListFileLexer_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscann
* @param _line_number line number
* @param yyscanner The scanner object.
*/
-void cmListFileLexer_yyset_lineno (int _line_number , yyscan_t yyscanner)
+void yyset_lineno (int _line_number , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* lineno is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
- YY_FATAL_ERROR( "cmListFileLexer_yyset_lineno called with no buffer" );
+ YY_FATAL_ERROR( "yyset_lineno called with no buffer" );
yylineno = _line_number;
}
@@ -2152,13 +2331,13 @@ void cmListFileLexer_yyset_lineno (int _line_number , yyscan_t yyscanner)
* @param _column_no column number
* @param yyscanner The scanner object.
*/
-void cmListFileLexer_yyset_column (int _column_no , yyscan_t yyscanner)
+void yyset_column (int _column_no , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* column is only valid if an input buffer exists. */
if (! YY_CURRENT_BUFFER )
- YY_FATAL_ERROR( "cmListFileLexer_yyset_column called with no buffer" );
+ YY_FATAL_ERROR( "yyset_column called with no buffer" );
yycolumn = _column_no;
}
@@ -2167,27 +2346,27 @@ void cmListFileLexer_yyset_column (int _column_no , yyscan_t yyscanner)
* input buffer.
* @param _in_str A readable stream.
* @param yyscanner The scanner object.
- * @see cmListFileLexer_yy_switch_to_buffer
+ * @see yy_switch_to_buffer
*/
-void cmListFileLexer_yyset_in (FILE * _in_str , yyscan_t yyscanner)
+void yyset_in (FILE * _in_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyin = _in_str ;
}
-void cmListFileLexer_yyset_out (FILE * _out_str , yyscan_t yyscanner)
+void yyset_out (FILE * _out_str , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yyout = _out_str ;
}
-int cmListFileLexer_yyget_debug (yyscan_t yyscanner)
+int yyget_debug (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
return yy_flex_debug;
}
-void cmListFileLexer_yyset_debug (int _bdebug , yyscan_t yyscanner)
+void yyset_debug (int _bdebug , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
yy_flex_debug = _bdebug ;
@@ -2197,20 +2376,18 @@ void cmListFileLexer_yyset_debug (int _bdebug , yyscan_t yyscanner)
/* User-visible API */
-/* cmListFileLexer_yylex_init is special because it creates the scanner itself, so it is
+/* yylex_init is special because it creates the scanner itself, so it is
* the ONLY reentrant function that doesn't take the scanner as the last argument.
* That's why we explicitly handle the declaration, instead of using our macros.
*/
-
-int cmListFileLexer_yylex_init(yyscan_t* ptr_yy_globals)
-
+int yylex_init(yyscan_t* ptr_yy_globals)
{
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
- *ptr_yy_globals = (yyscan_t) cmListFileLexer_yyalloc ( sizeof( struct yyguts_t ), NULL );
+ *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), NULL );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
@@ -2223,27 +2400,25 @@ int cmListFileLexer_yylex_init(yyscan_t* ptr_yy_globals)
return yy_init_globals ( *ptr_yy_globals );
}
-/* cmListFileLexer_yylex_init_extra has the same functionality as cmListFileLexer_yylex_init, but follows the
+/* yylex_init_extra has the same functionality as yylex_init, but follows the
* convention of taking the scanner as the last argument. Note however, that
* this is a *pointer* to a scanner, as it will be allocated by this call (and
* is the reason, too, why this function also must handle its own declaration).
- * The user defined value in the first argument will be available to cmListFileLexer_yyalloc in
+ * The user defined value in the first argument will be available to yyalloc in
* the yyextra field.
*/
-
-int cmListFileLexer_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals )
-
+int yylex_init_extra( YY_EXTRA_TYPE yy_user_defined, yyscan_t* ptr_yy_globals )
{
struct yyguts_t dummy_yyguts;
- cmListFileLexer_yyset_extra (yy_user_defined, &dummy_yyguts);
+ yyset_extra (yy_user_defined, &dummy_yyguts);
if (ptr_yy_globals == NULL){
errno = EINVAL;
return 1;
}
- *ptr_yy_globals = (yyscan_t) cmListFileLexer_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
+ *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts );
if (*ptr_yy_globals == NULL){
errno = ENOMEM;
@@ -2254,7 +2429,7 @@ int cmListFileLexer_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr
yy_init_globals. Leave at 0x00 for releases. */
memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t));
- cmListFileLexer_yyset_extra (yy_user_defined, *ptr_yy_globals);
+ yyset_extra (yy_user_defined, *ptr_yy_globals);
return yy_init_globals ( *ptr_yy_globals );
}
@@ -2263,7 +2438,7 @@ static int yy_init_globals (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Initialization is the same as for the non-reentrant scanner.
- * This function is called from cmListFileLexer_yylex_destroy(), so don't allocate here.
+ * This function is called from yylex_destroy(), so don't allocate here.
*/
yyg->yy_buffer_stack = NULL;
@@ -2287,37 +2462,37 @@ static int yy_init_globals (yyscan_t yyscanner)
#endif
/* For future reference: Set errno on error, since we are called by
- * cmListFileLexer_yylex_init()
+ * yylex_init()
*/
return 0;
}
-/* cmListFileLexer_yylex_destroy is for both reentrant and non-reentrant scanners. */
-int cmListFileLexer_yylex_destroy (yyscan_t yyscanner)
+/* yylex_destroy is for both reentrant and non-reentrant scanners. */
+int yylex_destroy (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
- cmListFileLexer_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner );
+ yy_delete_buffer( YY_CURRENT_BUFFER , yyscanner );
YY_CURRENT_BUFFER_LVALUE = NULL;
- cmListFileLexer_yypop_buffer_state(yyscanner);
+ yypop_buffer_state(yyscanner);
}
/* Destroy the stack itself. */
- cmListFileLexer_yyfree(yyg->yy_buffer_stack ,yyscanner);
+ yyfree(yyg->yy_buffer_stack , yyscanner);
yyg->yy_buffer_stack = NULL;
/* Destroy the start condition stack. */
- cmListFileLexer_yyfree(yyg->yy_start_stack ,yyscanner );
+ yyfree( yyg->yy_start_stack , yyscanner );
yyg->yy_start_stack = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
- * cmListFileLexer_yylex() is called, initialization will occur. */
+ * yylex() is called, initialization will occur. */
yy_init_globals( yyscanner);
/* Destroy the main struct (reentrant only). */
- cmListFileLexer_yyfree ( yyscanner , yyscanner );
+ yyfree ( yyscanner , yyscanner );
yyscanner = NULL;
return 0;
}
@@ -2327,7 +2502,7 @@ int cmListFileLexer_yylex_destroy (yyscan_t yyscanner)
*/
#ifndef yytext_ptr
-static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner)
+static void yy_flex_strncpy (char* s1, const char * s2, int n , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
@@ -2339,7 +2514,7 @@ static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yysca
#endif
#ifdef YY_NEED_STRLEN
-static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
+static int yy_flex_strlen (const char * s , yyscan_t yyscanner)
{
int n;
for ( n = 0; s[n]; ++n )
@@ -2349,14 +2524,14 @@ static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner)
}
#endif
-void *cmListFileLexer_yyalloc (yy_size_t size , yyscan_t yyscanner)
+void *yyalloc (yy_size_t size , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
return malloc(size);
}
-void *cmListFileLexer_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
+void *yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
@@ -2371,19 +2546,15 @@ void *cmListFileLexer_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscann
return realloc(ptr, size);
}
-void cmListFileLexer_yyfree (void * ptr , yyscan_t yyscanner)
+void yyfree (void * ptr , yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
(void)yyg;
- free( (char *) ptr ); /* see cmListFileLexer_yyrealloc() for (char *) cast */
+ free( (char *) ptr ); /* see yyrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
-#line 265 "cmListFileLexer.in.l"
-
-
-
/*--------------------------------------------------------------------------*/
static void cmListFileLexerSetToken(cmListFileLexer* lexer, const char* text,
int length)
diff --git a/Source/LexerParser/cmListFileLexer.in.l b/Source/LexerParser/cmListFileLexer.in.l
index 5152dbf08..f2fd5389d 100644
--- a/Source/LexerParser/cmListFileLexer.in.l
+++ b/Source/LexerParser/cmListFileLexer.in.l
@@ -7,14 +7,12 @@ This file must be translated to C and modified to build everywhere.
Run flex >= 2.6 like this:
- flex --nounistd -DFLEXINT_H --prefix=cmListFileLexer_yy -ocmListFileLexer.c cmListFileLexer.in.l
+ flex --nounistd -DFLEXINT_H --noline -ocmListFileLexer.c cmListFileLexer.in.l
Modify cmListFileLexer.c:
- - remove trailing whitespace: sed -i 's/\s*$//' cmListFileLexer.c
- - remove blank lines at end of file
- - #include "cmStandardLexer.h" at the top
- - add cast in yy_scan_bytes for loop condition of _yybytes_len to size_t
- - change type of variable yyl under yy_find_action from yy_size_t to int
+ - remove trailing whitespace: sed -i 's/\s*$//' cmListFileLexer.c
+ - remove blank lines at end of file: sed -i '${/^$/d;}' cmListFileLexer.c
+ - #include "cmStandardLexer.h" at the top: sed -i '1i#include "cmStandardLexer.h"' cmListFileLexer.c
*/
@@ -64,6 +62,8 @@ static void cmListFileLexerDestroy(cmListFileLexer* lexer);
/*--------------------------------------------------------------------------*/
%}
+%option prefix="cmListFileLexer_yy"
+
%option reentrant
%option yylineno
%option noyywrap
@@ -74,7 +74,7 @@ static void cmListFileLexerDestroy(cmListFileLexer* lexer);
%x COMMENT
MAKEVAR \$\([A-Za-z0-9_]*\)
-UNQUOTED ([^ \t\r\n\(\)#\\\"[=]|\\.)
+UNQUOTED ([^ \0\t\r\n\(\)#\\\"[=]|\\.)
LEGACY {MAKEVAR}|{UNQUOTED}|\"({MAKEVAR}|{UNQUOTED}|[ \t[=])*\"
%%
@@ -113,7 +113,7 @@ LEGACY {MAKEVAR}|{UNQUOTED}|\"({MAKEVAR}|{UNQUOTED}|[ \t[=])*\"
BEGIN(COMMENT);
}
-<COMMENT>.* {
+<COMMENT>[^\0\n]* {
lexer->column += yyleng;
}
@@ -168,7 +168,7 @@ LEGACY {MAKEVAR}|{UNQUOTED}|\"({MAKEVAR}|{UNQUOTED}|[ \t[=])*\"
BEGIN(BRACKET);
}
-<BRACKET,BRACKETEND>. {
+<BRACKET,BRACKETEND>[^\0\n] {
cmListFileLexerAppend(lexer, yytext, yyleng);
lexer->column += yyleng;
BEGIN(BRACKET);
@@ -231,7 +231,7 @@ LEGACY {MAKEVAR}|{UNQUOTED}|\"({MAKEVAR}|{UNQUOTED}|[ \t[=])*\"
return 1;
}
-<STRING>. {
+<STRING>[^\0\n] {
cmListFileLexerAppend(lexer, yytext, yyleng);
lexer->column += yyleng;
}
@@ -439,11 +439,15 @@ static cmListFileLexer_BOM cmListFileLexer_ReadBOM(FILE* f)
if (fread(b, 1, 2, f) == 2 && b[0] == 0 && b[1] == 0) {
return cmListFileLexer_BOM_UTF32LE;
}
- fsetpos(f, &p);
+ if (fsetpos(f, &p) != 0) {
+ return cmListFileLexer_BOM_Broken;
+ }
return cmListFileLexer_BOM_UTF16LE;
}
}
- rewind(f);
+ if (fseek(f, 0, SEEK_SET) != 0) {
+ return cmListFileLexer_BOM_Broken;
+ }
return cmListFileLexer_BOM_None;
}
diff --git a/Source/QtDialog/CMakeLists.txt b/Source/QtDialog/CMakeLists.txt
index 9e9df781e..b38797bca 100644
--- a/Source/QtDialog/CMakeLists.txt
+++ b/Source/QtDialog/CMakeLists.txt
@@ -33,6 +33,12 @@ if (Qt5Widgets_FOUND)
PROPERTY COMPILE_DEFINITIONS USE_QXcbIntegrationPlugin)
endif()
+ if(CMake_QT_STATIC_QWindowsIntegrationPlugin_LIBRARIES)
+ list(APPEND CMake_QT_LIBRARIES ${CMake_QT_STATIC_QWindowsIntegrationPlugin_LIBRARIES})
+ set_property(SOURCE CMakeSetup.cxx
+ PROPERTY COMPILE_DEFINITIONS USE_QWindowsIntegrationPlugin)
+ endif()
+
# We need to install platform plugin and add qt.conf for Qt5 on Mac and Windows.
# FIXME: This should be part of Qt5 CMake scripts, but unfortunatelly
# Qt5 support is missing there.
@@ -65,7 +71,7 @@ if (Qt5Widgets_FOUND)
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/qt.conf"
DESTINATION "${CMAKE_INSTALL_PREFIX}/Resources"
${COMPONENT})
- elseif(WIN32)
+ elseif(WIN32 AND NOT CMake_QT_STATIC_QWindowsIntegrationPlugin_LIBRARIES)
install_qt5_plugin("Qt5::QWindowsIntegrationPlugin" QT_PLUGINS)
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/qt.conf"
"[Paths]\nPlugins = ../${_qt_plugin_dir}\n")
diff --git a/Source/QtDialog/CMakeSetup.cxx b/Source/QtDialog/CMakeSetup.cxx
index 7fa2ac661..bfd43cfde 100644
--- a/Source/QtDialog/CMakeSetup.cxx
+++ b/Source/QtDialog/CMakeSetup.cxx
@@ -22,19 +22,18 @@
#include "cmSystemTools.h" // IWYU pragma: keep
-static const char* cmDocumentationName[][2] = { { CM_NULLPTR,
+static const char* cmDocumentationName[][2] = { { nullptr,
" cmake-gui - CMake GUI." },
- { CM_NULLPTR, CM_NULLPTR } };
+ { nullptr, nullptr } };
static const char* cmDocumentationUsage[][2] = {
- { CM_NULLPTR, " cmake-gui [options]\n"
- " cmake-gui [options] <path-to-source>\n"
- " cmake-gui [options] <path-to-existing-build>" },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, " cmake-gui [options]\n"
+ " cmake-gui [options] <path-to-source>\n"
+ " cmake-gui [options] <path-to-existing-build>" },
+ { nullptr, nullptr }
};
-static const char* cmDocumentationOptions[]
- [2] = { { CM_NULLPTR, CM_NULLPTR } };
+static const char* cmDocumentationOptions[][2] = { { nullptr, nullptr } };
#if defined(Q_OS_MAC)
static int cmOSXInstall(std::string dir);
@@ -45,6 +44,10 @@ static void cmAddPluginPath();
Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
#endif
+#if defined(USE_QWindowsIntegrationPlugin)
+Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
+#endif
+
int main(int argc, char** argv)
{
cmsys::Encoding::CommandLineArguments encoding_args =
@@ -93,6 +96,10 @@ int main(int argc, char** argv)
cmAddPluginPath();
#endif
+#if QT_VERSION >= 0x050600
+ QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
+#endif
+
QApplication app(argc, argv);
setlocale(LC_NUMERIC, "C");
diff --git a/Source/QtDialog/CMakeSetupDialog.cxx b/Source/QtDialog/CMakeSetupDialog.cxx
index 57f8e107e..bbb2395b2 100644
--- a/Source/QtDialog/CMakeSetupDialog.cxx
+++ b/Source/QtDialog/CMakeSetupDialog.cxx
@@ -32,7 +32,7 @@
QCMakeThread::QCMakeThread(QObject* p)
: QThread(p)
- , CMakeInstance(CM_NULLPTR)
+ , CMakeInstance(nullptr)
{
}
@@ -48,7 +48,7 @@ void QCMakeThread::run()
emit this->cmakeInitialized();
this->exec();
delete this->CMakeInstance;
- this->CMakeInstance = CM_NULLPTR;
+ this->CMakeInstance = nullptr;
}
CMakeSetupDialog::CMakeSetupDialog()
@@ -1195,7 +1195,7 @@ void CMakeSetupDialog::setSearchFilter(const QString& str)
this->CacheValues->setSearchFilter(str);
}
-void CMakeSetupDialog::doOutputContextMenu(const QPoint& pt)
+void CMakeSetupDialog::doOutputContextMenu(QPoint pt)
{
QMenu* menu = this->Output->createStandardContextMenu();
diff --git a/Source/QtDialog/CMakeSetupDialog.h b/Source/QtDialog/CMakeSetupDialog.h
index 1abdb462d..0da28d813 100644
--- a/Source/QtDialog/CMakeSetupDialog.h
+++ b/Source/QtDialog/CMakeSetupDialog.h
@@ -70,7 +70,7 @@ protected slots:
bool doConfigureInternal();
bool doGenerateInternal();
void exitLoop(int);
- void doOutputContextMenu(const QPoint&);
+ void doOutputContextMenu(QPoint pt);
void doOutputFindDialog();
void doOutputFindNext(bool directionForward = true);
void doOutputFindPrev();
diff --git a/Source/QtDialog/Compilers.h b/Source/QtDialog/Compilers.h
index 6c8c8f52a..746266cbb 100644
--- a/Source/QtDialog/Compilers.h
+++ b/Source/QtDialog/Compilers.h
@@ -3,7 +3,7 @@
#ifndef COMPILERS_HPP
#define COMPILERS_HPP
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <QWidget>
@@ -13,7 +13,7 @@ class Compilers : public QWidget, public Ui::Compilers
{
Q_OBJECT
public:
- Compilers(QWidget* p = CM_NULLPTR)
+ Compilers(QWidget* p = nullptr)
: QWidget(p)
{
this->setupUi(this);
diff --git a/Source/QtDialog/FirstConfigure.cxx b/Source/QtDialog/FirstConfigure.cxx
index b193a2782..88ce7cb8a 100644
--- a/Source/QtDialog/FirstConfigure.cxx
+++ b/Source/QtDialog/FirstConfigure.cxx
@@ -301,7 +301,7 @@ QString CrossCompilerSetup::getFindRoot() const
void CrossCompilerSetup::setFindRoot(const QString& t)
{
- return this->crossFindRoot->setText(t);
+ this->crossFindRoot->setText(t);
}
int CrossCompilerSetup::getProgramMode() const
diff --git a/Source/QtDialog/QCMake.h b/Source/QtDialog/QCMake.h
index e14cdf2c9..3b8cea721 100644
--- a/Source/QtDialog/QCMake.h
+++ b/Source/QtDialog/QCMake.h
@@ -3,7 +3,7 @@
#ifndef QCMake_h
#define QCMake_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmake.h"
@@ -63,7 +63,7 @@ class QCMake : public QObject
{
Q_OBJECT
public:
- QCMake(QObject* p = CM_NULLPTR);
+ QCMake(QObject* p = nullptr);
~QCMake();
public slots:
/// load the cache file in a directory
diff --git a/Source/QtDialog/QCMakeCacheView.cxx b/Source/QtDialog/QCMakeCacheView.cxx
index 08c2d58d5..1b3fb1583 100644
--- a/Source/QtDialog/QCMakeCacheView.cxx
+++ b/Source/QtDialog/QCMakeCacheView.cxx
@@ -23,7 +23,7 @@ public:
}
protected:
- bool filterAcceptsRow(int row, const QModelIndex& p) const CM_OVERRIDE
+ bool filterAcceptsRow(int row, const QModelIndex& p) const override
{
QStringList strs;
const QAbstractItemModel* m = this->sourceModel();
@@ -77,7 +77,7 @@ public:
protected:
bool ShowAdvanced;
- bool filterAcceptsRow(int row, const QModelIndex& p) const CM_OVERRIDE
+ bool filterAcceptsRow(int row, const QModelIndex& p) const override
{
const QAbstractItemModel* m = this->sourceModel();
QModelIndex idx = m->index(row, 0, p);
@@ -539,7 +539,7 @@ QWidget* QCMakeCacheModelDelegate::createEditor(
QModelIndex var = idx.sibling(idx.row(), 0);
int type = var.data(QCMakeCacheModel::TypeRole).toInt();
if (type == QCMakeProperty::BOOL) {
- return CM_NULLPTR;
+ return nullptr;
}
if (type == QCMakeProperty::PATH) {
QCMakePathEditor* editor =
@@ -642,7 +642,7 @@ QSize QCMakeCacheModelDelegate::sizeHint(const QStyleOptionViewItem& option,
QStyleOptionButton opt;
opt.QStyleOption::operator=(option);
sz = sz.expandedTo(
- style->subElementRect(QStyle::SE_ViewItemCheckIndicator, &opt, CM_NULLPTR)
+ style->subElementRect(QStyle::SE_ViewItemCheckIndicator, &opt, nullptr)
.size());
return sz;
diff --git a/Source/QtDialog/QCMakeWidgets.cxx b/Source/QtDialog/QCMakeWidgets.cxx
index 7f0cafa37..b544b8613 100644
--- a/Source/QtDialog/QCMakeWidgets.cxx
+++ b/Source/QtDialog/QCMakeWidgets.cxx
@@ -57,7 +57,7 @@ void QCMakeFilePathEditor::chooseFile()
emit this->fileDialogExists(true);
path =
QFileDialog::getOpenFileName(this, title, info.absolutePath(), QString(),
- CM_NULLPTR, QFileDialog::DontResolveSymlinks);
+ nullptr, QFileDialog::DontResolveSymlinks);
emit this->fileDialogExists(false);
if (!path.isEmpty()) {
@@ -89,7 +89,7 @@ void QCMakePathEditor::chooseFile()
// use same QDirModel for all completers
static QDirModel* fileDirModel()
{
- static QDirModel* m = CM_NULLPTR;
+ static QDirModel* m = nullptr;
if (!m) {
m = new QDirModel();
}
@@ -97,7 +97,7 @@ static QDirModel* fileDirModel()
}
static QDirModel* pathDirModel()
{
- static QDirModel* m = CM_NULLPTR;
+ static QDirModel* m = nullptr;
if (!m) {
m = new QDirModel();
m->setFilter(QDir::AllDirs | QDir::Drives | QDir::NoDotAndDotDot);
diff --git a/Source/QtDialog/QCMakeWidgets.h b/Source/QtDialog/QCMakeWidgets.h
index 1ec666ff6..e63c19753 100644
--- a/Source/QtDialog/QCMakeWidgets.h
+++ b/Source/QtDialog/QCMakeWidgets.h
@@ -3,7 +3,7 @@
#ifndef QCMakeWidgets_h
#define QCMakeWidgets_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <QComboBox>
#include <QCompleter>
@@ -35,7 +35,7 @@ class QCMakePathEditor : public QCMakeFileEditor
{
Q_OBJECT
public:
- QCMakePathEditor(QWidget* p = CM_NULLPTR, const QString& var = QString());
+ QCMakePathEditor(QWidget* p = nullptr, const QString& var = QString());
void chooseFile();
};
@@ -44,8 +44,7 @@ class QCMakeFilePathEditor : public QCMakeFileEditor
{
Q_OBJECT
public:
- QCMakeFilePathEditor(QWidget* p = CM_NULLPTR,
- const QString& var = QString());
+ QCMakeFilePathEditor(QWidget* p = nullptr, const QString& var = QString());
void chooseFile();
};
diff --git a/Source/bindexplib.cxx b/Source/bindexplib.cxx
index e96226a4b..2eb47f3e9 100644
--- a/Source/bindexplib.cxx
+++ b/Source/bindexplib.cxx
@@ -218,7 +218,7 @@ public:
* The name of the Function entry points
*/
if (pSymbolTable->N.Name.Short != 0) {
- symbol = "";
+ symbol.clear();
symbol.insert(0, (const char*)pSymbolTable->N.ShortName, 8);
} else {
symbol = stringTable + pSymbolTable->N.Name.Long;
@@ -394,12 +394,10 @@ bool bindexplib::AddDefinitionFile(const char* filename)
void bindexplib::WriteFile(FILE* file)
{
fprintf(file, "EXPORTS \n");
- for (std::set<std::string>::const_iterator i = this->DataSymbols.begin();
- i != this->DataSymbols.end(); ++i) {
- fprintf(file, "\t%s \t DATA\n", i->c_str());
+ for (std::string const& ds : this->DataSymbols) {
+ fprintf(file, "\t%s \t DATA\n", ds.c_str());
}
- for (std::set<std::string>::const_iterator i = this->Symbols.begin();
- i != this->Symbols.end(); ++i) {
- fprintf(file, "\t%s\n", i->c_str());
+ for (std::string const& s : this->Symbols) {
+ fprintf(file, "\t%s\n", s.c_str());
}
}
diff --git a/Source/bindexplib.h b/Source/bindexplib.h
index bc904e9f8..3e22ac78e 100644
--- a/Source/bindexplib.h
+++ b/Source/bindexplib.h
@@ -3,7 +3,7 @@
#ifndef bindexplib_h
#define bindexplib_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <set>
#include <stdio.h>
diff --git a/Source/cmAddCompileOptionsCommand.cxx b/Source/cmAddCompileOptionsCommand.cxx
index 21a8012d8..c37fd9a39 100644
--- a/Source/cmAddCompileOptionsCommand.cxx
+++ b/Source/cmAddCompileOptionsCommand.cxx
@@ -13,9 +13,8 @@ bool cmAddCompileOptionsCommand::InitialPass(
return true;
}
- for (std::vector<std::string>::const_iterator i = args.begin();
- i != args.end(); ++i) {
- this->Makefile->AddCompileOption(i->c_str());
+ for (std::string const& i : args) {
+ this->Makefile->AddCompileOption(i.c_str());
}
return true;
}
diff --git a/Source/cmAddCompileOptionsCommand.h b/Source/cmAddCompileOptionsCommand.h
index 297f901db..3d53d097b 100644
--- a/Source/cmAddCompileOptionsCommand.h
+++ b/Source/cmAddCompileOptionsCommand.h
@@ -3,7 +3,7 @@
#ifndef cmAddCompileOptionsCommand_h
#define cmAddCompileOptionsCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -18,14 +18,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmAddCompileOptionsCommand; }
+ cmCommand* Clone() override { return new cmAddCompileOptionsCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmAddCustomCommandCommand.cxx b/Source/cmAddCustomCommandCommand.cxx
index b5e7c9ea9..7fed52db5 100644
--- a/Source/cmAddCustomCommandCommand.cxx
+++ b/Source/cmAddCustomCommandCommand.cxx
@@ -31,7 +31,7 @@ bool cmAddCustomCommandCommand::InitialPass(
std::string source, target, main_dependency, working, depfile;
std::string comment_buffer;
- const char* comment = CM_NULLPTR;
+ const char* comment = nullptr;
std::vector<std::string> depends, outputs, output, byproducts;
bool verbatim = false;
bool append = false;
@@ -68,9 +68,7 @@ bool cmAddCustomCommandCommand::InitialPass(
tdoing doing = doing_nothing;
- for (unsigned int j = 0; j < args.size(); ++j) {
- std::string const& copy = args[j];
-
+ for (std::string const& copy : args) {
if (copy == "SOURCE") {
doing = doing_source;
} else if (copy == "COMMAND") {
@@ -355,12 +353,11 @@ bool cmAddCustomCommandCommand::InitialPass(
bool cmAddCustomCommandCommand::CheckOutputs(
const std::vector<std::string>& outputs)
{
- for (std::vector<std::string>::const_iterator o = outputs.begin();
- o != outputs.end(); ++o) {
+ for (std::string const& o : outputs) {
// Make sure the file will not be generated into the source
// directory during an out of source build.
- if (!this->Makefile->CanIWriteThisFile(o->c_str())) {
- std::string e = "attempted to have a file \"" + *o +
+ if (!this->Makefile->CanIWriteThisFile(o.c_str())) {
+ std::string e = "attempted to have a file \"" + o +
"\" in a source directory as an output of custom command.";
this->SetError(e);
cmSystemTools::SetFatalErrorOccured();
@@ -368,10 +365,10 @@ bool cmAddCustomCommandCommand::CheckOutputs(
}
// Make sure the output file name has no invalid characters.
- std::string::size_type pos = o->find_first_of("#<>");
+ std::string::size_type pos = o.find_first_of("#<>");
if (pos != std::string::npos) {
std::ostringstream msg;
- msg << "called with OUTPUT containing a \"" << (*o)[pos]
+ msg << "called with OUTPUT containing a \"" << o[pos]
<< "\". This character is not allowed.";
this->SetError(msg.str());
return false;
diff --git a/Source/cmAddCustomCommandCommand.h b/Source/cmAddCustomCommandCommand.h
index c3a91b2a3..6af4f1055 100644
--- a/Source/cmAddCustomCommandCommand.h
+++ b/Source/cmAddCustomCommandCommand.h
@@ -3,7 +3,7 @@
#ifndef cmAddCustomCommandCommand_h
#define cmAddCustomCommandCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmAddCustomCommandCommand; }
+ cmCommand* Clone() override { return new cmAddCustomCommandCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
protected:
bool CheckOutputs(const std::vector<std::string>& outputs);
diff --git a/Source/cmAddCustomTargetCommand.cxx b/Source/cmAddCustomTargetCommand.cxx
index 87e114780..a8d5b2edd 100644
--- a/Source/cmAddCustomTargetCommand.cxx
+++ b/Source/cmAddCustomTargetCommand.cxx
@@ -49,7 +49,7 @@ bool cmAddCustomTargetCommand::InitialPass(
bool uses_terminal = false;
bool command_expand_lists = false;
std::string comment_buffer;
- const char* comment = CM_NULLPTR;
+ const char* comment = nullptr;
std::vector<std::string> sources;
// Keep track of parser state.
diff --git a/Source/cmAddCustomTargetCommand.h b/Source/cmAddCustomTargetCommand.h
index 7229c2779..1a55116e3 100644
--- a/Source/cmAddCustomTargetCommand.h
+++ b/Source/cmAddCustomTargetCommand.h
@@ -3,7 +3,7 @@
#ifndef cmAddCustomTargetCommand_h
#define cmAddCustomTargetCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -25,14 +25,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmAddCustomTargetCommand; }
+ cmCommand* Clone() override { return new cmAddCustomTargetCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmAddDefinitionsCommand.cxx b/Source/cmAddDefinitionsCommand.cxx
index 9e0607c60..261fb5baa 100644
--- a/Source/cmAddDefinitionsCommand.cxx
+++ b/Source/cmAddDefinitionsCommand.cxx
@@ -15,9 +15,8 @@ bool cmAddDefinitionsCommand::InitialPass(std::vector<std::string> const& args,
return true;
}
- for (std::vector<std::string>::const_iterator i = args.begin();
- i != args.end(); ++i) {
- this->Makefile->AddDefineFlag(i->c_str());
+ for (std::string const& i : args) {
+ this->Makefile->AddDefineFlag(i.c_str());
}
return true;
}
diff --git a/Source/cmAddDefinitionsCommand.h b/Source/cmAddDefinitionsCommand.h
index abf5a5964..7b75638cb 100644
--- a/Source/cmAddDefinitionsCommand.h
+++ b/Source/cmAddDefinitionsCommand.h
@@ -3,7 +3,7 @@
#ifndef cmAddDefinitionsCommand_h
#define cmAddDefinitionsCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmAddDefinitionsCommand; }
+ cmCommand* Clone() override { return new cmAddDefinitionsCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmAddDependenciesCommand.h b/Source/cmAddDependenciesCommand.h
index c7328d63e..e10df7109 100644
--- a/Source/cmAddDependenciesCommand.h
+++ b/Source/cmAddDependenciesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmDependenciessCommand_h
#define cmDependenciessCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmAddDependenciesCommand; }
+ cmCommand* Clone() override { return new cmAddDependenciesCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmAddExecutableCommand.h b/Source/cmAddExecutableCommand.h
index 8100da185..bdf607d8d 100644
--- a/Source/cmAddExecutableCommand.h
+++ b/Source/cmAddExecutableCommand.h
@@ -3,7 +3,7 @@
#ifndef cmExecutablesCommand_h
#define cmExecutablesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmAddExecutableCommand; }
+ cmCommand* Clone() override { return new cmAddExecutableCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmAddLibraryCommand.h b/Source/cmAddLibraryCommand.h
index df49fae93..aa212611d 100644
--- a/Source/cmAddLibraryCommand.h
+++ b/Source/cmAddLibraryCommand.h
@@ -3,7 +3,7 @@
#ifndef cmLibrarysCommand_h
#define cmLibrarysCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmAddLibraryCommand; }
+ cmCommand* Clone() override { return new cmAddLibraryCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmAddSubDirectoryCommand.h b/Source/cmAddSubDirectoryCommand.h
index 0e71ffd85..0ea442329 100644
--- a/Source/cmAddSubDirectoryCommand.h
+++ b/Source/cmAddSubDirectoryCommand.h
@@ -3,7 +3,7 @@
#ifndef cmAddSubDirectoryCommand_h
#define cmAddSubDirectoryCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -25,14 +25,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmAddSubDirectoryCommand; }
+ cmCommand* Clone() override { return new cmAddSubDirectoryCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmAddTestCommand.h b/Source/cmAddTestCommand.h
index a098a03f1..bea3f3d5d 100644
--- a/Source/cmAddTestCommand.h
+++ b/Source/cmAddTestCommand.h
@@ -3,7 +3,7 @@
#ifndef cmAddTestCommand_h
#define cmAddTestCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmAddTestCommand; }
+ cmCommand* Clone() override { return new cmAddTestCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
bool HandleNameMode(std::vector<std::string> const& args);
diff --git a/Source/cmAlgorithms.h b/Source/cmAlgorithms.h
index 4adfe2328..69d0ed6a4 100644
--- a/Source/cmAlgorithms.h
+++ b/Source/cmAlgorithms.h
@@ -9,6 +9,7 @@
#include <algorithm>
#include <functional>
#include <iterator>
+#include <memory>
#include <sstream>
#include <string.h>
#include <string>
@@ -119,7 +120,7 @@ struct cmIsPair
};
template <typename K, typename V>
-struct cmIsPair<std::pair<K, V> >
+struct cmIsPair<std::pair<K, V>>
{
enum
{
@@ -369,8 +370,7 @@ std::string cmWrap(char prefix, Range const& r, char suffix,
template <typename Range, typename T>
typename Range::const_iterator cmFindNot(Range const& r, T const& t)
{
- return std::find_if(r.begin(), r.end(),
- std::bind1st(std::not_equal_to<T>(), t));
+ return std::find_if(r.begin(), r.end(), [&t](T const& i) { return i != t; });
}
template <typename Range>
@@ -402,4 +402,22 @@ inline void cmStripSuffixIfExists(std::string& str, const std::string& suffix)
}
}
+namespace cm {
+
+#if defined(CMake_HAVE_CXX_MAKE_UNIQUE)
+
+using std::make_unique;
+
+#else
+
+template <typename T, typename... Args>
+std::unique_ptr<T> make_unique(Args&&... args)
+{
+ return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
+}
+
+#endif
+
+} // namespace cm
+
#endif
diff --git a/Source/cmArchiveWrite.cxx b/Source/cmArchiveWrite.cxx
index 0f13b114f..02408a1e8 100644
--- a/Source/cmArchiveWrite.cxx
+++ b/Source/cmArchiveWrite.cxx
@@ -146,9 +146,9 @@ cmArchiveWrite::cmArchiveWrite(std::ostream& os, Compress c,
}
if (archive_write_open(
- this->Archive, this, CM_NULLPTR,
+ this->Archive, this, nullptr,
reinterpret_cast<archive_write_callback*>(&Callback::Write),
- CM_NULLPTR) != ARCHIVE_OK) {
+ nullptr) != ARCHIVE_OK) {
this->Error = "archive_write_open: ";
this->Error += cm_archive_error_string(this->Archive);
return;
@@ -224,7 +224,7 @@ bool cmArchiveWrite::AddFile(const char* file, size_t skip, const char* prefix)
Entry e;
cm_archive_entry_copy_sourcepath(e, file);
cm_archive_entry_copy_pathname(e, dest);
- if (archive_read_disk_entry_from_file(this->Disk, e, -1, CM_NULLPTR) !=
+ if (archive_read_disk_entry_from_file(this->Disk, e, -1, nullptr) !=
ARCHIVE_OK) {
this->Error = "archive_read_disk_entry_from_file '";
this->Error += file;
diff --git a/Source/cmArchiveWrite.h b/Source/cmArchiveWrite.h
index 4c85c0d16..56dce2a45 100644
--- a/Source/cmArchiveWrite.h
+++ b/Source/cmArchiveWrite.h
@@ -67,13 +67,13 @@ public:
* skip. The remaining part of the input path is appended to the
* "prefix" value to construct the final name in the archive.
*/
- bool Add(std::string path, size_t skip = 0, const char* prefix = CM_NULLPTR,
+ bool Add(std::string path, size_t skip = 0, const char* prefix = nullptr,
bool recursive = true);
/** Returns true if there has been no error. */
operator safe_bool() const
{
- return this->Okay() ? &cmArchiveWrite::safe_bool_true : CM_NULLPTR;
+ return this->Okay() ? &cmArchiveWrite::safe_bool_true : nullptr;
}
/** Returns true if there has been an error. */
diff --git a/Source/cmAuxSourceDirectoryCommand.h b/Source/cmAuxSourceDirectoryCommand.h
index e49e86117..3742e3e9b 100644
--- a/Source/cmAuxSourceDirectoryCommand.h
+++ b/Source/cmAuxSourceDirectoryCommand.h
@@ -3,7 +3,7 @@
#ifndef cmAuxSourceDirectoryCommand_h
#define cmAuxSourceDirectoryCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -27,14 +27,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmAuxSourceDirectoryCommand; }
+ cmCommand* Clone() override { return new cmAuxSourceDirectoryCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmBreakCommand.h b/Source/cmBreakCommand.h
index fcca45c31..3b1856736 100644
--- a/Source/cmBreakCommand.h
+++ b/Source/cmBreakCommand.h
@@ -3,7 +3,7 @@
#ifndef cmBreakCommand_h
#define cmBreakCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmBreakCommand; }
+ cmCommand* Clone() override { return new cmBreakCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmBuildCommand.h b/Source/cmBuildCommand.h
index 1f357a980..e0529a414 100644
--- a/Source/cmBuildCommand.h
+++ b/Source/cmBuildCommand.h
@@ -3,7 +3,7 @@
#ifndef cmBuildCommand_h
#define cmBuildCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmBuildCommand; }
+ cmCommand* Clone() override { return new cmBuildCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
/**
* The primary command signature with optional, KEYWORD-based args.
diff --git a/Source/cmBuildNameCommand.cxx b/Source/cmBuildNameCommand.cxx
index 9d2c0c642..5f54338c2 100644
--- a/Source/cmBuildNameCommand.cxx
+++ b/Source/cmBuildNameCommand.cxx
@@ -36,7 +36,7 @@ bool cmBuildNameCommand::InitialPass(std::vector<std::string> const& args,
std::string buildname = "WinNT";
if (this->Makefile->GetDefinition("UNIX")) {
- buildname = "";
+ buildname.clear();
cmSystemTools::RunSingleCommand("uname -a", &buildname, &buildname);
if (!buildname.empty()) {
std::string RegExp = "([^ ]*) [^ ]* ([^ ]*) ";
diff --git a/Source/cmBuildNameCommand.h b/Source/cmBuildNameCommand.h
index ff26c559c..4bb72d147 100644
--- a/Source/cmBuildNameCommand.h
+++ b/Source/cmBuildNameCommand.h
@@ -3,7 +3,7 @@
#ifndef cmBuildNameCommand_h
#define cmBuildNameCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,9 +15,9 @@ class cmExecutionStatus;
class cmBuildNameCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmBuildNameCommand; }
+ cmCommand* Clone() override { return new cmBuildNameCommand; }
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmCLocaleEnvironmentScope.cxx b/Source/cmCLocaleEnvironmentScope.cxx
index 28e8f2efc..737e3ea86 100644
--- a/Source/cmCLocaleEnvironmentScope.cxx
+++ b/Source/cmCLocaleEnvironmentScope.cxx
@@ -45,10 +45,9 @@ void cmCLocaleEnvironmentScope::SetEnv(std::string const& key,
cmCLocaleEnvironmentScope::~cmCLocaleEnvironmentScope()
{
- for (backup_map_t::const_iterator i = this->EnvironmentBackup.begin();
- i != this->EnvironmentBackup.end(); ++i) {
+ for (auto const& envb : this->EnvironmentBackup) {
std::ostringstream tmp;
- tmp << i->first << "=" << i->second;
+ tmp << envb.first << "=" << envb.second;
cmSystemTools::PutEnv(tmp.str());
}
}
diff --git a/Source/cmCLocaleEnvironmentScope.h b/Source/cmCLocaleEnvironmentScope.h
index e956cb24d..ec81cb9f2 100644
--- a/Source/cmCLocaleEnvironmentScope.h
+++ b/Source/cmCLocaleEnvironmentScope.h
@@ -3,7 +3,7 @@
#ifndef cmCLocaleEnvironmentScope_h
#define cmCLocaleEnvironmentScope_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <map>
#include <string>
diff --git a/Source/cmCMakeHostSystemInformationCommand.cxx b/Source/cmCMakeHostSystemInformationCommand.cxx
index 4475c5a52..5106f522d 100644
--- a/Source/cmCMakeHostSystemInformationCommand.cxx
+++ b/Source/cmCMakeHostSystemInformationCommand.cxx
@@ -76,6 +76,55 @@ bool cmCMakeHostSystemInformationCommand::GetValue(
value = this->ValueToString(info.GetTotalPhysicalMemory());
} else if (key == "AVAILABLE_PHYSICAL_MEMORY") {
value = this->ValueToString(info.GetAvailablePhysicalMemory());
+ } else if (key == "IS_64BIT") {
+ value = this->ValueToString(info.Is64Bits());
+ } else if (key == "HAS_FPU") {
+ value = this->ValueToString(
+ info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_FPU));
+ } else if (key == "HAS_MMX") {
+ value = this->ValueToString(
+ info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_MMX));
+ } else if (key == "HAS_MMX_PLUS") {
+ value = this->ValueToString(info.DoesCPUSupportFeature(
+ cmsys::SystemInformation::CPU_FEATURE_MMX_PLUS));
+ } else if (key == "HAS_SSE") {
+ value = this->ValueToString(
+ info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_SSE));
+ } else if (key == "HAS_SSE2") {
+ value = this->ValueToString(
+ info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_SSE2));
+ } else if (key == "HAS_SSE_FP") {
+ value = this->ValueToString(info.DoesCPUSupportFeature(
+ cmsys::SystemInformation::CPU_FEATURE_SSE_FP));
+ } else if (key == "HAS_SSE_MMX") {
+ value = this->ValueToString(info.DoesCPUSupportFeature(
+ cmsys::SystemInformation::CPU_FEATURE_SSE_MMX));
+ } else if (key == "HAS_AMD_3DNOW") {
+ value = this->ValueToString(info.DoesCPUSupportFeature(
+ cmsys::SystemInformation::CPU_FEATURE_AMD_3DNOW));
+ } else if (key == "HAS_AMD_3DNOW_PLUS") {
+ value = this->ValueToString(info.DoesCPUSupportFeature(
+ cmsys::SystemInformation::CPU_FEATURE_AMD_3DNOW_PLUS));
+ } else if (key == "HAS_IA64") {
+ value = this->ValueToString(
+ info.DoesCPUSupportFeature(cmsys::SystemInformation::CPU_FEATURE_IA64));
+ } else if (key == "HAS_SERIAL_NUMBER") {
+ value = this->ValueToString(info.DoesCPUSupportFeature(
+ cmsys::SystemInformation::CPU_FEATURE_SERIALNUMBER));
+ } else if (key == "PROCESSOR_NAME") {
+ value = this->ValueToString(info.GetExtendedProcessorName());
+ } else if (key == "PROCESSOR_DESCRIPTION") {
+ value = info.GetCPUDescription();
+ } else if (key == "PROCESSOR_SERIAL_NUMBER") {
+ value = this->ValueToString(info.GetProcessorSerialNumber());
+ } else if (key == "OS_NAME") {
+ value = this->ValueToString(info.GetOSName());
+ } else if (key == "OS_RELEASE") {
+ value = this->ValueToString(info.GetOSRelease());
+ } else if (key == "OS_VERSION") {
+ value = this->ValueToString(info.GetOSVersion());
+ } else if (key == "OS_PLATFORM") {
+ value = this->ValueToString(info.GetOSPlatform());
#ifdef HAVE_VS_SETUP_HELPER
} else if (key == "VS_15_DIR") {
cmVSSetupAPIHelper vsSetupAPIHelper;
diff --git a/Source/cmCMakeHostSystemInformationCommand.h b/Source/cmCMakeHostSystemInformationCommand.h
index ef6ca3730..bfff8f1a1 100644
--- a/Source/cmCMakeHostSystemInformationCommand.h
+++ b/Source/cmCMakeHostSystemInformationCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCMakeHostSystemInformationCommand_h
#define cmCMakeHostSystemInformationCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <stddef.h>
#include <string>
@@ -28,7 +28,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
return new cmCMakeHostSystemInformationCommand;
}
@@ -38,7 +38,7 @@ public:
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
bool GetValue(cmsys::SystemInformation& info, std::string const& key,
diff --git a/Source/cmCMakeMinimumRequired.cxx b/Source/cmCMakeMinimumRequired.cxx
index 942688cee..bcc41fca9 100644
--- a/Source/cmCMakeMinimumRequired.cxx
+++ b/Source/cmCMakeMinimumRequired.cxx
@@ -19,10 +19,10 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args,
// Process arguments.
std::string version_string;
bool doing_version = false;
- for (unsigned int i = 0; i < args.size(); ++i) {
- if (args[i] == "VERSION") {
+ for (std::string const& arg : args) {
+ if (arg == "VERSION") {
doing_version = true;
- } else if (args[i] == "FATAL_ERROR") {
+ } else if (arg == "FATAL_ERROR") {
if (doing_version) {
this->SetError("called with no value for VERSION.");
return false;
@@ -30,9 +30,9 @@ bool cmCMakeMinimumRequired::InitialPass(std::vector<std::string> const& args,
doing_version = false;
} else if (doing_version) {
doing_version = false;
- version_string = args[i];
+ version_string = arg;
} else {
- this->UnknownArguments.push_back(args[i]);
+ this->UnknownArguments.push_back(arg);
}
}
if (doing_version) {
diff --git a/Source/cmCMakeMinimumRequired.h b/Source/cmCMakeMinimumRequired.h
index 45b6b7885..18d9460ed 100644
--- a/Source/cmCMakeMinimumRequired.h
+++ b/Source/cmCMakeMinimumRequired.h
@@ -3,7 +3,7 @@
#ifndef cmCMakeMinimumRequired_h
#define cmCMakeMinimumRequired_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmCMakeMinimumRequired; }
+ cmCommand* Clone() override { return new cmCMakeMinimumRequired; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
std::vector<std::string> UnknownArguments;
diff --git a/Source/cmCMakePolicyCommand.h b/Source/cmCMakePolicyCommand.h
index 0e88243f5..b18576c67 100644
--- a/Source/cmCMakePolicyCommand.h
+++ b/Source/cmCMakePolicyCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCMakePolicyCommand_h
#define cmCMakePolicyCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmCMakePolicyCommand; }
+ cmCommand* Clone() override { return new cmCMakePolicyCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
bool HandleSetMode(std::vector<std::string> const& args);
diff --git a/Source/cmCPackPropertiesGenerator.cxx b/Source/cmCPackPropertiesGenerator.cxx
index 57a8b383c..a33b824f3 100644
--- a/Source/cmCPackPropertiesGenerator.cxx
+++ b/Source/cmCPackPropertiesGenerator.cxx
@@ -6,7 +6,6 @@
#include <map>
#include <ostream>
-#include <utility>
cmCPackPropertiesGenerator::cmCPackPropertiesGenerator(
cmLocalGenerator* lg, cmInstalledFile const& installedFile,
@@ -27,19 +26,17 @@ void cmCPackPropertiesGenerator::GenerateScriptForConfig(
cmInstalledFile::PropertyMapType const& properties =
this->InstalledFile.GetProperties();
- for (cmInstalledFile::PropertyMapType::const_iterator i = properties.begin();
- i != properties.end(); ++i) {
- std::string const& name = i->first;
- cmInstalledFile::Property const& property = i->second;
+ for (cmInstalledFile::PropertyMapType::value_type const& i : properties) {
+ std::string const& name = i.first;
+ cmInstalledFile::Property const& property = i.second;
os << indent << "set_property(INSTALL "
<< cmOutputConverter::EscapeForCMake(expandedFileName) << " PROPERTY "
<< cmOutputConverter::EscapeForCMake(name);
- for (cmInstalledFile::ExpressionVectorType::const_iterator j =
- property.ValueExpressions.begin();
- j != property.ValueExpressions.end(); ++j) {
- std::string value = (*j)->Evaluate(this->LG, config);
+ for (cmInstalledFile::ExpressionVectorType::value_type const& j :
+ property.ValueExpressions) {
+ std::string value = j->Evaluate(this->LG, config);
os << " " << cmOutputConverter::EscapeForCMake(value);
}
diff --git a/Source/cmCPackPropertiesGenerator.h b/Source/cmCPackPropertiesGenerator.h
index 48f4c10f4..e580e044b 100644
--- a/Source/cmCPackPropertiesGenerator.h
+++ b/Source/cmCPackPropertiesGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmCPackPropertiesGenerator_h
#define cmCPackPropertiesGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmScriptGenerator.h"
@@ -29,7 +29,7 @@ public:
protected:
void GenerateScriptForConfig(std::ostream& os, const std::string& config,
- Indent indent) CM_OVERRIDE;
+ Indent indent) override;
cmLocalGenerator* LG;
cmInstalledFile const& InstalledFile;
diff --git a/Source/cmCPluginAPI.cxx b/Source/cmCPluginAPI.cxx
index e78f5fe04..e1e11afad 100644
--- a/Source/cmCPluginAPI.cxx
+++ b/Source/cmCPluginAPI.cxx
@@ -218,8 +218,8 @@ void CCONV cmAddUtilityCommand(void* arg, const char* utilityName,
}
// Pass the call to the makefile instance.
- mf->AddUtilityCommand(utilityName, (all ? false : true), CM_NULLPTR,
- depends2, commandLines);
+ mf->AddUtilityCommand(utilityName, (all ? false : true), nullptr, depends2,
+ commandLines);
}
void CCONV cmAddCustomCommand(void* arg, const char* source,
const char* command, int numArgs,
@@ -257,7 +257,7 @@ void CCONV cmAddCustomCommand(void* arg, const char* source,
}
// Pass the call to the makefile instance.
- const char* no_comment = CM_NULLPTR;
+ const char* no_comment = nullptr;
mf->AddCustomCommandOldStyle(target, outputs2, depends2, source,
commandLines, no_comment);
}
@@ -291,8 +291,8 @@ void CCONV cmAddCustomCommandToOutput(void* arg, const char* output,
}
// Pass the call to the makefile instance.
- const char* no_comment = CM_NULLPTR;
- const char* no_working_dir = CM_NULLPTR;
+ const char* no_comment = nullptr;
+ const char* no_working_dir = nullptr;
mf->AddCustomCommandToOutput(output, depends2, main_dependency, commandLines,
no_comment, no_working_dir);
}
@@ -333,8 +333,8 @@ void CCONV cmAddCustomCommandToTarget(void* arg, const char* target,
// Pass the call to the makefile instance.
std::vector<std::string> no_byproducts;
std::vector<std::string> no_depends;
- const char* no_comment = CM_NULLPTR;
- const char* no_working_dir = CM_NULLPTR;
+ const char* no_comment = nullptr;
+ const char* no_working_dir = nullptr;
mf->AddCustomCommandToTarget(target, no_byproducts, no_depends, commandLines,
cctype, no_comment, no_working_dir);
}
@@ -405,14 +405,8 @@ char CCONV* cmExpandVariablesInString(void* arg, const char* source,
{
cmMakefile* mf = static_cast<cmMakefile*>(arg);
std::string barf = source;
- std::string result = mf->ExpandVariablesInString(
- barf, (escapeQuotes ? true : false), (atOnly ? true : false));
- char* res = static_cast<char*>(malloc(result.size() + 1));
- if (!result.empty()) {
- strcpy(res, result.c_str());
- }
- res[result.size()] = '\0';
- return res;
+ std::string result = mf->ExpandVariablesInString(barf, escapeQuotes, atOnly);
+ return strdup(result.c_str());
}
int CCONV cmExecuteCommand(void* arg, const char* name, int numArgs,
@@ -443,7 +437,7 @@ void CCONV cmExpandSourceListArguments(void* arg, int numArgs,
result.push_back(args[i]);
}
int resargc = static_cast<int>(result.size());
- char** resargv = CM_NULLPTR;
+ char** resargv = nullptr;
if (resargc) {
resargv = (char**)malloc(resargc * sizeof(char*));
}
@@ -460,9 +454,7 @@ void CCONV cmFreeArguments(int argc, char** argv)
for (i = 0; i < argc; ++i) {
free(argv[i]);
}
- if (argv) {
- free(argv);
- }
+ free(argv);
}
int CCONV cmGetTotalArgumentSize(int argc, char** argv)
@@ -482,7 +474,7 @@ int CCONV cmGetTotalArgumentSize(int argc, char** argv)
struct cmCPluginAPISourceFile
{
cmCPluginAPISourceFile()
- : RealSourceFile(CM_NULLPTR)
+ : RealSourceFile(nullptr)
{
}
cmSourceFile* RealSourceFile;
@@ -504,8 +496,8 @@ public:
typedef derived::value_type value_type;
~cmCPluginAPISourceFileMap()
{
- for (iterator i = this->begin(); i != this->end(); ++i) {
- delete i->second;
+ for (auto const& i : *this) {
+ delete i.second;
}
}
};
@@ -513,13 +505,12 @@ cmCPluginAPISourceFileMap cmCPluginAPISourceFiles;
void* CCONV cmCreateSourceFile(void)
{
- return (void*)new cmCPluginAPISourceFile;
+ return new cmCPluginAPISourceFile;
}
void* CCONV cmCreateNewSourceFile(void*)
{
- cmCPluginAPISourceFile* sf = new cmCPluginAPISourceFile;
- return (void*)sf;
+ return new cmCPluginAPISourceFile;
}
void CCONV cmDestroySourceFile(void* arg)
@@ -552,9 +543,9 @@ void CCONV* cmGetSource(void* arg, const char* name)
cmCPluginAPISourceFileMap::value_type entry(rsf, sf);
i = cmCPluginAPISourceFiles.insert(entry).first;
}
- return (void*)i->second;
+ return i->second;
}
- return CM_NULLPTR;
+ return nullptr;
}
void* CCONV cmAddSource(void* arg, void* arg2)
@@ -562,15 +553,14 @@ void* CCONV cmAddSource(void* arg, void* arg2)
cmMakefile* mf = static_cast<cmMakefile*>(arg);
cmCPluginAPISourceFile* osf = static_cast<cmCPluginAPISourceFile*>(arg2);
if (osf->FullPath.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
// Create the real cmSourceFile instance and copy over saved information.
cmSourceFile* rsf = mf->GetOrCreateSource(osf->FullPath);
rsf->GetProperties() = osf->Properties;
- for (std::vector<std::string>::iterator i = osf->Depends.begin();
- i != osf->Depends.end(); ++i) {
- rsf->AddDepend(*i);
+ for (std::string const& d : osf->Depends) {
+ rsf->AddDepend(d);
}
// Create the proxy for the real source file.
@@ -582,7 +572,7 @@ void* CCONV cmAddSource(void* arg, void* arg2)
// Store the proxy in the map so it can be re-used and deleted later.
cmCPluginAPISourceFiles[rsf] = sf;
- return (void*)sf;
+ return sf;
}
const char* CCONV cmSourceFileGetSourceName(void* arg)
@@ -763,25 +753,19 @@ void CCONV cmSourceFileSetName2(void* arg, const char* name, const char* dir,
char* CCONV cmGetFilenameWithoutExtension(const char* name)
{
std::string sres = cmSystemTools::GetFilenameWithoutExtension(name);
- char* result = (char*)malloc(sres.size() + 1);
- strcpy(result, sres.c_str());
- return result;
+ return strdup(sres.c_str());
}
char* CCONV cmGetFilenamePath(const char* name)
{
std::string sres = cmSystemTools::GetFilenamePath(name);
- char* result = (char*)malloc(sres.size() + 1);
- strcpy(result, sres.c_str());
- return result;
+ return strdup(sres.c_str());
}
char* CCONV cmCapitalized(const char* name)
{
std::string sres = cmSystemTools::Capitalized(name);
- char* result = (char*)malloc(sres.size() + 1);
- strcpy(result, sres.c_str());
- return result;
+ return strdup(sres.c_str());
}
void CCONV cmCopyFileIfDifferent(const char* name1, const char* name2)
diff --git a/Source/cmCTest.cxx b/Source/cmCTest.cxx
index e2605561a..4ea14931e 100644
--- a/Source/cmCTest.cxx
+++ b/Source/cmCTest.cxx
@@ -11,9 +11,11 @@
#include "cmsys/Process.h"
#include "cmsys/String.hxx"
#include "cmsys/SystemInformation.hxx"
+#include <algorithm>
#include <ctype.h>
#include <iostream>
#include <map>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
@@ -49,7 +51,6 @@
#include "cmVersion.h"
#include "cmVersionConfig.h"
#include "cmXMLWriter.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
#if defined(__BEOS__) || defined(__HAIKU__)
@@ -66,7 +67,7 @@
struct tm* cmCTest::GetNightlyTime(std::string const& str, bool tomorrowtag)
{
struct tm* lctime;
- time_t tctime = time(CM_NULLPTR);
+ time_t tctime = time(nullptr);
lctime = gmtime(&tctime);
char buf[1024];
// add todays year day and month to the time in str because
@@ -84,7 +85,7 @@ struct tm* cmCTest::GetNightlyTime(std::string const& str, bool tomorrowtag)
// As such, this time may be in the past or in the future.
time_t ntime = curl_getdate(buf, &tctime);
cmCTestLog(this, DEBUG, " Get curl time: " << ntime << std::endl);
- tctime = time(CM_NULLPTR);
+ tctime = time(nullptr);
cmCTestLog(this, DEBUG, " Get the current time: " << tctime << std::endl);
const int dayLength = 24 * 60 * 60;
@@ -130,7 +131,7 @@ std::string cmCTest::CleanString(const std::string& str)
std::string cmCTest::CurrentTime()
{
- time_t currenttime = time(CM_NULLPTR);
+ time_t currenttime = time(nullptr);
struct tm* t = localtime(&currenttime);
// return ::CleanString(ctime(&currenttime));
char current_time[1024];
@@ -146,7 +147,7 @@ std::string cmCTest::CurrentTime()
std::string cmCTest::GetCostDataFile()
{
std::string fname = this->GetCTestConfiguration("CostDataFile");
- if (fname == "") {
+ if (fname.empty()) {
fname = this->GetBinaryDir() + "/Testing/Temporary/CTestCostData.txt";
}
return fname;
@@ -156,7 +157,7 @@ std::string cmCTest::GetCostDataFile()
static size_t HTTPResponseCallback(void* ptr, size_t size, size_t nmemb,
void* data)
{
- int realsize = (int)(size * nmemb);
+ int realsize = static_cast<int>(size * nmemb);
std::string* response = static_cast<std::string*>(data);
const char* chPtr = static_cast<char*>(ptr);
@@ -190,7 +191,8 @@ int cmCTest::HTTPRequest(std::string url, HTTPMethod method,
::curl_easy_setopt(curl, CURLOPT_PUT, 1);
file = cmsys::SystemTools::Fopen(putFile, "rb");
::curl_easy_setopt(curl, CURLOPT_INFILE, file);
- // fall through to append GET fields
+ // fall through to append GET fields
+ CM_FALLTHROUGH;
case cmCTest::HTTP_GET:
if (!fields.empty()) {
url += "?" + fields;
@@ -204,7 +206,7 @@ int cmCTest::HTTPRequest(std::string url, HTTPMethod method,
// set response options
::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HTTPResponseCallback);
- ::curl_easy_setopt(curl, CURLOPT_FILE, (void*)&response);
+ ::curl_easy_setopt(curl, CURLOPT_FILE, &response);
::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
CURLcode res = ::curl_easy_perform(curl);
@@ -220,12 +222,11 @@ std::string cmCTest::MakeURLSafe(const std::string& str)
{
std::ostringstream ost;
char buffer[10];
- for (std::string::size_type pos = 0; pos < str.size(); pos++) {
- unsigned char ch = str[pos];
+ for (unsigned char ch : str) {
if ((ch > 126 || ch < 32 || ch == '&' || ch == '%' || ch == '+' ||
ch == '=' || ch == '@') &&
ch != 9) {
- sprintf(buffer, "%02x;", (unsigned int)ch);
+ sprintf(buffer, "%02x;", static_cast<unsigned int>(ch));
ost << buffer;
} else {
ost << ch;
@@ -240,7 +241,7 @@ std::string cmCTest::DecodeURL(const std::string& in)
for (const char* c = in.c_str(); *c; ++c) {
if (*c == '%' && isxdigit(*(c + 1)) && isxdigit(*(c + 2))) {
char buf[3] = { *(c + 1), *(c + 2), 0 };
- out.append(1, char(strtoul(buf, CM_NULLPTR, 16)));
+ out.append(1, char(strtoul(buf, nullptr, 16)));
c += 2;
} else {
out.append(1, *c);
@@ -252,6 +253,7 @@ std::string cmCTest::DecodeURL(const std::string& in)
cmCTest::cmCTest()
{
this->LabelSummary = true;
+ this->SubprojectSummary = true;
this->ParallelLevel = 1;
this->ParallelLevelSetInCli = false;
this->TestLoad = 0;
@@ -279,11 +281,11 @@ cmCTest::cmCTest()
this->GlobalTimeout = 0;
this->LastStopTimeout = 24 * 60 * 60;
this->CompressXMLFiles = false;
- this->CTestConfigFile = "";
- this->ScheduleType = "";
- this->StopTime = "";
+ this->CTestConfigFile.clear();
+ this->ScheduleType.clear();
+ this->StopTime.clear();
this->NextDayStopTime = false;
- this->OutputLogFile = CM_NULLPTR;
+ this->OutputLogFile = nullptr;
this->OutputLogFileLastTag = -1;
this->SuppressUpdatingCTestConfiguration = false;
this->DartVersion = 1;
@@ -328,10 +330,8 @@ cmCTest::cmCTest()
this->TestingHandlers["submit"] = new cmCTestSubmitHandler;
this->TestingHandlers["upload"] = new cmCTestUploadHandler;
- cmCTest::t_TestingHandlers::iterator it;
- for (it = this->TestingHandlers.begin(); it != this->TestingHandlers.end();
- ++it) {
- it->second->SetCTestInstance(this);
+ for (auto& handler : this->TestingHandlers) {
+ handler.second->SetCTestInstance(this);
}
// Make sure we can capture the build tool output.
@@ -341,7 +341,7 @@ cmCTest::cmCTest()
cmCTest::~cmCTest()
{
cmDeleteAll(this->TestingHandlers);
- this->SetOutputLogFileName(CM_NULLPTR);
+ this->SetOutputLogFileName(nullptr);
}
void cmCTest::SetParallelLevel(int level)
@@ -421,9 +421,8 @@ int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
cm.SetHomeOutputDirectory("");
cm.GetCurrentSnapshot().SetDefaultDefinitions();
cmGlobalGenerator gg(&cm);
- CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
- if (!this->ReadCustomConfigurationFileTree(this->BinaryDir.c_str(),
- mf.get())) {
+ cmMakefile mf(&gg, cm.GetCurrentSnapshot());
+ if (!this->ReadCustomConfigurationFileTree(this->BinaryDir.c_str(), &mf)) {
cmCTestOptionalLog(
this, DEBUG, "Cannot find custom configuration file tree" << std::endl,
quiet);
@@ -462,7 +461,7 @@ int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
std::string tag;
if (createNewTag) {
- time_t tctime = time(CM_NULLPTR);
+ time_t tctime = time(nullptr);
if (this->TomorrowTag) {
tctime += (24 * 60 * 60);
}
@@ -477,7 +476,7 @@ int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
&min);
if (year != lctime->tm_year + 1900 || mon != lctime->tm_mon + 1 ||
day != lctime->tm_mday) {
- tag = "";
+ tag.clear();
}
std::string tagmode;
if (cmSystemTools::GetLineFromStream(tfin, tagmode)) {
@@ -487,7 +486,7 @@ int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
}
tfin.close();
}
- if (tag.empty() || (CM_NULLPTR != command) || this->Parts[PartStart]) {
+ if (tag.empty() || (nullptr != command) || this->Parts[PartStart]) {
cmCTestOptionalLog(
this, DEBUG,
"TestModel: " << this->GetTestModelString() << std::endl, quiet);
@@ -509,7 +508,7 @@ int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
ofs << this->GetTestModelString() << std::endl;
}
ofs.close();
- if (CM_NULLPTR == command) {
+ if (nullptr == command) {
cmCTestOptionalLog(this, OUTPUT, "Create new tag: "
<< tag << " - " << this->GetTestModelString()
<< std::endl,
@@ -805,7 +804,7 @@ cmCTestGenericHandler* cmCTest::GetInitializedHandler(const char* handler)
cmCTest::t_TestingHandlers::iterator it =
this->TestingHandlers.find(handler);
if (it == this->TestingHandlers.end()) {
- return CM_NULLPTR;
+ return nullptr;
}
it->second->Initialize();
return it->second;
@@ -816,7 +815,7 @@ cmCTestGenericHandler* cmCTest::GetHandler(const char* handler)
cmCTest::t_TestingHandlers::iterator it =
this->TestingHandlers.find(handler);
if (it == this->TestingHandlers.end()) {
- return CM_NULLPTR;
+ return nullptr;
}
return it->second;
}
@@ -970,17 +969,19 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
}
std::vector<const char*> argv;
- for (std::vector<std::string>::const_iterator a = args.begin();
- a != args.end(); ++a) {
- argv.push_back(a->c_str());
+ argv.reserve(args.size() + 1);
+ for (std::string const& a : args) {
+ argv.push_back(a.c_str());
}
- argv.push_back(CM_NULLPTR);
+ argv.push_back(nullptr);
- output = "";
+ output.clear();
cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, "Run command:");
- std::vector<const char*>::iterator ait;
- for (ait = argv.begin(); ait != argv.end() && *ait; ++ait) {
- cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, " \"" << *ait << "\"");
+ for (char const* arg : argv) {
+ if (!arg) {
+ break;
+ }
+ cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, " \"" << arg << "\"");
}
cmCTestLog(this, HANDLER_VERBOSE_OUTPUT, std::endl);
@@ -1004,11 +1005,11 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, " Each . represents "
<< tick_len << " bytes of output" << std::endl
<< " " << std::flush);
- while (cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
+ while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
processOutput.DecodeText(data, length, strdata);
- for (size_t cc = 0; cc < strdata.size(); ++cc) {
- if (strdata[cc] == 0) {
- strdata[cc] = '\n';
+ for (char& cc : strdata) {
+ if (cc == 0) {
+ cc = '\n';
}
}
output.append(strdata);
@@ -1040,7 +1041,7 @@ int cmCTest::RunMakeCommand(const char* command, std::string& output,
cmCTestLog(this, HANDLER_PROGRESS_OUTPUT, " Size of output: "
<< int(double(output.size()) / 1024.0) << "K" << std::endl);
- cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ cmsysProcess_WaitForExit(cp, nullptr);
int result = cmsysProcess_GetState(cp);
@@ -1104,27 +1105,27 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
inst.SetStreams(&oss, &oss);
std::vector<std::string> args;
- for (unsigned int i = 0; i < argv.size(); ++i) {
- if (argv[i]) {
+ for (char const* i : argv) {
+ if (i) {
// make sure we pass the timeout in for any build and test
// invocations. Since --build-generator is required this is a
// good place to check for it, and to add the arguments in
- if (strcmp(argv[i], "--build-generator") == 0 && timeout > 0) {
+ if (strcmp(i, "--build-generator") == 0 && timeout > 0) {
args.push_back("--test-timeout");
std::ostringstream msg;
msg << timeout;
args.push_back(msg.str());
}
- args.push_back(argv[i]);
+ args.push_back(i);
}
}
if (log) {
*log << "* Run internal CTest" << std::endl;
}
- CM_AUTO_PTR<cmSystemTools::SaveRestoreEnvironment> saveEnv;
+ std::unique_ptr<cmSystemTools::SaveRestoreEnvironment> saveEnv;
if (modifyEnv) {
- saveEnv.reset(new cmSystemTools::SaveRestoreEnvironment);
+ saveEnv = cm::make_unique<cmSystemTools::SaveRestoreEnvironment>();
cmSystemTools::AppendEnv(*environment);
}
@@ -1146,12 +1147,12 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
}
std::vector<char> tempOutput;
if (output) {
- *output = "";
+ output->clear();
}
- CM_AUTO_PTR<cmSystemTools::SaveRestoreEnvironment> saveEnv;
+ std::unique_ptr<cmSystemTools::SaveRestoreEnvironment> saveEnv;
if (modifyEnv) {
- saveEnv.reset(new cmSystemTools::SaveRestoreEnvironment);
+ saveEnv = cm::make_unique<cmSystemTools::SaveRestoreEnvironment>();
cmSystemTools::AppendEnv(*environment);
}
@@ -1169,7 +1170,7 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
int length;
cmProcessOutput processOutput(encoding);
std::string strdata;
- while (cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) {
+ while (cmsysProcess_WaitForData(cp, &data, &length, nullptr)) {
processOutput.DecodeText(data, length, strdata);
if (output) {
tempOutput.insert(tempOutput.end(), data, data + length);
@@ -1189,7 +1190,7 @@ int cmCTest::RunTest(std::vector<const char*> argv, std::string* output,
}
}
- cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ cmsysProcess_WaitForExit(cp, nullptr);
processOutput.DecodeText(tempOutput, tempOutput);
if (output && tempOutput.begin() != tempOutput.end()) {
output->append(&*tempOutput.begin(), tempOutput.size());
@@ -1234,7 +1235,7 @@ std::string cmCTest::SafeBuildIdField(const std::string& value)
{
std::string safevalue(value);
- if (safevalue != "") {
+ if (!safevalue.empty()) {
// Disallow non-filename and non-space whitespace characters.
// If they occur, replace them with ""
//
@@ -1253,7 +1254,7 @@ std::string cmCTest::SafeBuildIdField(const std::string& value)
}
}
- if (safevalue == "") {
+ if (safevalue.empty()) {
safevalue = "(empty)";
}
@@ -1345,9 +1346,8 @@ void cmCTest::AddSiteProperties(cmXMLWriter& xml)
std::string l = labels;
std::vector<std::string> args;
cmSystemTools::ExpandListArgument(l, args);
- for (std::vector<std::string>::iterator i = args.begin();
- i != args.end(); ++i) {
- xml.Element("Label", *i);
+ for (std::string const& i : args) {
+ xml.Element("Label", i);
}
xml.EndElement();
}
@@ -1363,6 +1363,33 @@ void cmCTest::AddSiteProperties(cmXMLWriter& xml)
}
}
+void cmCTest::GenerateSubprojectsOutput(cmXMLWriter& xml)
+{
+ for (std::string const& subproj : this->GetLabelsForSubprojects()) {
+ xml.StartElement("Subproject");
+ xml.Attribute("name", subproj);
+ xml.Element("Label", subproj);
+ xml.EndElement(); // Subproject
+ }
+}
+
+std::vector<std::string> cmCTest::GetLabelsForSubprojects()
+{
+ std::string labelsForSubprojects =
+ this->GetCTestConfiguration("LabelsForSubprojects");
+ std::vector<std::string> subprojects;
+ cmSystemTools::ExpandListArgument(labelsForSubprojects, subprojects);
+
+ // sort the array
+ std::sort(subprojects.begin(), subprojects.end());
+ // remove duplicates
+ std::vector<std::string>::iterator new_end =
+ std::unique(subprojects.begin(), subprojects.end());
+ subprojects.erase(new_end, subprojects.end());
+
+ return subprojects;
+}
+
void cmCTest::EndXML(cmXMLWriter& xml)
{
xml.EndElement(); // Site
@@ -1374,7 +1401,6 @@ int cmCTest::GenerateCTestNotesOutput(cmXMLWriter& xml,
{
std::string buildname =
cmCTest::SafeBuildIdField(this->GetCTestConfiguration("BuildName"));
- cmCTest::VectorOfStrings::const_iterator it;
xml.StartDocument();
xml.ProcessingInstruction("xml-stylesheet",
"type=\"text/xsl\" "
@@ -1390,15 +1416,15 @@ int cmCTest::GenerateCTestNotesOutput(cmXMLWriter& xml,
this->AddSiteProperties(xml);
xml.StartElement("Notes");
- for (it = files.begin(); it != files.end(); it++) {
- cmCTestLog(this, OUTPUT, "\tAdd file: " << *it << std::endl);
+ for (cmsys::String const& file : files) {
+ cmCTestLog(this, OUTPUT, "\tAdd file: " << file << std::endl);
std::string note_time = this->CurrentTime();
xml.StartElement("Note");
- xml.Attribute("Name", *it);
+ xml.Attribute("Name", file);
xml.Element("Time", cmSystemTools::GetTime());
xml.Element("DateTime", note_time);
xml.StartElement("Text");
- cmsys::ifstream ifs(it->c_str());
+ cmsys::ifstream ifs(file.c_str());
if (ifs) {
std::string line;
while (cmSystemTools::GetLineFromStream(ifs, line)) {
@@ -1407,9 +1433,9 @@ int cmCTest::GenerateCTestNotesOutput(cmXMLWriter& xml,
}
ifs.close();
} else {
- xml.Content("Problem reading file: " + *it + "\n");
+ xml.Content("Problem reading file: " + file + "\n");
cmCTestLog(this, ERROR_MESSAGE, "Problem reading file: "
- << *it << " while creating notes" << std::endl);
+ << file << " while creating notes" << std::endl);
}
xml.EndElement(); // Text
xml.EndElement(); // Note
@@ -1491,14 +1517,13 @@ std::string cmCTest::Base64EncodeFile(std::string const& file)
bool cmCTest::SubmitExtraFiles(const VectorOfStrings& files)
{
- VectorOfStrings::const_iterator it;
- for (it = files.begin(); it != files.end(); ++it) {
- if (!cmSystemTools::FileExists(it->c_str())) {
+ for (cmsys::String const& file : files) {
+ if (!cmSystemTools::FileExists(file.c_str())) {
cmCTestLog(this, ERROR_MESSAGE, "Cannot find extra file: "
- << *it << " to submit." << std::endl;);
+ << file << " to submit." << std::endl;);
return false;
}
- this->AddSubmitFile(PartExtraFiles, it->c_str());
+ this->AddSubmitFile(PartExtraFiles, file.c_str());
}
return true;
}
@@ -1735,7 +1760,7 @@ bool cmCTest::HandleCommandLineArguments(size_t& i,
if (this->CheckArgument(arg, "--timeout") && i < args.size() - 1) {
i++;
- double timeout = (double)atof(args[i].c_str());
+ double timeout = atof(args[i].c_str());
this->GlobalTimeout = timeout;
}
@@ -1764,6 +1789,9 @@ bool cmCTest::HandleCommandLineArguments(size_t& i,
if (this->CheckArgument(arg, "--no-label-summary")) {
this->LabelSummary = false;
}
+ if (this->CheckArgument(arg, "--no-subproject-summary")) {
+ this->SubprojectSummary = false;
+ }
if (this->CheckArgument(arg, "-Q", "--quiet")) {
this->Quiet = true;
}
@@ -2069,10 +2097,8 @@ int cmCTest::Run(std::vector<std::string>& args, std::string* output)
// pass the argument to all the handlers as well, but i may no longer be
// set to what it was originally so I'm not sure this is working as
// intended
- cmCTest::t_TestingHandlers::iterator it;
- for (it = this->TestingHandlers.begin(); it != this->TestingHandlers.end();
- ++it) {
- if (!it->second->ProcessCommandLineArguments(arg, i, args)) {
+ for (auto& handler : this->TestingHandlers) {
+ if (!handler.second->ProcessCommandLineArguments(arg, i, args)) {
cmCTestLog(this, ERROR_MESSAGE,
"Problem parsing command line arguments within a handler");
return 0;
@@ -2169,11 +2195,9 @@ int cmCTest::ExecuteTests()
if (this->ExtraVerbose) {
cmCTestLog(this, OUTPUT, "* Extra verbosity turned on" << std::endl);
}
- cmCTest::t_TestingHandlers::iterator it;
- for (it = this->TestingHandlers.begin(); it != this->TestingHandlers.end();
- ++it) {
- it->second->SetVerbose(this->ExtraVerbose);
- it->second->SetSubmitIndex(this->SubmitIndex);
+ for (auto& handler : this->TestingHandlers) {
+ handler.second->SetVerbose(this->ExtraVerbose);
+ handler.second->SetSubmitIndex(this->SubmitIndex);
}
this->GetHandler("script")->SetVerbose(this->Verbose);
res = this->GetHandler("script")->ProcessHandler();
@@ -2187,14 +2211,12 @@ int cmCTest::ExecuteTests()
// and Verbose is always on in this case
this->ExtraVerbose = this->Verbose;
this->Verbose = true;
- cmCTest::t_TestingHandlers::iterator it;
- for (it = this->TestingHandlers.begin(); it != this->TestingHandlers.end();
- ++it) {
- it->second->SetVerbose(this->Verbose);
- it->second->SetSubmitIndex(this->SubmitIndex);
+ for (auto& handler : this->TestingHandlers) {
+ handler.second->SetVerbose(this->Verbose);
+ handler.second->SetSubmitIndex(this->SubmitIndex);
}
std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
- if (!this->Initialize(cwd.c_str(), CM_NULLPTR)) {
+ if (!this->Initialize(cwd.c_str(), nullptr)) {
res = 12;
cmCTestLog(this, ERROR_MESSAGE, "Problem initializing the dashboard."
<< std::endl);
@@ -2292,13 +2314,11 @@ int cmCTest::ReadCustomConfigurationFileTree(const char* dir, cmMakefile* mf)
}
if (found) {
- cmCTest::t_TestingHandlers::iterator it;
- for (it = this->TestingHandlers.begin(); it != this->TestingHandlers.end();
- ++it) {
- cmCTestLog(this, DEBUG,
- "* Read custom CTest configuration vectors for handler: "
- << it->first << " (" << it->second << ")" << std::endl);
- it->second->PopulateCustomVectors(mf);
+ for (auto& handler : this->TestingHandlers) {
+ cmCTestLog(
+ this, DEBUG, "* Read custom CTest configuration vectors for handler: "
+ << handler.first << " (" << handler.second << ")" << std::endl);
+ handler.second->PopulateCustomVectors(mf);
}
}
@@ -2317,9 +2337,8 @@ void cmCTest::PopulateCustomVector(cmMakefile* mf, const std::string& def,
vec.clear();
cmSystemTools::ExpandListArgument(dval, vec);
- for (std::vector<std::string>::const_iterator it = vec.begin();
- it != vec.end(); ++it) {
- cmCTestLog(this, DEBUG, " -- " << *it << std::endl);
+ for (std::string const& it : vec) {
+ cmCTestLog(this, DEBUG, " -- " << it << std::endl);
}
}
@@ -2352,7 +2371,7 @@ std::string cmCTest::GetShortPathToFile(const char* cfname)
bool inBld = bldRelpath.find("..") == std::string::npos;
// TODO: Handle files with .. in their name
- std::string* res = CM_NULLPTR;
+ std::string* res = nullptr;
if (inSrc && inBld) {
// If both have relative path with no dots, pick the shorter one
@@ -2402,7 +2421,7 @@ void cmCTest::EmptyCTestConfiguration()
void cmCTest::DetermineNextDayStop()
{
struct tm* lctime;
- time_t current_time = time(CM_NULLPTR);
+ time_t current_time = time(nullptr);
lctime = gmtime(&current_time);
int gm_hour = lctime->tm_hour;
time_t gm_time = mktime(lctime);
@@ -2486,7 +2505,7 @@ bool cmCTest::GetProduceXML()
const char* cmCTest::GetSpecificTrack()
{
if (this->SpecificTrack.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
return this->SpecificTrack.c_str();
}
@@ -2494,7 +2513,7 @@ const char* cmCTest::GetSpecificTrack()
void cmCTest::SetSpecificTrack(const char* track)
{
if (!track) {
- this->SpecificTrack = "";
+ this->SpecificTrack.clear();
return;
}
this->SpecificTrack = track;
@@ -2546,25 +2565,19 @@ bool cmCTest::SetCTestConfigurationFromCMakeVariable(
return true;
}
-bool cmCTest::RunCommand(const char* command, std::string* stdOut,
- std::string* stdErr, int* retVal, const char* dir,
- double timeout, Encoding encoding)
+bool cmCTest::RunCommand(std::vector<std::string> const& args,
+ std::string* stdOut, std::string* stdErr, int* retVal,
+ const char* dir, double timeout, Encoding encoding)
{
- std::vector<std::string> args = cmSystemTools::ParseArguments(command);
-
- if (args.empty()) {
- return false;
- }
-
std::vector<const char*> argv;
- for (std::vector<std::string>::const_iterator a = args.begin();
- a != args.end(); ++a) {
- argv.push_back(a->c_str());
+ argv.reserve(args.size() + 1);
+ for (std::string const& a : args) {
+ argv.push_back(a.c_str());
}
- argv.push_back(CM_NULLPTR);
+ argv.push_back(nullptr);
- *stdOut = "";
- *stdErr = "";
+ stdOut->clear();
+ stdErr->clear();
cmsysProcess* cp = cmsysProcess_New();
cmsysProcess_SetCommand(cp, &*argv.begin());
@@ -2584,7 +2597,7 @@ bool cmCTest::RunCommand(const char* command, std::string* stdOut,
int res;
bool done = false;
while (!done) {
- res = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR);
+ res = cmsysProcess_WaitForData(cp, &data, &length, nullptr);
switch (res) {
case cmsysProcess_Pipe_STDOUT:
tempOutput.insert(tempOutput.end(), data, data + length);
@@ -2608,7 +2621,7 @@ bool cmCTest::RunCommand(const char* command, std::string* stdOut,
}
}
- cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ cmsysProcess_WaitForExit(cp, nullptr);
if (!tempOutput.empty()) {
processOutput.DecodeText(tempOutput, tempOutput);
stdOut->append(&*tempOutput.begin(), tempOutput.size());
@@ -2652,7 +2665,7 @@ void cmCTest::SetOutputLogFileName(const char* name)
{
if (this->OutputLogFile) {
delete this->OutputLogFile;
- this->OutputLogFile = CM_NULLPTR;
+ this->OutputLogFile = nullptr;
}
if (name) {
this->OutputLogFile = new cmGeneratedFileStream(name);
@@ -2666,7 +2679,7 @@ static const char* cmCTestStringLogType[] = { "DEBUG",
"HANDLER_VERBOSE_OUTPUT",
"WARNING",
"ERROR_MESSAGE",
- CM_NULLPTR };
+ nullptr };
#define cmCTestLogOutputFileLine(stream) \
if (this->ShowLineNumbers) { \
diff --git a/Source/cmCTest.h b/Source/cmCTest.h
index 60f3295e7..dbd67dc68 100644
--- a/Source/cmCTest.h
+++ b/Source/cmCTest.h
@@ -3,7 +3,7 @@
#ifndef cmCTest_h
#define cmCTest_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmProcessOutput.h"
#include "cmsys/String.hxx"
@@ -95,7 +95,7 @@ public:
typedef std::set<std::string> SetOfStrings;
/** Process Command line arguments */
- int Run(std::vector<std::string>&, std::string* output = CM_NULLPTR);
+ int Run(std::vector<std::string>&, std::string* output = nullptr);
/**
* Initialize and finalize testing
@@ -245,15 +245,10 @@ public:
* exit code will be stored. If the retVal is not specified and
* the program exits with a code other than 0, then the this
* function will return false.
- *
- * If the command has spaces in the path the caller MUST call
- * cmSystemTools::ConvertToRunCommandPath on the command before passing
- * it into this function or it will not work. The command must be correctly
- * escaped for this to with spaces.
*/
- bool RunCommand(const char* command, std::string* stdOut,
- std::string* stdErr, int* retVal = CM_NULLPTR,
- const char* dir = CM_NULLPTR, double timeout = 0.0,
+ bool RunCommand(std::vector<std::string> const& args, std::string* stdOut,
+ std::string* stdErr, int* retVal = nullptr,
+ const char* dir = nullptr, double timeout = 0.0,
Encoding encoding = cmProcessOutput::Auto);
/**
@@ -438,7 +433,9 @@ public:
this->StreamErr = err;
}
void AddSiteProperties(cmXMLWriter& xml);
+
bool GetLabelSummary() { return this->LabelSummary; }
+ bool GetSubprojectSummary() { return this->SubprojectSummary; }
std::string GetCostDataFile();
@@ -453,6 +450,9 @@ public:
/** Return true if test should run until fail */
bool GetRepeatUntilFail() { return this->RepeatUntilFail; }
+ void GenerateSubprojectsOutput(cmXMLWriter& xml);
+ std::vector<std::string> GetLabelsForSubprojects();
+
private:
int RepeatTests;
bool RepeatUntilFail;
@@ -464,6 +464,7 @@ private:
bool ExtraVerbose;
bool ProduceXML;
bool LabelSummary;
+ bool SubprojectSummary;
bool UseHTTP10;
bool PrintLabels;
bool Failover;
@@ -571,7 +572,7 @@ private:
/** Check if the argument is the one specified */
bool CheckArgument(const std::string& arg, const char* varg1,
- const char* varg2 = CM_NULLPTR);
+ const char* varg2 = nullptr);
/** Output errors from a test */
void OutputTestErrors(std::vector<char> const& process_output);
diff --git a/Source/cmCacheManager.cxx b/Source/cmCacheManager.cxx
index 0b025ab6f..44095ec14 100644
--- a/Source/cmCacheManager.cxx
+++ b/Source/cmCacheManager.cxx
@@ -173,7 +173,7 @@ bool cmCacheManager::LoadCache(const std::string& path, bool internal,
}
const char* cmCacheManager::PersistentProperties[] = { "ADVANCED", "MODIFIED",
- "STRINGS", CM_NULLPTR };
+ "STRINGS", nullptr };
bool cmCacheManager::ReadPropertyEntry(std::string const& entryKey,
CacheEntry& e)
@@ -297,10 +297,8 @@ bool cmCacheManager::SaveCache(const std::string& path)
fout << "########################\n";
fout << "\n";
- for (std::map<std::string, CacheEntry>::const_iterator i =
- this->Cache.begin();
- i != this->Cache.end(); ++i) {
- const CacheEntry& ce = (*i).second;
+ for (auto const& i : this->Cache) {
+ CacheEntry const& ce = i.second;
cmStateEnums::CacheEntryType t = ce.Type;
if (!ce.Initialized) {
/*
@@ -315,7 +313,7 @@ bool cmCacheManager::SaveCache(const std::string& path)
} else {
cmCacheManager::OutputHelpString(fout, "Missing description");
}
- this->OutputKey(fout, i->first);
+ this->OutputKey(fout, i.first);
fout << ":" << cmState::CacheEntryTypeToString(t) << "=";
this->OutputValue(fout, ce.Value);
fout << "\n\n";
@@ -440,7 +438,7 @@ cmCacheManager::CacheEntry* cmCacheManager::GetCacheEntry(
if (i != this->Cache.end()) {
return &i->second;
}
- return CM_NULLPTR;
+ return nullptr;
}
cmCacheManager::CacheIterator cmCacheManager::GetCacheIterator(const char* key)
@@ -455,18 +453,16 @@ const char* cmCacheManager::GetInitializedCacheValue(
if (i != this->Cache.end() && i->second.Initialized) {
return i->second.Value.c_str();
}
- return CM_NULLPTR;
+ return nullptr;
}
void cmCacheManager::PrintCache(std::ostream& out) const
{
out << "=================================================" << std::endl;
out << "CMakeCache Contents:" << std::endl;
- for (std::map<std::string, CacheEntry>::const_iterator i =
- this->Cache.begin();
- i != this->Cache.end(); ++i) {
- if ((*i).second.Type != cmStateEnums::INTERNAL) {
- out << (*i).first << " = " << (*i).second.Value << std::endl;
+ for (auto const& i : this->Cache) {
+ if (i.second.Type != cmStateEnums::INTERNAL) {
+ out << i.first << " = " << i.second.Value << std::endl;
}
}
out << "\n\n";
@@ -484,7 +480,7 @@ void cmCacheManager::AddCacheEntry(const std::string& key, const char* value,
e.Value = value;
e.Initialized = true;
} else {
- e.Value = "";
+ e.Value.clear();
}
e.Type = type;
// make sure we only use unix style paths
@@ -494,11 +490,10 @@ void cmCacheManager::AddCacheEntry(const std::string& key, const char* value,
cmSystemTools::ExpandListArgument(e.Value, paths);
const char* sep = "";
e.Value = "";
- for (std::vector<std::string>::iterator i = paths.begin();
- i != paths.end(); ++i) {
- cmSystemTools::ConvertToUnixSlashes(*i);
+ for (std::string& i : paths) {
+ cmSystemTools::ConvertToUnixSlashes(i);
e.Value += sep;
- e.Value += *i;
+ e.Value += i;
sep = ";";
}
} else {
@@ -548,7 +543,7 @@ void cmCacheManager::CacheIterator::SetValue(const char* value)
entry->Value = value;
entry->Initialized = true;
} else {
- entry->Value = "";
+ entry->Value.clear();
}
}
@@ -610,7 +605,7 @@ const char* cmCacheManager::CacheIterator::GetProperty(
if (!this->IsAtEnd()) {
return this->GetEntry().GetProperty(prop);
}
- return CM_NULLPTR;
+ return nullptr;
}
void cmCacheManager::CacheIterator::SetProperty(const std::string& p,
@@ -647,5 +642,5 @@ void cmCacheManager::CacheIterator::SetProperty(const std::string& p, bool v)
bool cmCacheManager::CacheIterator::PropertyExists(
const std::string& prop) const
{
- return this->GetProperty(prop) != CM_NULLPTR;
+ return this->GetProperty(prop) != nullptr;
}
diff --git a/Source/cmCacheManager.h b/Source/cmCacheManager.h
index c464311c6..e9e6570ef 100644
--- a/Source/cmCacheManager.h
+++ b/Source/cmCacheManager.h
@@ -117,7 +117,7 @@ public:
void PrintCache(std::ostream&) const;
///! Get the iterator for an entry with a given key.
- cmCacheManager::CacheIterator GetCacheIterator(const char* key = CM_NULLPTR);
+ cmCacheManager::CacheIterator GetCacheIterator(const char* key = nullptr);
///! Remove an entry from the cache
void RemoveCacheEntry(const std::string& key);
@@ -132,7 +132,7 @@ public:
{
cmCacheManager::CacheIterator it = this->GetCacheIterator(key.c_str());
if (it.IsAtEnd()) {
- return CM_NULLPTR;
+ return nullptr;
}
return it.GetValue();
}
@@ -175,8 +175,7 @@ public:
void RemoveCacheEntryProperty(std::string const& key,
std::string const& propName)
{
- this->GetCacheIterator(key.c_str())
- .SetProperty(propName, (void*)CM_NULLPTR);
+ this->GetCacheIterator(key.c_str()).SetProperty(propName, nullptr);
}
void AppendCacheEntryProperty(std::string const& key,
diff --git a/Source/cmCallVisualStudioMacro.h b/Source/cmCallVisualStudioMacro.h
index ad35d306a..fdc9e6646 100644
--- a/Source/cmCallVisualStudioMacro.h
+++ b/Source/cmCallVisualStudioMacro.h
@@ -3,7 +3,7 @@
#ifndef cmCallVisualStudioMacro_h
#define cmCallVisualStudioMacro_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
diff --git a/Source/cmCommand.h b/Source/cmCommand.h
index ad72fe208..2cc0b88ec 100644
--- a/Source/cmCommand.h
+++ b/Source/cmCommand.h
@@ -3,7 +3,7 @@
#ifndef cmCommand_h
#define cmCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -31,7 +31,7 @@ public:
* Construct the command. By default it has no makefile.
*/
cmCommand()
- : Makefile(CM_NULLPTR)
+ : Makefile(nullptr)
{
}
diff --git a/Source/cmCommandArgumentParserHelper.cxx b/Source/cmCommandArgumentParserHelper.cxx
index 4eb4531f6..6ae58d67a 100644
--- a/Source/cmCommandArgumentParserHelper.cxx
+++ b/Source/cmCommandArgumentParserHelper.cxx
@@ -19,7 +19,7 @@ cmCommandArgumentParserHelper::cmCommandArgumentParserHelper()
this->WarnUninitialized = false;
this->CheckSystemVars = false;
this->FileLine = -1;
- this->FileName = CM_NULLPTR;
+ this->FileName = nullptr;
this->RemoveEmpty = true;
this->EmptyVariable[0] = 0;
strcpy(this->DCURLYVariable, "${");
@@ -88,13 +88,13 @@ char* cmCommandArgumentParserHelper::ExpandSpecialVariable(const char* key,
e << "Syntax $" << key << "{} is not supported. "
<< "Only ${}, $ENV{}, and $CACHE{} are allowed.";
this->SetError(e.str());
- return CM_NULLPTR;
+ return nullptr;
}
char* cmCommandArgumentParserHelper::ExpandVariable(const char* var)
{
if (!var) {
- return CM_NULLPTR;
+ return nullptr;
}
if (this->FileLine >= 0 && strcmp(var, "CMAKE_CURRENT_LIST_LINE") == 0) {
std::ostringstream ostr;
@@ -117,7 +117,7 @@ char* cmCommandArgumentParserHelper::ExpandVariable(const char* var)
this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, msg.str());
}
}
- return CM_NULLPTR;
+ return nullptr;
}
if (this->EscapeQuotes && value) {
return this->AddString(cmSystemTools::EscapeQuotes(value));
@@ -169,7 +169,7 @@ char* cmCommandArgumentParserHelper::CombineUnions(char* in1, char* in2)
void cmCommandArgumentParserHelper::AllocateParserType(
cmCommandArgumentParserHelper::ParserType* pt, const char* str, int len)
{
- pt->str = CM_NULLPTR;
+ pt->str = nullptr;
if (len == 0) {
len = static_cast<int>(strlen(str));
}
@@ -234,7 +234,7 @@ int cmCommandArgumentParserHelper::ParseString(const char* str, int verb)
this->InputBufferPos = 0;
this->CurrentLine = 0;
- this->Result = "";
+ this->Result.clear();
yyscan_t yyscanner;
cmCommandArgument_yylex_init(&yyscanner);
@@ -258,8 +258,8 @@ int cmCommandArgumentParserHelper::ParseString(const char* str, int verb)
void cmCommandArgumentParserHelper::CleanupParser()
{
std::vector<char*>::iterator sit;
- for (sit = this->Variables.begin(); sit != this->Variables.end(); ++sit) {
- delete[] * sit;
+ for (char* var : this->Variables) {
+ delete[] var;
}
this->Variables.erase(this->Variables.begin(), this->Variables.end());
}
@@ -298,7 +298,7 @@ void cmCommandArgumentParserHelper::SetMakefile(const cmMakefile* mf)
void cmCommandArgumentParserHelper::SetResult(const char* value)
{
if (!value) {
- this->Result = "";
+ this->Result.clear();
return;
}
this->Result = value;
diff --git a/Source/cmCommandArgumentParserHelper.h b/Source/cmCommandArgumentParserHelper.h
index 465ca9e28..cb2a39074 100644
--- a/Source/cmCommandArgumentParserHelper.h
+++ b/Source/cmCommandArgumentParserHelper.h
@@ -3,7 +3,7 @@
#ifndef cmCommandArgumentParserHelper_h
#define cmCommandArgumentParserHelper_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
diff --git a/Source/cmCommandArgumentsHelper.cxx b/Source/cmCommandArgumentsHelper.cxx
index babddbe94..968b17cb9 100644
--- a/Source/cmCommandArgumentsHelper.cxx
+++ b/Source/cmCommandArgumentsHelper.cxx
@@ -11,11 +11,11 @@ cmCommandArgument::cmCommandArgument(cmCommandArgumentsHelper* args,
, ArgumentsBeforeEmpty(true)
, CurrentIndex(0)
{
- if (args != CM_NULLPTR) {
+ if (args != nullptr) {
args->AddArgument(this);
}
- if (this->Group != CM_NULLPTR) {
+ if (this->Group != nullptr) {
this->Group->ContainedArguments.push_back(this);
}
}
@@ -35,7 +35,7 @@ void cmCommandArgument::Follows(const cmCommandArgument* arg)
void cmCommandArgument::FollowsGroup(const cmCommandArgumentGroup* group)
{
- if (group != CM_NULLPTR) {
+ if (group != nullptr) {
this->ArgumentsBeforeEmpty = false;
this->ArgumentsBefore.insert(group->ContainedArguments.begin(),
group->ContainedArguments.end());
@@ -52,7 +52,7 @@ bool cmCommandArgument::MayFollow(const cmCommandArgument* current) const
bool cmCommandArgument::KeyMatches(const std::string& key) const
{
- if ((this->Key == CM_NULLPTR) || (this->Key[0] == '\0')) {
+ if ((this->Key == nullptr) || (this->Key[0] == '\0')) {
return true;
}
return (key == this->Key);
@@ -60,12 +60,10 @@ bool cmCommandArgument::KeyMatches(const std::string& key) const
void cmCommandArgument::ApplyOwnGroup()
{
- if (this->Group != CM_NULLPTR) {
- for (std::vector<cmCommandArgument*>::const_iterator it =
- this->Group->ContainedArguments.begin();
- it != this->Group->ContainedArguments.end(); ++it) {
- if (*it != this) {
- this->ArgumentsBefore.insert(*it);
+ if (this->Group != nullptr) {
+ for (cmCommandArgument* cargs : this->Group->ContainedArguments) {
+ if (cargs != this) {
+ this->ArgumentsBefore.insert(cargs);
}
}
}
@@ -88,9 +86,9 @@ cmCAStringVector::cmCAStringVector(cmCommandArgumentsHelper* args,
const char* key,
cmCommandArgumentGroup* group)
: cmCommandArgument(args, key, group)
- , Ignore(CM_NULLPTR)
+ , Ignore(nullptr)
{
- if ((key == CM_NULLPTR) || (*key == 0)) {
+ if ((key == nullptr) || (*key == 0)) {
this->DataStart = 0;
} else {
this->DataStart = 1;
@@ -100,7 +98,7 @@ cmCAStringVector::cmCAStringVector(cmCommandArgumentsHelper* args,
bool cmCAStringVector::DoConsume(const std::string& arg, unsigned int index)
{
if (index >= this->DataStart) {
- if ((this->Ignore == CM_NULLPTR) || (arg != this->Ignore)) {
+ if ((this->Ignore == nullptr) || (arg != this->Ignore)) {
this->Vector.push_back(arg);
}
}
@@ -117,7 +115,7 @@ cmCAString::cmCAString(cmCommandArgumentsHelper* args, const char* key,
cmCommandArgumentGroup* group)
: cmCommandArgument(args, key, group)
{
- if ((key == CM_NULLPTR) || (*key == 0)) {
+ if ((key == nullptr) || (*key == 0)) {
this->DataStart = 0;
} else {
this->DataStart = 1;
@@ -135,7 +133,7 @@ bool cmCAString::DoConsume(const std::string& arg, unsigned int index)
void cmCAString::DoReset()
{
- this->String = "";
+ this->String.clear();
}
cmCAEnabler::cmCAEnabler(cmCommandArgumentsHelper* args, const char* key,
@@ -180,60 +178,50 @@ void cmCADisabler::DoReset()
void cmCommandArgumentGroup::Follows(const cmCommandArgument* arg)
{
- for (std::vector<cmCommandArgument*>::iterator it =
- this->ContainedArguments.begin();
- it != this->ContainedArguments.end(); ++it) {
- (*it)->Follows(arg);
+ for (cmCommandArgument* ca : this->ContainedArguments) {
+ ca->Follows(arg);
}
}
void cmCommandArgumentGroup::FollowsGroup(const cmCommandArgumentGroup* group)
{
- for (std::vector<cmCommandArgument*>::iterator it =
- this->ContainedArguments.begin();
- it != this->ContainedArguments.end(); ++it) {
- (*it)->FollowsGroup(group);
+ for (cmCommandArgument* ca : this->ContainedArguments) {
+ ca->FollowsGroup(group);
}
}
void cmCommandArgumentsHelper::Parse(const std::vector<std::string>* args,
std::vector<std::string>* unconsumedArgs)
{
- if (args == CM_NULLPTR) {
+ if (args == nullptr) {
return;
}
- for (std::vector<cmCommandArgument*>::iterator argIt =
- this->Arguments.begin();
- argIt != this->Arguments.end(); ++argIt) {
- (*argIt)->ApplyOwnGroup();
- (*argIt)->Reset();
+ for (cmCommandArgument* ca : this->Arguments) {
+ ca->ApplyOwnGroup();
+ ca->Reset();
}
- cmCommandArgument* activeArgument = CM_NULLPTR;
- const cmCommandArgument* previousArgument = CM_NULLPTR;
- for (std::vector<std::string>::const_iterator it = args->begin();
- it != args->end(); ++it) {
- for (std::vector<cmCommandArgument*>::iterator argIt =
- this->Arguments.begin();
- argIt != this->Arguments.end(); ++argIt) {
- if ((*argIt)->KeyMatches(*it) &&
- ((*argIt)->MayFollow(previousArgument))) {
- activeArgument = *argIt;
+ cmCommandArgument* activeArgument = nullptr;
+ const cmCommandArgument* previousArgument = nullptr;
+ for (std::string const& it : *args) {
+ for (cmCommandArgument* ca : this->Arguments) {
+ if (ca->KeyMatches(it) && (ca->MayFollow(previousArgument))) {
+ activeArgument = ca;
activeArgument->Activate();
break;
}
}
if (activeArgument) {
- bool argDone = activeArgument->Consume(*it);
+ bool argDone = activeArgument->Consume(it);
previousArgument = activeArgument;
if (argDone) {
- activeArgument = CM_NULLPTR;
+ activeArgument = nullptr;
}
} else {
- if (unconsumedArgs != CM_NULLPTR) {
- unconsumedArgs->push_back(*it);
+ if (unconsumedArgs != nullptr) {
+ unconsumedArgs->push_back(it);
}
}
}
diff --git a/Source/cmCommandArgumentsHelper.h b/Source/cmCommandArgumentsHelper.h
index 44db374d6..d3f102c29 100644
--- a/Source/cmCommandArgumentsHelper.h
+++ b/Source/cmCommandArgumentsHelper.h
@@ -3,7 +3,7 @@
#ifndef cmCommandArgumentsHelper_h
#define cmCommandArgumentsHelper_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <set>
#include <string>
@@ -38,7 +38,7 @@ class cmCommandArgument
{
public:
cmCommandArgument(cmCommandArgumentsHelper* args, const char* key,
- cmCommandArgumentGroup* group = CM_NULLPTR);
+ cmCommandArgumentGroup* group = nullptr);
virtual ~cmCommandArgument() {}
/// this argument may follow after arg. 0 means it comes first.
@@ -90,7 +90,7 @@ class cmCAStringVector : public cmCommandArgument
{
public:
cmCAStringVector(cmCommandArgumentsHelper* args, const char* key,
- cmCommandArgumentGroup* group = CM_NULLPTR);
+ cmCommandArgumentGroup* group = nullptr);
/// Return the vector of strings
const std::vector<std::string>& GetVector() const { return this->Vector; }
@@ -103,8 +103,8 @@ private:
unsigned int DataStart;
const char* Ignore;
cmCAStringVector();
- bool DoConsume(const std::string& arg, unsigned int index) CM_OVERRIDE;
- void DoReset() CM_OVERRIDE;
+ bool DoConsume(const std::string& arg, unsigned int index) override;
+ void DoReset() override;
};
/** cmCAString is to be used for arguments which consist of one value,
@@ -113,7 +113,7 @@ class cmCAString : public cmCommandArgument
{
public:
cmCAString(cmCommandArgumentsHelper* args, const char* key,
- cmCommandArgumentGroup* group = CM_NULLPTR);
+ cmCommandArgumentGroup* group = nullptr);
/// Return the string
const std::string& GetString() const { return this->String; }
@@ -121,8 +121,8 @@ public:
private:
std::string String;
unsigned int DataStart;
- bool DoConsume(const std::string& arg, unsigned int index) CM_OVERRIDE;
- void DoReset() CM_OVERRIDE;
+ bool DoConsume(const std::string& arg, unsigned int index) override;
+ void DoReset() override;
cmCAString();
};
@@ -132,14 +132,14 @@ class cmCAEnabler : public cmCommandArgument
{
public:
cmCAEnabler(cmCommandArgumentsHelper* args, const char* key,
- cmCommandArgumentGroup* group = CM_NULLPTR);
+ cmCommandArgumentGroup* group = nullptr);
/// Has it been enabled ?
bool IsEnabled() const { return this->Enabled; }
private:
bool Enabled;
- bool DoConsume(const std::string& arg, unsigned int index) CM_OVERRIDE;
- void DoReset() CM_OVERRIDE;
+ bool DoConsume(const std::string& arg, unsigned int index) override;
+ void DoReset() override;
cmCAEnabler();
};
@@ -149,14 +149,14 @@ class cmCADisabler : public cmCommandArgument
{
public:
cmCADisabler(cmCommandArgumentsHelper* args, const char* key,
- cmCommandArgumentGroup* group = CM_NULLPTR);
+ cmCommandArgumentGroup* group = nullptr);
/// Is it still enabled ?
bool IsEnabled() const { return this->Enabled; }
private:
bool Enabled;
- bool DoConsume(const std::string& arg, unsigned int index) CM_OVERRIDE;
- void DoReset() CM_OVERRIDE;
+ bool DoConsume(const std::string& arg, unsigned int index) override;
+ void DoReset() override;
cmCADisabler();
};
diff --git a/Source/cmCommands.cxx b/Source/cmCommands.cxx
index e1d8ef143..8a7d9bde7 100644
--- a/Source/cmCommands.cxx
+++ b/Source/cmCommands.cxx
@@ -42,6 +42,7 @@
#include "cmIfCommand.h"
#include "cmIncludeCommand.h"
#include "cmIncludeDirectoryCommand.h"
+#include "cmIncludeGuardCommand.h"
#include "cmIncludeRegularExpressionCommand.h"
#include "cmInstallCommand.h"
#include "cmInstallFilesCommand.h"
@@ -67,7 +68,12 @@
#include "cmSiteNameCommand.h"
#include "cmStringCommand.h"
#include "cmSubdirCommand.h"
+#include "cmTargetCompileDefinitionsCommand.h"
+#include "cmTargetCompileFeaturesCommand.h"
+#include "cmTargetCompileOptionsCommand.h"
+#include "cmTargetIncludeDirectoriesCommand.h"
#include "cmTargetLinkLibrariesCommand.h"
+#include "cmTargetSourcesCommand.h"
#include "cmTryCompileCommand.h"
#include "cmTryRunCommand.h"
#include "cmUnsetCommand.h"
@@ -93,11 +99,6 @@
#include "cmRemoveDefinitionsCommand.h"
#include "cmSourceGroupCommand.h"
#include "cmSubdirDependsCommand.h"
-#include "cmTargetCompileDefinitionsCommand.h"
-#include "cmTargetCompileFeaturesCommand.h"
-#include "cmTargetCompileOptionsCommand.h"
-#include "cmTargetIncludeDirectoriesCommand.h"
-#include "cmTargetSourcesCommand.h"
#include "cmUseMangledMesaCommand.h"
#include "cmUtilitySourceCommand.h"
#include "cmVariableRequiresCommand.h"
@@ -132,6 +133,7 @@ void GetScriptingCommands(cmState* state)
state->AddBuiltinCommand("get_property", new cmGetPropertyCommand);
state->AddBuiltinCommand("if", new cmIfCommand);
state->AddBuiltinCommand("include", new cmIncludeCommand);
+ state->AddBuiltinCommand("include_guard", new cmIncludeGuardCommand);
state->AddBuiltinCommand("list", new cmListCommand);
state->AddBuiltinCommand("macro", new cmMacroCommand);
state->AddBuiltinCommand("make_directory", new cmMakeDirectoryCommand);
@@ -145,8 +147,6 @@ void GetScriptingCommands(cmState* state)
state->AddBuiltinCommand("separate_arguments",
new cmSeparateArgumentsCommand);
state->AddBuiltinCommand("set", new cmSetCommand);
- state->AddBuiltinCommand("set_directory_properties",
- new cmSetDirectoryPropertiesCommand);
state->AddBuiltinCommand("set_property", new cmSetPropertyCommand);
state->AddBuiltinCommand("site_name", new cmSiteNameCommand);
state->AddBuiltinCommand("string", new cmStringCommand);
@@ -229,6 +229,8 @@ void GetProjectCommands(cmState* state)
state->AddBuiltinCommand("install_targets", new cmInstallTargetsCommand);
state->AddBuiltinCommand("link_directories", new cmLinkDirectoriesCommand);
state->AddBuiltinCommand("project", new cmProjectCommand);
+ state->AddBuiltinCommand("set_directory_properties",
+ new cmSetDirectoryPropertiesCommand);
state->AddBuiltinCommand("set_source_files_properties",
new cmSetSourceFilesPropertiesCommand);
state->AddBuiltinCommand("set_target_properties",
@@ -236,8 +238,17 @@ void GetProjectCommands(cmState* state)
state->AddBuiltinCommand("set_tests_properties",
new cmSetTestsPropertiesCommand);
state->AddBuiltinCommand("subdirs", new cmSubdirCommand);
+ state->AddBuiltinCommand("target_compile_definitions",
+ new cmTargetCompileDefinitionsCommand);
+ state->AddBuiltinCommand("target_compile_features",
+ new cmTargetCompileFeaturesCommand);
+ state->AddBuiltinCommand("target_compile_options",
+ new cmTargetCompileOptionsCommand);
+ state->AddBuiltinCommand("target_include_directories",
+ new cmTargetIncludeDirectoriesCommand);
state->AddBuiltinCommand("target_link_libraries",
new cmTargetLinkLibrariesCommand);
+ state->AddBuiltinCommand("target_sources", new cmTargetSourcesCommand);
state->AddBuiltinCommand("try_compile", new cmTryCompileCommand);
state->AddBuiltinCommand("try_run", new cmTryRunCommand);
@@ -258,15 +269,6 @@ void GetProjectCommands(cmState* state)
state->AddBuiltinCommand("remove_definitions",
new cmRemoveDefinitionsCommand);
state->AddBuiltinCommand("source_group", new cmSourceGroupCommand);
- state->AddBuiltinCommand("target_compile_definitions",
- new cmTargetCompileDefinitionsCommand);
- state->AddBuiltinCommand("target_compile_features",
- new cmTargetCompileFeaturesCommand);
- state->AddBuiltinCommand("target_compile_options",
- new cmTargetCompileOptionsCommand);
- state->AddBuiltinCommand("target_include_directories",
- new cmTargetIncludeDirectoriesCommand);
- state->AddBuiltinCommand("target_sources", new cmTargetSourcesCommand);
state->AddDisallowedCommand(
"export_library_dependencies", new cmExportLibraryDependenciesCommand,
diff --git a/Source/cmCommonTargetGenerator.cxx b/Source/cmCommonTargetGenerator.cxx
index 391d65c40..1189606fc 100644
--- a/Source/cmCommonTargetGenerator.cxx
+++ b/Source/cmCommonTargetGenerator.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCommonTargetGenerator.h"
-#include "cmConfigure.h"
#include <set>
#include <sstream>
#include <utility>
@@ -22,10 +21,11 @@
cmCommonTargetGenerator::cmCommonTargetGenerator(cmGeneratorTarget* gt)
: GeneratorTarget(gt)
, Makefile(gt->Makefile)
- , LocalGenerator(static_cast<cmLocalCommonGenerator*>(gt->LocalGenerator))
- , GlobalGenerator(static_cast<cmGlobalCommonGenerator*>(
+ , LocalCommonGenerator(
+ static_cast<cmLocalCommonGenerator*>(gt->LocalGenerator))
+ , GlobalCommonGenerator(static_cast<cmGlobalCommonGenerator*>(
gt->LocalGenerator->GetGlobalGenerator()))
- , ConfigName(LocalGenerator->GetConfigName())
+ , ConfigName(LocalCommonGenerator->GetConfigName())
{
}
@@ -62,10 +62,10 @@ void cmCommonTargetGenerator::AddModuleDefinitionFlag(
// Append the flag and value. Use ConvertToLinkReference to help
// vs6's "cl -link" pass it to the linker.
std::string flag = defFileFlag;
- flag += this->LocalGenerator->ConvertToOutputFormat(
+ flag += this->LocalCommonGenerator->ConvertToOutputFormat(
linkLineComputer->ConvertToLinkReference(mdi->DefFile),
cmOutputConverter::SHELL);
- this->LocalGenerator->AppendFlags(flags, flag);
+ this->LocalCommonGenerator->AppendFlags(flags, flag);
}
void cmCommonTargetGenerator::AppendFortranFormatFlags(
@@ -78,7 +78,7 @@ void cmCommonTargetGenerator::AppendFortranFormatFlags(
const char* tgtfmt = this->GeneratorTarget->GetProperty("Fortran_FORMAT");
format = cmOutputConverter::GetFortranFormat(tgtfmt);
}
- const char* var = CM_NULLPTR;
+ const char* var = nullptr;
switch (format) {
case cmOutputConverter::FortranFormatFixed:
var = "CMAKE_Fortran_FORMAT_FIXED_FLAG";
@@ -90,8 +90,8 @@ void cmCommonTargetGenerator::AppendFortranFormatFlags(
break;
}
if (var) {
- this->LocalGenerator->AppendFlags(flags,
- this->Makefile->GetDefinition(var));
+ this->LocalCommonGenerator->AppendFlags(
+ flags, this->Makefile->GetDefinition(var));
}
}
@@ -101,8 +101,8 @@ std::string cmCommonTargetGenerator::GetFlags(const std::string& l)
if (i == this->FlagsByLanguage.end()) {
std::string flags;
- this->LocalGenerator->GetTargetCompileFlags(this->GeneratorTarget,
- this->ConfigName, l, flags);
+ this->LocalCommonGenerator->GetTargetCompileFlags(
+ this->GeneratorTarget, this->ConfigName, l, flags);
ByLanguageMap::value_type entry(l, flags);
i = this->FlagsByLanguage.insert(entry).first;
@@ -115,11 +115,11 @@ std::string cmCommonTargetGenerator::GetDefines(const std::string& l)
ByLanguageMap::iterator i = this->DefinesByLanguage.find(l);
if (i == this->DefinesByLanguage.end()) {
std::set<std::string> defines;
- this->LocalGenerator->GetTargetDefines(this->GeneratorTarget,
- this->ConfigName, l, defines);
+ this->LocalCommonGenerator->GetTargetDefines(this->GeneratorTarget,
+ this->ConfigName, l, defines);
std::string definesString;
- this->LocalGenerator->JoinDefines(defines, definesString, l);
+ this->LocalCommonGenerator->JoinDefines(defines, definesString, l);
ByLanguageMap::value_type entry(l, definesString);
i = this->DefinesByLanguage.insert(entry).first;
@@ -147,10 +147,8 @@ std::vector<std::string> cmCommonTargetGenerator::GetLinkedTargetDirectories()
if (cmComputeLinkInformation* cli =
this->GeneratorTarget->GetLinkInformation(this->ConfigName)) {
cmComputeLinkInformation::ItemVector const& items = cli->GetItems();
- for (cmComputeLinkInformation::ItemVector::const_iterator i =
- items.begin();
- i != items.end(); ++i) {
- cmGeneratorTarget const* linkee = i->Target;
+ for (auto const& item : items) {
+ cmGeneratorTarget const* linkee = item.Target;
if (linkee && !linkee->IsImported()
// We can ignore the INTERFACE_LIBRARY items because
// Target->GetLinkInformation already processed their
@@ -196,11 +194,12 @@ std::string cmCommonTargetGenerator::GetManifests()
this->GeneratorTarget->GetManifests(manifest_srcs, this->ConfigName);
std::vector<std::string> manifests;
- for (std::vector<cmSourceFile const*>::iterator mi = manifest_srcs.begin();
- mi != manifest_srcs.end(); ++mi) {
- manifests.push_back(this->LocalGenerator->ConvertToOutputFormat(
- this->LocalGenerator->ConvertToRelativePath(
- this->LocalGenerator->GetWorkingDirectory(), (*mi)->GetFullPath()),
+ manifests.reserve(manifest_srcs.size());
+ for (cmSourceFile const* manifest_src : manifest_srcs) {
+ manifests.push_back(this->LocalCommonGenerator->ConvertToOutputFormat(
+ this->LocalCommonGenerator->ConvertToRelativePath(
+ this->LocalCommonGenerator->GetWorkingDirectory(),
+ manifest_src->GetFullPath()),
cmOutputConverter::SHELL));
}
@@ -233,6 +232,6 @@ void cmCommonTargetGenerator::AppendOSXVerFlag(std::string& flags,
// Append the flag since a non-zero version is specified.
std::ostringstream vflag;
vflag << flag << major << "." << minor << "." << patch;
- this->LocalGenerator->AppendFlags(flags, vflag.str());
+ this->LocalCommonGenerator->AppendFlags(flags, vflag.str());
}
}
diff --git a/Source/cmCommonTargetGenerator.h b/Source/cmCommonTargetGenerator.h
index c36145fe2..6b0f74efd 100644
--- a/Source/cmCommonTargetGenerator.h
+++ b/Source/cmCommonTargetGenerator.h
@@ -37,8 +37,8 @@ protected:
cmGeneratorTarget* GeneratorTarget;
cmMakefile* Makefile;
- cmLocalCommonGenerator* LocalGenerator;
- cmGlobalCommonGenerator* GlobalGenerator;
+ cmLocalCommonGenerator* LocalCommonGenerator;
+ cmGlobalCommonGenerator* GlobalCommonGenerator;
std::string ConfigName;
void AppendFortranFormatFlags(std::string& flags,
diff --git a/Source/cmComputeComponentGraph.cxx b/Source/cmComputeComponentGraph.cxx
index a02d8854b..9ec98ae8e 100644
--- a/Source/cmComputeComponentGraph.cxx
+++ b/Source/cmComputeComponentGraph.cxx
@@ -57,8 +57,8 @@ void cmComputeComponentGraph::TarjanVisit(int i)
// Follow outgoing edges.
EdgeList const& nl = this->InputGraph[i];
- for (EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) {
- int j = *ni;
+ for (cmGraphEdge const& ni : nl) {
+ int j = ni;
// Ignore edges to nodes that have been reached by a previous DFS
// walk. Since we did not reach the current node from that walk
@@ -119,14 +119,14 @@ void cmComputeComponentGraph::TransferEdges()
for (int i = 0; i < n; ++i) {
int i_component = this->TarjanComponents[i];
EdgeList const& nl = this->InputGraph[i];
- for (EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) {
- int j = *ni;
+ for (cmGraphEdge const& ni : nl) {
+ int j = ni;
int j_component = this->TarjanComponents[j];
if (i_component != j_component) {
// We do not attempt to combine duplicate edges, but instead
// store the inter-component edges with suitable multiplicity.
this->ComponentGraph[i_component].push_back(
- cmGraphEdge(j_component, ni->IsStrong()));
+ cmGraphEdge(j_component, ni.IsStrong()));
}
}
}
diff --git a/Source/cmComputeLinkDepends.cxx b/Source/cmComputeLinkDepends.cxx
index 9c516ee8d..d9efc2e33 100644
--- a/Source/cmComputeLinkDepends.cxx
+++ b/Source/cmComputeLinkDepends.cxx
@@ -194,7 +194,7 @@ cmComputeLinkDepends::cmComputeLinkDepends(const cmGeneratorTarget* target,
this->OldLinkDirMode = false;
// No computation has been done.
- this->CCG = CM_NULLPTR;
+ this->CCG = nullptr;
}
cmComputeLinkDepends::~cmComputeLinkDepends()
@@ -286,7 +286,7 @@ std::map<std::string, int>::iterator cmComputeLinkDepends::AllocateLinkEntry(
std::map<std::string, int>::iterator lei =
this->LinkEntryIndex.insert(index_entry).first;
this->EntryList.push_back(LinkEntry());
- this->InferredDependSets.push_back(CM_NULLPTR);
+ this->InferredDependSets.push_back(nullptr);
this->EntryConstraintGraph.push_back(EdgeList());
return lei;
}
@@ -314,7 +314,7 @@ int cmComputeLinkDepends::AddLinkEntry(cmLinkItem const& item)
// If the item has dependencies queue it to follow them.
if (entry.Target) {
// Target dependencies are always known. Follow them.
- BFSEntry qe = { index, CM_NULLPTR };
+ BFSEntry qe = { index, nullptr };
this->BFSQueue.push(qe);
} else {
// Look for an old-style <item>_LIB_DEPENDS variable.
@@ -357,10 +357,8 @@ void cmComputeLinkDepends::FollowLinkEntry(BFSEntry qe)
this->FollowSharedDeps(depender_index, iface);
// Support for CMP0003.
- for (std::vector<cmLinkItem>::const_iterator oi =
- iface->WrongConfigLibraries.begin();
- oi != iface->WrongConfigLibraries.end(); ++oi) {
- this->CheckWrongConfigItem(*oi);
+ for (cmLinkItem const& oi : iface->WrongConfigLibraries) {
+ this->CheckWrongConfigItem(oi);
}
}
} else {
@@ -385,10 +383,9 @@ void cmComputeLinkDepends::FollowSharedDeps(int depender_index,
void cmComputeLinkDepends::QueueSharedDependencies(
int depender_index, std::vector<cmLinkItem> const& deps)
{
- for (std::vector<cmLinkItem>::const_iterator li = deps.begin();
- li != deps.end(); ++li) {
+ for (cmLinkItem const& li : deps) {
SharedDepEntry qe;
- qe.Item = *li;
+ qe.Item = li;
qe.DependerIndex = depender_index;
this->SharedDepQueue.push(qe);
}
@@ -445,25 +442,24 @@ void cmComputeLinkDepends::AddVarLinkEntries(int depender_index,
std::vector<cmLinkItem> actual_libs;
cmTargetLinkLibraryType llt = GENERAL_LibraryType;
bool haveLLT = false;
- for (std::vector<std::string>::const_iterator di = deplist.begin();
- di != deplist.end(); ++di) {
- if (*di == "debug") {
+ for (std::string const& d : deplist) {
+ if (d == "debug") {
llt = DEBUG_LibraryType;
haveLLT = true;
- } else if (*di == "optimized") {
+ } else if (d == "optimized") {
llt = OPTIMIZED_LibraryType;
haveLLT = true;
- } else if (*di == "general") {
+ } else if (d == "general") {
llt = GENERAL_LibraryType;
haveLLT = true;
- } else if (!di->empty()) {
+ } else if (!d.empty()) {
// If no explicit link type was given prior to this entry then
// check if the entry has its own link type variable. This is
// needed for compatibility with dependency files generated by
// the export_library_dependencies command from CMake 2.4 and
// lower.
if (!haveLLT) {
- std::string var = *di;
+ std::string var = d;
var += "_LINK_TYPE";
if (const char* val = this->Makefile->GetDefinition(var)) {
if (strcmp(val, "debug") == 0) {
@@ -476,10 +472,10 @@ void cmComputeLinkDepends::AddVarLinkEntries(int depender_index,
// If the library is meant for this link type then use it.
if (llt == GENERAL_LibraryType || llt == this->LinkType) {
- cmLinkItem item(*di, this->FindTargetToLink(depender_index, *di));
+ cmLinkItem item(d, this->FindTargetToLink(depender_index, d));
actual_libs.push_back(item);
} else if (this->OldLinkDirMode) {
- cmLinkItem item(*di, this->FindTargetToLink(depender_index, *di));
+ cmLinkItem item(d, this->FindTargetToLink(depender_index, d));
this->CheckWrongConfigItem(item);
}
@@ -499,10 +495,8 @@ void cmComputeLinkDepends::AddDirectLinkEntries()
cmLinkImplementation const* impl =
this->Target->GetLinkImplementation(this->Config);
this->AddLinkEntries(-1, impl->Libraries);
- for (std::vector<cmLinkItem>::const_iterator wi =
- impl->WrongConfigLibraries.begin();
- wi != impl->WrongConfigLibraries.end(); ++wi) {
- this->CheckWrongConfigItem(*wi);
+ for (cmLinkItem const& wi : impl->WrongConfigLibraries) {
+ this->CheckWrongConfigItem(wi);
}
}
@@ -514,17 +508,16 @@ void cmComputeLinkDepends::AddLinkEntries(int depender_index,
std::map<int, DependSet> dependSets;
// Loop over the libraries linked directly by the depender.
- for (typename std::vector<T>::const_iterator li = libs.begin();
- li != libs.end(); ++li) {
+ for (T const& l : libs) {
// Skip entries that will resolve to the target getting linked or
// are empty.
- cmLinkItem const& item = *li;
+ cmLinkItem const& item = l;
if (item == this->Target->GetName() || item.empty()) {
continue;
}
// Add a link entry for this item.
- int dependee_index = this->AddLinkEntry(*li);
+ int dependee_index = this->AddLinkEntry(l);
// The dependee must come after the depender.
if (depender_index >= 0) {
@@ -535,16 +528,15 @@ void cmComputeLinkDepends::AddLinkEntries(int depender_index,
}
// Update the inferred dependencies for earlier items.
- for (std::map<int, DependSet>::iterator dsi = dependSets.begin();
- dsi != dependSets.end(); ++dsi) {
+ for (auto& dependSet : dependSets) {
// Add this item to the inferred dependencies of other items.
// Target items are never inferred dependees because unknown
// items are outside libraries that should not be depending on
// targets.
if (!this->EntryList[dependee_index].Target &&
!this->EntryList[dependee_index].IsFlag &&
- dependee_index != dsi->first) {
- dsi->second.insert(dependee_index);
+ dependee_index != dependSet.first) {
+ dependSet.second.insert(dependee_index);
}
}
@@ -556,9 +548,8 @@ void cmComputeLinkDepends::AddLinkEntries(int depender_index,
}
// Store the inferred dependency sets discovered for this list.
- for (std::map<int, DependSet>::iterator dsi = dependSets.begin();
- dsi != dependSets.end(); ++dsi) {
- this->InferredDependSets[dsi->first]->push_back(dsi->second);
+ for (auto const& dependSet : dependSets) {
+ this->InferredDependSets[dependSet.first]->push_back(dependSet.second);
}
}
@@ -608,14 +599,14 @@ void cmComputeLinkDepends::InferDependencies()
void cmComputeLinkDepends::CleanConstraintGraph()
{
- for (Graph::iterator i = this->EntryConstraintGraph.begin();
- i != this->EntryConstraintGraph.end(); ++i) {
+ for (cmGraphEdgeList& edgeList : this->EntryConstraintGraph) {
// Sort the outgoing edges for each graph node so that the
// original order will be preserved as much as possible.
- std::sort(i->begin(), i->end());
+ std::sort(edgeList.begin(), edgeList.end());
// Make the edge list unique.
- i->erase(std::unique(i->begin(), i->end()), i->end());
+ edgeList.erase(std::unique(edgeList.begin(), edgeList.end()),
+ edgeList.end());
}
}
@@ -660,9 +651,8 @@ void cmComputeLinkDepends::OrderLinkEntires()
}
// Start with the original link line.
- for (std::vector<int>::const_iterator i = this->OriginalEntries.begin();
- i != this->OriginalEntries.end(); ++i) {
- this->VisitEntry(*i);
+ for (int originalEntry : this->OriginalEntries) {
+ this->VisitEntry(originalEntry);
}
// Now explore anything left pending. Since the component graph is
@@ -684,13 +674,12 @@ void cmComputeLinkDepends::DisplayComponents()
for (unsigned int c = 0; c < components.size(); ++c) {
fprintf(stderr, "Component (%u):\n", c);
NodeList const& nl = components[c];
- for (NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) {
- int i = *ni;
+ for (int i : nl) {
fprintf(stderr, " item %d [%s]\n", i, this->EntryList[i].Item.c_str());
}
EdgeList const& ol = this->CCG->GetComponentGraphEdges(c);
- for (EdgeList::const_iterator oi = ol.begin(); oi != ol.end(); ++oi) {
- int i = *oi;
+ for (cmGraphEdge const& oi : ol) {
+ int i = oi;
fprintf(stderr, " followed by Component (%d)\n", i);
}
fprintf(stderr, " topo order index %d\n", this->ComponentOrder[c]);
@@ -771,10 +760,10 @@ void cmComputeLinkDepends::VisitEntry(int index)
// are now pending.
if (completed) {
EdgeList const& ol = this->CCG->GetComponentGraphEdges(component);
- for (EdgeList::const_iterator oi = ol.begin(); oi != ol.end(); ++oi) {
+ for (cmGraphEdge const& oi : ol) {
// This entire component is now pending no matter whether it has
// been partially seen already.
- this->MakePendingComponent(*oi);
+ this->MakePendingComponent(oi);
}
}
}
@@ -816,8 +805,8 @@ cmComputeLinkDepends::MakePendingComponent(unsigned int component)
int cmComputeLinkDepends::ComputeComponentCount(NodeList const& nl)
{
unsigned int count = 2;
- for (NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) {
- if (cmGeneratorTarget const* target = this->EntryList[*ni].Target) {
+ for (int ni : nl) {
+ if (cmGeneratorTarget const* target = this->EntryList[ni].Target) {
if (cmLinkInterface const* iface =
target->GetLinkInterface(this->Config, this->Target)) {
if (iface->Multiplicity > count) {
@@ -832,13 +821,11 @@ int cmComputeLinkDepends::ComputeComponentCount(NodeList const& nl)
void cmComputeLinkDepends::DisplayFinalEntries()
{
fprintf(stderr, "target [%s] links to:\n", this->Target->GetName().c_str());
- for (std::vector<LinkEntry>::const_iterator lei =
- this->FinalLinkEntries.begin();
- lei != this->FinalLinkEntries.end(); ++lei) {
- if (lei->Target) {
- fprintf(stderr, " target [%s]\n", lei->Target->GetName().c_str());
+ for (LinkEntry const& lei : this->FinalLinkEntries) {
+ if (lei.Target) {
+ fprintf(stderr, " target [%s]\n", lei.Target->GetName().c_str());
} else {
- fprintf(stderr, " item [%s]\n", lei->Item.c_str());
+ fprintf(stderr, " item [%s]\n", lei.Item.c_str());
}
}
fprintf(stderr, "\n");
diff --git a/Source/cmComputeLinkDepends.h b/Source/cmComputeLinkDepends.h
index 84ee9161f..dd0e02943 100644
--- a/Source/cmComputeLinkDepends.h
+++ b/Source/cmComputeLinkDepends.h
@@ -40,7 +40,7 @@ public:
bool IsFlag;
LinkEntry()
: Item()
- , Target(CM_NULLPTR)
+ , Target(nullptr)
, IsSharedDep(false)
, IsFlag(false)
{
diff --git a/Source/cmComputeLinkInformation.cxx b/Source/cmComputeLinkInformation.cxx
index b2deaaa85..fb13a585b 100644
--- a/Source/cmComputeLinkInformation.cxx
+++ b/Source/cmComputeLinkInformation.cxx
@@ -260,7 +260,7 @@ cmComputeLinkInformation::cmComputeLinkInformation(
this->GlobalGenerator, target, "linker search path");
this->OrderRuntimeSearchPath = new cmOrderDirectories(
this->GlobalGenerator, target, "runtime search path");
- this->OrderDependentRPath = CM_NULLPTR;
+ this->OrderDependentRPath = nullptr;
// Get the language used for linking this target.
this->LinkLanguage = this->Target->GetLinkerLanguage(config);
@@ -281,7 +281,7 @@ 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 = CM_NULLPTR;
+ this->LoaderFlag = nullptr;
if (!this->UseImportLibrary &&
this->Target->GetType() == cmStateEnums::MODULE_LIBRARY) {
std::string loader_flag_var = "CMAKE_SHARED_MODULE_LOADER_";
@@ -468,13 +468,11 @@ bool cmComputeLinkInformation::Compute()
cmComputeLinkDepends::EntryVector const& linkEntries = cld.Compute();
// Add the link line items.
- for (cmComputeLinkDepends::EntryVector::const_iterator lei =
- linkEntries.begin();
- lei != linkEntries.end(); ++lei) {
- if (lei->IsSharedDep) {
- this->AddSharedDepItem(lei->Item, lei->Target);
+ for (cmComputeLinkDepends::LinkEntry const& linkEntry : linkEntries) {
+ if (linkEntry.IsSharedDep) {
+ this->AddSharedDepItem(linkEntry.Item, linkEntry.Target);
} else {
- this->AddItem(lei->Item, lei->Target);
+ this->AddItem(linkEntry.Item, linkEntry.Target);
}
}
@@ -494,10 +492,7 @@ bool cmComputeLinkInformation::Compute()
// directories.
std::set<cmGeneratorTarget const*> const& wrongItems =
cld.GetOldWrongConfigItems();
- for (std::set<cmGeneratorTarget const*>::const_iterator i =
- wrongItems.begin();
- i != wrongItems.end(); ++i) {
- cmGeneratorTarget const* tgt = *i;
+ for (cmGeneratorTarget const* tgt : wrongItems) {
bool implib = (this->UseImportLibrary &&
(tgt->GetType() == cmStateEnums::SHARED_LIBRARY));
cmStateEnums::ArtifactType artifact = implib
@@ -540,11 +535,10 @@ void cmComputeLinkInformation::AddImplicitLinkInfo()
// The link closure lists all languages whose implicit info is needed.
cmGeneratorTarget::LinkClosure const* lc =
this->Target->GetLinkClosure(this->Config);
- for (std::vector<std::string>::const_iterator li = lc->Languages.begin();
- li != lc->Languages.end(); ++li) {
+ for (std::string const& li : lc->Languages) {
// Skip those of the linker language. They are implicit.
- if (*li != this->LinkLanguage) {
- this->AddImplicitLinkInfo(*li);
+ if (li != this->LinkLanguage) {
+ this->AddImplicitLinkInfo(li);
}
}
}
@@ -559,10 +553,9 @@ void cmComputeLinkInformation::AddImplicitLinkInfo(std::string const& lang)
if (const char* libs = this->Makefile->GetDefinition(libVar)) {
std::vector<std::string> libsVec;
cmSystemTools::ExpandListArgument(libs, libsVec);
- for (std::vector<std::string>::const_iterator i = libsVec.begin();
- i != libsVec.end(); ++i) {
- if (this->ImplicitLinkLibs.find(*i) == this->ImplicitLinkLibs.end()) {
- this->AddItem(*i, CM_NULLPTR);
+ for (std::string const& i : libsVec) {
+ if (this->ImplicitLinkLibs.find(i) == this->ImplicitLinkLibs.end()) {
+ this->AddItem(i, nullptr);
}
}
}
@@ -616,7 +609,7 @@ void cmComputeLinkInformation::AddItem(std::string const& item,
// Also add the item the interface specifies to be used in its place.
std::string const& libName = tgt->GetImportedLibName(config);
if (!libName.empty()) {
- this->AddItem(libName, CM_NULLPTR);
+ this->AddItem(libName, nullptr);
}
} else {
// Decide whether to use an import library.
@@ -710,7 +703,7 @@ void cmComputeLinkInformation::AddSharedDepItem(std::string const& item,
// Check if we need to include the dependent shared library in other
// path ordering.
- cmOrderDirectories* order = CM_NULLPTR;
+ cmOrderDirectories* order = nullptr;
if (this->SharedDependencyMode == SharedDepModeLibDir &&
!this->LinkWithRuntimePath /* AddLibraryRuntimeInfo adds it */) {
// Add the item to the linker search path.
@@ -722,7 +715,7 @@ void cmComputeLinkInformation::AddSharedDepItem(std::string const& item,
if (order) {
if (tgt) {
std::string soName = tgt->GetSOName(this->Config);
- const char* soname = soName.empty() ? CM_NULLPTR : soName.c_str();
+ const char* soname = soName.empty() ? nullptr : soName.c_str();
order->AddRuntimeLibrary(lib, soname);
} else {
order->AddRuntimeLibrary(lib);
@@ -741,9 +734,9 @@ void cmComputeLinkInformation::ComputeLinkTypeInfo()
this->LinkTypeEnabled = false;
// Lookup link type selection flags.
- const char* static_link_type_flag = CM_NULLPTR;
- const char* shared_link_type_flag = CM_NULLPTR;
- const char* target_type_str = CM_NULLPTR;
+ const char* static_link_type_flag = nullptr;
+ const char* shared_link_type_flag = nullptr;
+ const char* target_type_str = nullptr;
switch (this->Target->GetType()) {
case cmStateEnums::EXECUTABLE:
target_type_str = "EXE";
@@ -811,18 +804,16 @@ void cmComputeLinkInformation::ComputeItemParserInfo()
mf->GetDefinition("CMAKE_EXTRA_LINK_EXTENSIONS")) {
std::vector<std::string> linkSuffixVec;
cmSystemTools::ExpandListArgument(linkSuffixes, linkSuffixVec);
- for (std::vector<std::string>::iterator i = linkSuffixVec.begin();
- i != linkSuffixVec.end(); ++i) {
- this->AddLinkExtension(i->c_str(), LinkUnknown);
+ for (std::string const& i : linkSuffixVec) {
+ this->AddLinkExtension(i.c_str(), LinkUnknown);
}
}
if (const char* sharedSuffixes =
mf->GetDefinition("CMAKE_EXTRA_SHARED_LIBRARY_SUFFIXES")) {
std::vector<std::string> sharedSuffixVec;
cmSystemTools::ExpandListArgument(sharedSuffixes, sharedSuffixVec);
- for (std::vector<std::string>::iterator i = sharedSuffixVec.begin();
- i != sharedSuffixVec.end(); ++i) {
- this->AddLinkExtension(i->c_str(), LinkShared);
+ for (std::string const& i : sharedSuffixVec) {
+ this->AddLinkExtension(i.c_str(), LinkShared);
}
}
@@ -840,9 +831,8 @@ void cmComputeLinkInformation::ComputeItemParserInfo()
// be the library name. Match index 3 will be the library
// extension.
reg = "^(";
- for (std::set<std::string>::iterator p = this->LinkPrefixes.begin();
- p != this->LinkPrefixes.end(); ++p) {
- reg += *p;
+ for (std::string const& p : this->LinkPrefixes) {
+ reg += p;
reg += "|";
}
reg += ")";
@@ -906,8 +896,7 @@ std::string cmComputeLinkInformation::CreateExtensionRegex(
// Build a list of extension choices.
std::string libext = "(";
const char* sep = "";
- for (std::vector<std::string>::const_iterator i = exts.begin();
- i != exts.end(); ++i) {
+ for (std::string const& i : exts) {
// Separate this choice from the previous one.
libext += sep;
sep = "|";
@@ -915,9 +904,9 @@ std::string cmComputeLinkInformation::CreateExtensionRegex(
// Store this extension choice with the "." escaped.
libext += "\\";
#if defined(_WIN32) && !defined(__CYGWIN__)
- libext += this->NoCaseExpression(i->c_str());
+ libext += this->NoCaseExpression(i.c_str());
#else
- libext += *i;
+ libext += i;
#endif
}
@@ -1457,10 +1446,8 @@ bool cmComputeLinkInformation::FinishLinkerSearchDirectories()
}
// Add the link directories for full path items.
- for (std::vector<std::string>::const_iterator i =
- this->OldLinkDirItems.begin();
- i != this->OldLinkDirItems.end(); ++i) {
- this->OrderLinkerSearchPath->AddLinkLibrary(*i);
+ for (std::string const& i : this->OldLinkDirItems) {
+ this->OrderLinkerSearchPath->AddLinkLibrary(i);
}
return true;
}
@@ -1489,19 +1476,17 @@ void cmComputeLinkInformation::PrintLinkPolicyDiagnosis(std::ostream& os)
std::string::size_type max_size = 76;
std::string line;
const char* sep = " ";
- for (std::vector<std::string>::const_iterator i =
- this->OldUserFlagItems.begin();
- i != this->OldUserFlagItems.end(); ++i) {
+ for (std::string const& i : this->OldUserFlagItems) {
// If the addition of another item will exceed the limit then
// output the current line and reset it. Note that the separator
// is either " " or ", " which is always 2 characters.
- if (!line.empty() && (line.size() + i->size() + 2) > max_size) {
+ if (!line.empty() && (line.size() + i.size() + 2) > max_size) {
os << line << "\n";
sep = " ";
- line = "";
+ line.clear();
}
line += sep;
- line += *i;
+ line += i;
// Convert to the other separator.
sep = ", ";
}
@@ -1513,11 +1498,9 @@ void cmComputeLinkInformation::PrintLinkPolicyDiagnosis(std::ostream& os)
// List the paths old behavior is adding.
os << "and other libraries with known full path:\n";
std::set<std::string> emitted;
- for (std::vector<std::string>::const_iterator i =
- this->OldLinkDirItems.begin();
- i != this->OldLinkDirItems.end(); ++i) {
- if (emitted.insert(cmSystemTools::GetFilenamePath(*i)).second) {
- os << " " << *i << "\n";
+ for (std::string const& i : this->OldLinkDirItems) {
+ if (emitted.insert(cmSystemTools::GetFilenamePath(i)).second) {
+ os << " " << i << "\n";
}
}
@@ -1544,9 +1527,8 @@ void cmComputeLinkInformation::LoadImplicitLinkInfo()
// and add them to the set
if (const char* libraryArch =
this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
- for (std::vector<std::string>::const_iterator i = implicitDirVec.begin();
- i != implicitDirVec.end(); ++i) {
- this->ImplicitLinkDirs.insert(*i + "/" + libraryArch);
+ for (std::string const& i : implicitDirVec) {
+ this->ImplicitLinkDirs.insert(i + "/" + libraryArch);
}
}
@@ -1573,11 +1555,9 @@ void cmComputeLinkInformation::LoadImplicitLinkInfo()
}
// Store implicit link libraries.
- for (std::vector<std::string>::const_iterator i = implicitLibVec.begin();
- i != implicitLibVec.end(); ++i) {
+ for (std::string const& item : implicitLibVec) {
// Items starting in '-' but not '-l' are flags, not libraries,
// and should not be filtered by this implicit list.
- std::string const& item = *i;
if (item[0] != '-' || item[1] == 'l') {
this->ImplicitLinkLibs.insert(item);
}
@@ -1623,7 +1603,7 @@ void cmComputeLinkInformation::AddLibraryRuntimeInfo(
// Try to get the soname of the library. Only files with this name
// could possibly conflict.
std::string soName = target->GetSOName(this->Config);
- const char* soname = soName.empty() ? CM_NULLPTR : soName.c_str();
+ const char* soname = soName.empty() ? nullptr : soName.c_str();
// Include this library in the runtime path ordering.
this->OrderRuntimeSearchPath->AddRuntimeLibrary(fullPath, soname);
@@ -1694,10 +1674,9 @@ static void cmCLI_ExpandListUnique(const char* str,
{
std::vector<std::string> tmp;
cmSystemTools::ExpandListArgument(str, tmp);
- for (std::vector<std::string>::iterator i = tmp.begin(); i != tmp.end();
- ++i) {
- if (emitted.insert(*i).second) {
- out.push_back(*i);
+ for (std::string const& i : tmp) {
+ if (emitted.insert(i).second) {
+ out.push_back(i);
}
}
}
@@ -1750,12 +1729,11 @@ void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs,
this->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
cmSystemTools::ConvertToUnixSlashes(rootPath);
std::vector<std::string> const& rdirs = this->GetRuntimeSearchPath();
- for (std::vector<std::string>::const_iterator ri = rdirs.begin();
- ri != rdirs.end(); ++ri) {
+ for (std::string const& ri : rdirs) {
// Put this directory in the rpath if using build-tree rpath
// support or if using the link path as an rpath.
if (use_build_rpath) {
- std::string d = *ri;
+ std::string d = ri;
if (!rootPath.empty() && d.find(rootPath) == 0) {
d = d.substr(rootPath.size());
} else if (stagePath && *stagePath && d.find(stagePath) == 0) {
@@ -1773,11 +1751,11 @@ void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs,
const char* topSourceDir = this->CMakeInstance->GetHomeDirectory();
const char* topBinaryDir =
this->CMakeInstance->GetHomeOutputDirectory();
- if (!cmSystemTools::ComparePath(*ri, topSourceDir) &&
- !cmSystemTools::ComparePath(*ri, topBinaryDir) &&
- !cmSystemTools::IsSubDirectory(*ri, topSourceDir) &&
- !cmSystemTools::IsSubDirectory(*ri, topBinaryDir)) {
- std::string d = *ri;
+ if (!cmSystemTools::ComparePath(ri, topSourceDir) &&
+ !cmSystemTools::ComparePath(ri, topBinaryDir) &&
+ !cmSystemTools::IsSubDirectory(ri, topSourceDir) &&
+ !cmSystemTools::IsSubDirectory(ri, topBinaryDir)) {
+ std::string d = ri;
if (!rootPath.empty() && d.find(rootPath) == 0) {
d = d.substr(rootPath.size());
} else if (stagePath && *stagePath && d.find(stagePath) == 0) {
@@ -1800,12 +1778,11 @@ void cmComputeLinkInformation::GetRPath(std::vector<std::string>& runtimeDirs,
{
cmGeneratorTarget::LinkClosure const* lc =
this->Target->GetLinkClosure(this->Config);
- for (std::vector<std::string>::const_iterator li = lc->Languages.begin();
- li != lc->Languages.end(); ++li) {
+ for (std::string const& li : lc->Languages) {
std::string useVar =
- "CMAKE_" + *li + "_USE_IMPLICIT_LINK_DIRECTORIES_IN_RUNTIME_PATH";
+ "CMAKE_" + li + "_USE_IMPLICIT_LINK_DIRECTORIES_IN_RUNTIME_PATH";
if (this->Makefile->IsOn(useVar)) {
- std::string dirVar = "CMAKE_" + *li + "_IMPLICIT_LINK_DIRECTORIES";
+ std::string dirVar = "CMAKE_" + li + "_IMPLICIT_LINK_DIRECTORIES";
if (const char* dirs = this->Makefile->GetDefinition(dirVar)) {
cmCLI_ExpandListUnique(dirs, runtimeDirs, emitted);
}
diff --git a/Source/cmComputeLinkInformation.h b/Source/cmComputeLinkInformation.h
index 00e3ad265..f8c62145e 100644
--- a/Source/cmComputeLinkInformation.h
+++ b/Source/cmComputeLinkInformation.h
@@ -33,11 +33,11 @@ public:
Item()
: Value()
, IsPath(true)
- , Target(CM_NULLPTR)
+ , Target(nullptr)
{
}
Item(std::string const& v, bool p,
- cmGeneratorTarget const* target = CM_NULLPTR)
+ cmGeneratorTarget const* target = nullptr)
: Value(v)
, IsPath(p)
, Target(target)
diff --git a/Source/cmComputeTargetDepends.cxx b/Source/cmComputeTargetDepends.cxx
index ff19eac63..963c2df88 100644
--- a/Source/cmComputeTargetDepends.cxx
+++ b/Source/cmComputeTargetDepends.cxx
@@ -148,10 +148,10 @@ void cmComputeTargetDepends::GetTargetDirectDepends(cmGeneratorTarget const* t,
// Get its final dependencies.
EdgeList const& nl = this->FinalGraph[i];
- for (EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) {
- cmGeneratorTarget const* dep = this->Targets[*ni];
+ for (cmGraphEdge const& ni : nl) {
+ cmGeneratorTarget const* dep = this->Targets[ni];
cmTargetDependSet::iterator di = deps.insert(dep).first;
- di->SetType(ni->IsStrong());
+ di->SetType(ni.IsStrong());
}
}
@@ -160,15 +160,13 @@ void cmComputeTargetDepends::CollectTargets()
// Collect all targets from all generators.
std::vector<cmLocalGenerator*> const& lgens =
this->GlobalGenerator->GetLocalGenerators();
- for (unsigned int i = 0; i < lgens.size(); ++i) {
- const std::vector<cmGeneratorTarget*> targets =
- lgens[i]->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin();
- ti != targets.end(); ++ti) {
- cmGeneratorTarget* gt = *ti;
+ for (cmLocalGenerator* lgen : lgens) {
+ const std::vector<cmGeneratorTarget*>& targets =
+ lgen->GetGeneratorTargets();
+ for (cmGeneratorTarget const* ti : targets) {
int index = static_cast<int>(this->Targets.size());
- this->TargetIndex[gt] = index;
- this->Targets.push_back(gt);
+ this->TargetIndex[ti] = index;
+ this->Targets.push_back(ti);
}
}
}
@@ -204,14 +202,11 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index)
if (configs.empty()) {
configs.push_back("");
}
- for (std::vector<std::string>::const_iterator it = configs.begin();
- it != configs.end(); ++it) {
+ for (std::string const& it : configs) {
std::vector<cmSourceFile const*> objectFiles;
- depender->GetExternalObjects(objectFiles, *it);
- for (std::vector<cmSourceFile const*>::const_iterator oi =
- objectFiles.begin();
- oi != objectFiles.end(); ++oi) {
- std::string objLib = (*oi)->GetObjectLibrary();
+ depender->GetExternalObjects(objectFiles, it);
+ for (cmSourceFile const* o : objectFiles) {
+ std::string objLib = o->GetObjectLibrary();
if (!objLib.empty() && emitted.insert(objLib).second) {
if (depender->GetType() != cmStateEnums::EXECUTABLE &&
depender->GetType() != cmStateEnums::STATIC_LIBRARY &&
@@ -228,17 +223,15 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index)
}
}
- cmLinkImplementation const* impl = depender->GetLinkImplementation(*it);
+ cmLinkImplementation const* impl = depender->GetLinkImplementation(it);
// A target should not depend on itself.
emitted.insert(depender->GetName());
- for (std::vector<cmLinkImplItem>::const_iterator lib =
- impl->Libraries.begin();
- lib != impl->Libraries.end(); ++lib) {
+ for (cmLinkImplItem const& lib : impl->Libraries) {
// Don't emit the same library twice for this target.
- if (emitted.insert(*lib).second) {
- this->AddTargetDepend(depender_index, *lib, true);
- this->AddInterfaceDepends(depender_index, *lib, *it, emitted);
+ if (emitted.insert(lib).second) {
+ this->AddTargetDepend(depender_index, lib, true);
+ this->AddInterfaceDepends(depender_index, lib, it, emitted);
}
}
}
@@ -250,11 +243,10 @@ void cmComputeTargetDepends::CollectTargetDepends(int depender_index)
std::set<std::string> emitted;
// A target should not depend on itself.
emitted.insert(depender->GetName());
- for (std::set<cmLinkItem>::const_iterator util = tutils.begin();
- util != tutils.end(); ++util) {
+ for (cmLinkItem const& litem : tutils) {
// Don't emit the same utility twice for this target.
- if (emitted.insert(*util).second) {
- this->AddTargetDepend(depender_index, *util, false);
+ if (emitted.insert(litem).second) {
+ this->AddTargetDepend(depender_index, litem, false);
}
}
}
@@ -267,13 +259,11 @@ void cmComputeTargetDepends::AddInterfaceDepends(
cmGeneratorTarget const* depender = this->Targets[depender_index];
if (cmLinkInterface const* iface =
dependee->GetLinkInterface(config, depender)) {
- for (std::vector<cmLinkItem>::const_iterator lib =
- iface->Libraries.begin();
- lib != iface->Libraries.end(); ++lib) {
+ for (cmLinkItem const& lib : iface->Libraries) {
// Don't emit the same library twice for this target.
- if (emitted.insert(*lib).second) {
- this->AddTargetDepend(depender_index, *lib, true);
- this->AddInterfaceDepends(depender_index, *lib, config, emitted);
+ if (emitted.insert(lib).second) {
+ this->AddTargetDepend(depender_index, lib, true);
+ this->AddInterfaceDepends(depender_index, lib, config, emitted);
}
}
}
@@ -290,7 +280,7 @@ void cmComputeTargetDepends::AddInterfaceDepends(
// within the project.
if (dependee && dependee->GetType() == cmStateEnums::EXECUTABLE &&
!dependee->IsExecutableWithExports()) {
- dependee = CM_NULLPTR;
+ dependee = nullptr;
}
if (dependee) {
@@ -348,7 +338,7 @@ void cmComputeTargetDepends::AddTargetDepend(int depender_index,
// within the project.
if (linking && dependee && dependee->GetType() == cmStateEnums::EXECUTABLE &&
!dependee->IsExecutableWithExports()) {
- dependee = CM_NULLPTR;
+ dependee = nullptr;
}
if (dependee) {
@@ -365,9 +355,8 @@ void cmComputeTargetDepends::AddTargetDepend(int depender_index,
// Skip IMPORTED and INTERFACE targets but follow their utility
// dependencies.
std::set<cmLinkItem> const& utils = dependee->GetUtilityItems();
- for (std::set<cmLinkItem>::const_iterator i = utils.begin();
- i != utils.end(); ++i) {
- if (cmGeneratorTarget const* transitive_dependee = i->Target) {
+ for (cmLinkItem const& i : utils) {
+ if (cmGeneratorTarget const* transitive_dependee = i.Target) {
this->AddTargetDepend(depender_index, transitive_dependee, false);
}
}
@@ -395,11 +384,11 @@ void cmComputeTargetDepends::DisplayGraph(Graph const& graph,
cmGeneratorTarget const* depender = this->Targets[depender_index];
fprintf(stderr, "target %d is [%s]\n", depender_index,
depender->GetName().c_str());
- for (EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) {
- int dependee_index = *ni;
+ for (cmGraphEdge const& ni : nl) {
+ int dependee_index = ni;
cmGeneratorTarget const* dependee = this->Targets[dependee_index];
fprintf(stderr, " depends on target %d [%s] (%s)\n", dependee_index,
- dependee->GetName().c_str(), ni->IsStrong() ? "strong" : "weak");
+ dependee->GetName().c_str(), ni.IsStrong() ? "strong" : "weak");
}
}
fprintf(stderr, "\n");
@@ -414,8 +403,7 @@ void cmComputeTargetDepends::DisplayComponents(
for (int c = 0; c < n; ++c) {
NodeList const& nl = components[c];
fprintf(stderr, "Component (%d):\n", c);
- for (NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) {
- int i = *ni;
+ for (int i : nl) {
fprintf(stderr, " contains target %d [%s]\n", i,
this->Targets[i]->GetName().c_str());
}
@@ -446,8 +434,8 @@ bool cmComputeTargetDepends::CheckComponents(
}
// Make sure the component is all STATIC_LIBRARY targets.
- for (NodeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) {
- if (this->Targets[*ni]->GetType() != cmStateEnums::STATIC_LIBRARY) {
+ for (int ni : nl) {
+ if (this->Targets[ni]->GetType() != cmStateEnums::STATIC_LIBRARY) {
this->ComplainAboutBadComponent(ccg, c);
return false;
}
@@ -466,9 +454,8 @@ void cmComputeTargetDepends::ComplainAboutBadComponent(
std::vector<NodeList> const& components = ccg.GetComponents();
std::vector<int> const& cmap = ccg.GetComponentMap();
NodeList const& cl = components[c];
- for (NodeList::const_iterator ci = cl.begin(); ci != cl.end(); ++ci) {
+ for (int i : cl) {
// Get the depender.
- int i = *ci;
cmGeneratorTarget const* depender = this->Targets[i];
// Describe the depender.
@@ -477,12 +464,12 @@ void cmComputeTargetDepends::ComplainAboutBadComponent(
// List its dependencies that are inside the component.
EdgeList const& nl = this->InitialGraph[i];
- for (EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) {
- int j = *ni;
+ for (cmGraphEdge const& ni : nl) {
+ int j = ni;
if (cmap[j] == c) {
cmGeneratorTarget const* dependee = this->Targets[j];
e << " depends on \"" << dependee->GetName() << "\""
- << " (" << (ni->IsStrong() ? "strong" : "weak") << ")\n";
+ << " (" << (ni.IsStrong() ? "strong" : "weak") << ")\n";
}
}
}
@@ -514,9 +501,9 @@ bool cmComputeTargetDepends::IntraComponent(std::vector<int> const& cmap,
if (emitted.insert(i).second) {
// Honor strong intra-component edges in the final order.
EdgeList const& el = this->InitialGraph[i];
- for (EdgeList::const_iterator ei = el.begin(); ei != el.end(); ++ei) {
- int j = *ei;
- if (cmap[j] == c && ei->IsStrong()) {
+ for (cmGraphEdge const& edge : el) {
+ int j = edge;
+ if (cmap[j] == c && edge.IsStrong()) {
this->FinalGraph[i].push_back(cmGraphEdge(j, true));
if (!this->IntraComponent(cmap, c, j, head, emitted, visited)) {
return false;
@@ -573,11 +560,11 @@ bool cmComputeTargetDepends::ComputeFinalDepends(
++depender_component) {
int depender_component_tail = this->ComponentTail[depender_component];
EdgeList const& nl = cgraph[depender_component];
- for (EdgeList::const_iterator ni = nl.begin(); ni != nl.end(); ++ni) {
- int dependee_component = *ni;
+ for (cmGraphEdge const& ni : nl) {
+ int dependee_component = ni;
int dependee_component_head = this->ComponentHead[dependee_component];
this->FinalGraph[depender_component_tail].push_back(
- cmGraphEdge(dependee_component_head, ni->IsStrong()));
+ cmGraphEdge(dependee_component_head, ni.IsStrong()));
}
}
return true;
diff --git a/Source/cmConditionEvaluator.cxx b/Source/cmConditionEvaluator.cxx
index 2bacf7321..90b3f6d9a 100644
--- a/Source/cmConditionEvaluator.cxx
+++ b/Source/cmConditionEvaluator.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmConditionEvaluator.h"
-#include "cmConfigure.h"
#include "cmsys/RegularExpression.hxx"
#include <algorithm>
#include <sstream>
@@ -84,7 +83,7 @@ bool cmConditionEvaluator::IsTrue(
const std::vector<cmExpandedCommandArgument>& args, std::string& errorString,
cmake::MessageType& status)
{
- errorString = "";
+ errorString.clear();
// handle empty invocation
if (args.empty()) {
@@ -139,7 +138,7 @@ const char* cmConditionEvaluator::GetDefinitionIfUnquoted(
if ((this->Policy54Status != cmPolicies::WARN &&
this->Policy54Status != cmPolicies::OLD) &&
argument.WasQuoted()) {
- return CM_NULLPTR;
+ return nullptr;
}
const char* def = this->Makefile.GetDefinition(argument.GetValue());
@@ -455,7 +454,7 @@ bool cmConditionEvaluator::HandleLevel1(cmArgumentList& newArgs, std::string&,
if (this->IsKeyword(keyCOMMAND, *arg) && argP1 != newArgs.end()) {
cmCommand* command =
this->Makefile.GetState()->GetCommand(argP1->c_str());
- this->HandlePredicate(command != CM_NULLPTR, reducible, arg, newArgs,
+ this->HandlePredicate(command != nullptr, reducible, arg, newArgs,
argP1, argP2);
}
// does a policy exist
@@ -467,7 +466,7 @@ bool cmConditionEvaluator::HandleLevel1(cmArgumentList& newArgs, std::string&,
// does a target exist
if (this->IsKeyword(keyTARGET, *arg) && argP1 != newArgs.end()) {
this->HandlePredicate(
- this->Makefile.FindTargetToUse(argP1->GetValue()) != CM_NULLPTR,
+ this->Makefile.FindTargetToUse(argP1->GetValue()) != nullptr,
reducible, arg, newArgs, argP1, argP2);
}
// does a test exist
@@ -475,8 +474,8 @@ bool cmConditionEvaluator::HandleLevel1(cmArgumentList& newArgs, std::string&,
this->Policy64Status != cmPolicies::WARN) {
if (this->IsKeyword(keyTEST, *arg) && argP1 != newArgs.end()) {
const cmTest* haveTest = this->Makefile.GetTest(argP1->c_str());
- this->HandlePredicate(haveTest != CM_NULLPTR, reducible, arg,
- newArgs, argP1, argP2);
+ this->HandlePredicate(haveTest != nullptr, reducible, arg, newArgs,
+ argP1, argP2);
}
} else if (this->Policy64Status == cmPolicies::WARN &&
this->IsKeyword(keyTEST, *arg)) {
diff --git a/Source/cmConfigure.cmake.h.in b/Source/cmConfigure.cmake.h.in
index 524fdf808..9a78aca36 100644
--- a/Source/cmConfigure.cmake.h.in
+++ b/Source/cmConfigure.cmake.h.in
@@ -19,51 +19,25 @@
#cmakedefine HAVE_UNSETENV
#cmakedefine CMAKE_USE_ELF_PARSER
#cmakedefine CMAKE_USE_MACH_PARSER
-#cmakedefine CMAKE_USE_LIBUV
-#cmakedefine CMake_HAVE_CXX_AUTO_PTR
-#cmakedefine CMake_HAVE_CXX_EQ_DELETE
#cmakedefine CMake_HAVE_CXX_FALLTHROUGH
#cmakedefine CMake_HAVE_CXX_GNU_FALLTHROUGH
#cmakedefine CMake_HAVE_CXX_ATTRIBUTE_FALLTHROUGH
#cmakedefine CMake_HAVE_CXX_MAKE_UNIQUE
-#cmakedefine CMake_HAVE_CXX_NULLPTR
-#cmakedefine CMake_HAVE_CXX_OVERRIDE
-#cmakedefine CMake_HAVE_CXX_UNIQUE_PTR
-#cmakedefine CMake_HAVE_CXX_UNORDERED_MAP
-#cmakedefine CMake_HAVE_CXX_UNORDERED_SET
#define CMAKE_BIN_DIR "/@CMAKE_BIN_DIR@"
#define CMAKE_DATA_DIR "/@CMAKE_DATA_DIR@"
-#ifdef CMake_HAVE_CXX_EQ_DELETE
-#define CM_EQ_DELETE = delete
-#else
-#define CM_EQ_DELETE
-#endif
-
#if defined(CMake_HAVE_CXX_FALLTHROUGH)
#define CM_FALLTHROUGH [[fallthrough]]
#elif defined(CMake_HAVE_CXX_GNU_FALLTHROUGH)
#define CM_FALLTHROUGH [[gnu::fallthrough]]
-elif defined(CMake_HAVE_CXX_ATTRIBUTE_FALLTHROUGH)
+#elif defined(CMake_HAVE_CXX_ATTRIBUTE_FALLTHROUGH)
#define CM_FALLTHROUGH __attribute__((fallthrough))
#else
#define CM_FALLTHROUGH
#endif
-#ifdef CMake_HAVE_CXX_NULLPTR
-#define CM_NULLPTR nullptr
-#else
-#define CM_NULLPTR 0
-#endif
-
-#ifdef CMake_HAVE_CXX_OVERRIDE
-#define CM_OVERRIDE override
-#else
-#define CM_OVERRIDE
-#endif
-
#define CM_DISABLE_COPY(Class) \
- Class(Class const&) CM_EQ_DELETE; \
- Class& operator=(Class const&) CM_EQ_DELETE;
+ Class(Class const&) = delete; \
+ Class& operator=(Class const&) = delete;
#endif
diff --git a/Source/cmConfigureFileCommand.h b/Source/cmConfigureFileCommand.h
index 6cebbd258..cff934b48 100644
--- a/Source/cmConfigureFileCommand.h
+++ b/Source/cmConfigureFileCommand.h
@@ -3,7 +3,7 @@
#ifndef cmConfigureFileCommand_h
#define cmConfigureFileCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -16,14 +16,14 @@ class cmExecutionStatus;
class cmConfigureFileCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmConfigureFileCommand; }
+ cmCommand* Clone() override { return new cmConfigureFileCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
int ConfigureFile();
diff --git a/Source/cmConnection.cxx b/Source/cmConnection.cxx
new file mode 100644
index 000000000..28ba12c4b
--- /dev/null
+++ b/Source/cmConnection.cxx
@@ -0,0 +1,168 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmConnection.h"
+
+#include "cmServer.h"
+#include "cm_uv.h"
+
+#include <cassert>
+#include <cstring>
+
+struct write_req_t
+{
+ uv_write_t req;
+ uv_buf_t buf;
+};
+
+void cmEventBasedConnection::on_alloc_buffer(uv_handle_t* handle,
+ size_t suggested_size,
+ uv_buf_t* buf)
+{
+ (void)(handle);
+ char* rawBuffer = new char[suggested_size];
+ *buf = uv_buf_init(rawBuffer, static_cast<unsigned int>(suggested_size));
+}
+
+void cmEventBasedConnection::on_read(uv_stream_t* stream, ssize_t nread,
+ const uv_buf_t* buf)
+{
+ auto conn = reinterpret_cast<cmEventBasedConnection*>(stream->data);
+ if (conn) {
+ if (nread >= 0) {
+ conn->ReadData(std::string(buf->base, buf->base + nread));
+ } else {
+ conn->OnDisconnect(static_cast<int>(nread));
+ }
+ }
+
+ delete[](buf->base);
+}
+
+void cmEventBasedConnection::on_close(uv_handle_t* /*handle*/)
+{
+}
+
+void cmEventBasedConnection::on_write(uv_write_t* req, int status)
+{
+ (void)(status);
+
+ // Free req and buffer
+ write_req_t* wr = reinterpret_cast<write_req_t*>(req);
+ delete[](wr->buf.base);
+ delete wr;
+}
+
+void cmEventBasedConnection::on_new_connection(uv_stream_t* stream, int status)
+{
+ (void)(status);
+ auto conn = reinterpret_cast<cmEventBasedConnection*>(stream->data);
+
+ if (conn) {
+ conn->Connect(stream);
+ }
+}
+
+bool cmEventBasedConnection::IsOpen() const
+{
+ return this->WriteStream != nullptr;
+}
+
+void cmEventBasedConnection::WriteData(const std::string& _data)
+{
+#ifndef NDEBUG
+ auto curr_thread_id = uv_thread_self();
+ assert(this->Server);
+ assert(uv_thread_equal(&curr_thread_id, &this->Server->ServeThreadId));
+#endif
+
+ auto data = _data;
+ assert(this->WriteStream);
+ if (BufferStrategy) {
+ data = BufferStrategy->BufferOutMessage(data);
+ }
+
+ auto ds = data.size();
+
+ write_req_t* req = new write_req_t;
+ req->req.data = this;
+ req->buf = uv_buf_init(new char[ds], static_cast<unsigned int>(ds));
+ memcpy(req->buf.base, data.c_str(), ds);
+ uv_write(reinterpret_cast<uv_write_t*>(req),
+ static_cast<uv_stream_t*>(this->WriteStream), &req->buf, 1,
+ on_write);
+}
+
+void cmEventBasedConnection::ReadData(const std::string& data)
+{
+ this->RawReadBuffer += data;
+ if (BufferStrategy) {
+ std::string packet = BufferStrategy->BufferMessage(this->RawReadBuffer);
+ while (!packet.empty()) {
+ ProcessRequest(packet);
+ packet = BufferStrategy->BufferMessage(this->RawReadBuffer);
+ }
+ } else {
+ ProcessRequest(this->RawReadBuffer);
+ this->RawReadBuffer.clear();
+ }
+}
+
+cmEventBasedConnection::cmEventBasedConnection(
+ cmConnectionBufferStrategy* bufferStrategy)
+ : BufferStrategy(bufferStrategy)
+{
+}
+
+void cmEventBasedConnection::Connect(uv_stream_t* server)
+{
+ (void)server;
+ Server->OnConnected(nullptr);
+}
+
+void cmEventBasedConnection::OnDisconnect(int onerror)
+{
+ (void)onerror;
+ this->OnConnectionShuttingDown();
+ if (this->Server) {
+ this->Server->OnDisconnect(this);
+ }
+}
+
+cmConnection::~cmConnection()
+{
+}
+
+bool cmConnection::OnConnectionShuttingDown()
+{
+ this->Server = nullptr;
+ return true;
+}
+
+void cmConnection::SetServer(cmServerBase* s)
+{
+ Server = s;
+}
+
+void cmConnection::ProcessRequest(const std::string& request)
+{
+ Server->ProcessRequest(this, request);
+}
+
+bool cmConnection::OnServeStart(std::string* errString)
+{
+ (void)errString;
+ return true;
+}
+
+bool cmEventBasedConnection::OnConnectionShuttingDown()
+{
+ if (this->WriteStream) {
+ this->WriteStream->data = nullptr;
+ }
+ if (this->ReadStream) {
+ this->ReadStream->data = nullptr;
+ }
+ this->ReadStream = nullptr;
+ this->WriteStream = nullptr;
+ return true;
+}
diff --git a/Source/cmConnection.h b/Source/cmConnection.h
new file mode 100644
index 000000000..ddb774457
--- /dev/null
+++ b/Source/cmConnection.h
@@ -0,0 +1,134 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+
+#pragma once
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include "cm_uv.h"
+
+#include <cstddef>
+#include <memory>
+#include <string>
+
+class cmServerBase;
+
+/***
+ * Given a sequence of bytes with any kind of buffering, instances of this
+ * class arrange logical chunks according to whatever the use case is for
+ * the connection.
+ */
+class cmConnectionBufferStrategy
+{
+public:
+ virtual ~cmConnectionBufferStrategy();
+
+ /***
+ * Called whenever with an active raw buffer. If a logical chunk
+ * becomes available, that chunk is returned and that portion is
+ * removed from the rawBuffer
+ *
+ * @param rawBuffer in/out parameter. Receive buffer; the buffer strategy is
+ * free to manipulate this buffer anyway it needs to.
+ *
+ * @return Next chunk from the stream. Returns the empty string if a chunk
+ * isn't ready yet. Users of this interface should repeatedly call this
+ * function until an empty string is returned since its entirely possible
+ * multiple chunks come in a single raw buffer.
+ */
+ virtual std::string BufferMessage(std::string& rawBuffer) = 0;
+
+ /***
+ * Called to properly buffer an outgoing message.
+ *
+ * @param rawBuffer Message to format in the correct way
+ *
+ * @return Formatted message
+ */
+ virtual std::string BufferOutMessage(const std::string& rawBuffer) const
+ {
+ return rawBuffer;
+ };
+ /***
+ * Resets the internal state of the buffering
+ */
+ virtual void clear();
+
+ // TODO: There should be a callback / flag set for errors
+};
+
+class cmConnection
+{
+ CM_DISABLE_COPY(cmConnection)
+
+public:
+ cmConnection() {}
+
+ virtual void WriteData(const std::string& data) = 0;
+
+ virtual ~cmConnection();
+
+ virtual bool OnConnectionShuttingDown();
+
+ virtual bool IsOpen() const = 0;
+
+ virtual void SetServer(cmServerBase* s);
+
+ virtual void ProcessRequest(const std::string& request);
+
+ virtual bool OnServeStart(std::string* pString);
+
+protected:
+ cmServerBase* Server = nullptr;
+};
+
+/***
+ * Abstraction of a connection; ties in event callbacks from libuv and notifies
+ * the server when appropriate
+ */
+class cmEventBasedConnection : public cmConnection
+{
+
+public:
+ /***
+ * @param bufferStrategy If no strategy is given, it will process the raw
+ * chunks as they come in. The connection
+ * owns the pointer given.
+ */
+ cmEventBasedConnection(cmConnectionBufferStrategy* bufferStrategy = nullptr);
+
+ virtual void Connect(uv_stream_t* server);
+
+ virtual void ReadData(const std::string& data);
+
+ bool IsOpen() const override;
+
+ void WriteData(const std::string& data) override;
+ bool OnConnectionShuttingDown() override;
+
+ virtual void OnDisconnect(int errorCode);
+ uv_stream_t* ReadStream = nullptr;
+ uv_stream_t* WriteStream = nullptr;
+
+ static void on_close(uv_handle_t* handle);
+
+ template <typename T>
+ static void on_close_delete(uv_handle_t* handle)
+ {
+ delete reinterpret_cast<T*>(handle);
+ }
+
+protected:
+ std::string RawReadBuffer;
+
+ std::unique_ptr<cmConnectionBufferStrategy> BufferStrategy;
+
+ static void on_read(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf);
+
+ static void on_write(uv_write_t* req, int status);
+
+ static void on_new_connection(uv_stream_t* stream, int status);
+
+ static void on_alloc_buffer(uv_handle_t* handle, size_t suggested_size,
+ uv_buf_t* buf);
+};
diff --git a/Source/cmContinueCommand.h b/Source/cmContinueCommand.h
index 92bc68e85..d383d1d03 100644
--- a/Source/cmContinueCommand.h
+++ b/Source/cmContinueCommand.h
@@ -3,7 +3,7 @@
#ifndef cmContinueCommand_h
#define cmContinueCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmContinueCommand; }
+ cmCommand* Clone() override { return new cmContinueCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmCoreTryCompile.cxx b/Source/cmCoreTryCompile.cxx
index 9a4abf3ca..fd258fe79 100644
--- a/Source/cmCoreTryCompile.cxx
+++ b/Source/cmCoreTryCompile.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCoreTryCompile.h"
-#include "cmConfigure.h"
#include "cmsys/Directory.hxx"
#include <set>
#include <sstream>
@@ -72,7 +71,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
bool isTryRun)
{
this->BinaryDirectory = argv[1];
- this->OutputFile = "";
+ this->OutputFile.clear();
// which signature were we called with ?
this->SrcFileSignature = true;
@@ -102,7 +101,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
}
const char* sourceDirectory = argv[2].c_str();
- const char* projectName = CM_NULLPTR;
+ const char* projectName = nullptr;
std::string targetName;
std::vector<std::string> cmakeFlags(1, "CMAKE_FLAGS"); // fake argv[0]
std::vector<std::string> compileDefs;
@@ -418,16 +417,15 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
// Detect languages to enable.
cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
std::set<std::string> testLangs;
- for (std::vector<std::string>::iterator si = sources.begin();
- si != sources.end(); ++si) {
- std::string ext = cmSystemTools::GetFilenameLastExtension(*si);
+ for (std::string const& si : sources) {
+ std::string ext = cmSystemTools::GetFilenameLastExtension(si);
std::string lang = gg->GetLanguageFromExtension(ext.c_str());
if (!lang.empty()) {
testLangs.insert(lang);
} else {
std::ostringstream err;
err << "Unknown extension \"" << ext << "\" for file\n"
- << " " << *si << "\n"
+ << " " << si << "\n"
<< "try_compile() works only for enabled languages. "
<< "Currently these are:\n ";
std::vector<std::string> langs;
@@ -468,11 +466,10 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
}
std::string projectLangs;
- for (std::set<std::string>::iterator li = testLangs.begin();
- li != testLangs.end(); ++li) {
- projectLangs += " " + *li;
+ for (std::string const& li : testLangs) {
+ projectLangs += " " + li;
std::string rulesOverrideBase = "CMAKE_USER_MAKE_RULES_OVERRIDE";
- std::string rulesOverrideLang = rulesOverrideBase + "_" + *li;
+ std::string rulesOverrideLang = rulesOverrideBase + "_" + li;
if (const char* rulesOverridePath =
this->Makefile->GetDefinition(rulesOverrideLang)) {
fprintf(fout, "set(%s \"%s\")\n", rulesOverrideLang.c_str(),
@@ -485,15 +482,14 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
}
fprintf(fout, "project(CMAKE_TRY_COMPILE%s)\n", projectLangs.c_str());
fprintf(fout, "set(CMAKE_VERBOSE_MAKEFILE 1)\n");
- for (std::set<std::string>::iterator li = testLangs.begin();
- li != testLangs.end(); ++li) {
- std::string langFlags = "CMAKE_" + *li + "_FLAGS";
+ for (std::string const& li : testLangs) {
+ std::string langFlags = "CMAKE_" + li + "_FLAGS";
const char* flags = this->Makefile->GetDefinition(langFlags);
- fprintf(fout, "set(CMAKE_%s_FLAGS %s)\n", li->c_str(),
+ fprintf(fout, "set(CMAKE_%s_FLAGS %s)\n", li.c_str(),
cmOutputConverter::EscapeForCMake(flags ? flags : "").c_str());
fprintf(fout, "set(CMAKE_%s_FLAGS \"${CMAKE_%s_FLAGS}"
" ${COMPILE_DEFINITIONS}\")\n",
- li->c_str(), li->c_str());
+ li.c_str(), li.c_str());
}
switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0066)) {
case cmPolicies::WARN:
@@ -523,9 +519,8 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
static std::string const cfgDefault = "DEBUG";
std::string const cfg =
!tcConfig.empty() ? cmSystemTools::UpperCase(tcConfig) : cfgDefault;
- for (std::set<std::string>::iterator li = testLangs.begin();
- li != testLangs.end(); ++li) {
- std::string const langFlagsCfg = "CMAKE_" + *li + "_FLAGS_" + cfg;
+ for (std::string const& li : testLangs) {
+ std::string const langFlagsCfg = "CMAKE_" + li + "_FLAGS_" + cfg;
const char* flagsCfg = this->Makefile->GetDefinition(langFlagsCfg);
fprintf(fout, "set(%s %s)\n", langFlagsCfg.c_str(),
cmOutputConverter::EscapeForCMake(flagsCfg ? flagsCfg : "")
@@ -639,9 +634,7 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
cmakeFlags.push_back(flag);
}
- for (std::set<std::string>::iterator vi = vars.begin(); vi != vars.end();
- ++vi) {
- std::string const& var = *vi;
+ for (std::string const& var : vars) {
if (const char* val = this->Makefile->GetDefinition(var)) {
std::string flag = "-D" + var + "=" + val;
cmakeFlags.push_back(flag);
@@ -670,13 +663,12 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
/* Create the actual static library. */
fprintf(fout, "add_library(%s STATIC", targetName.c_str());
}
- for (std::vector<std::string>::iterator si = sources.begin();
- si != sources.end(); ++si) {
- fprintf(fout, " \"%s\"", si->c_str());
+ for (std::string const& si : sources) {
+ fprintf(fout, " \"%s\"", si.c_str());
// Add dependencies on any non-temporary sources.
- if (si->find("CMakeTmp") == std::string::npos) {
- this->Makefile->AddCMakeDependFile(*si);
+ if (si.find("CMakeTmp") == std::string::npos) {
+ this->Makefile->AddCMakeDependFile(si);
}
}
fprintf(fout, ")\n");
@@ -763,9 +755,8 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
"is not honoring language standard variables in the test project:\n"
;
/* clang-format on */
- for (std::vector<std::string>::iterator vi = this->WarnCMP0067.begin();
- vi != this->WarnCMP0067.end(); ++vi) {
- w << " " << *vi << "\n";
+ for (std::string const& vi : this->WarnCMP0067) {
+ w << " " << vi << "\n";
}
this->Makefile->IssueMessage(cmake::AUTHOR_WARNING, w.str());
}
@@ -928,8 +919,8 @@ void cmCoreTryCompile::CleanupFiles(const char* binDir)
void cmCoreTryCompile::FindOutputFile(const std::string& targetName,
cmStateEnums::TargetType targetType)
{
- this->FindErrorMessage = "";
- this->OutputFile = "";
+ this->FindErrorMessage.clear();
+ this->OutputFile.clear();
std::string tmpOutputFile = "/";
if (targetType == cmStateEnums::EXECUTABLE) {
tmpOutputFile += targetName;
@@ -964,10 +955,9 @@ void cmCoreTryCompile::FindOutputFile(const std::string& targetName,
#endif
searchDirs.push_back("/Development");
- for (std::vector<std::string>::const_iterator it = searchDirs.begin();
- it != searchDirs.end(); ++it) {
+ for (std::string const& sdir : searchDirs) {
std::string command = this->BinaryDirectory;
- command += *it;
+ command += sdir;
command += tmpOutputFile;
if (cmSystemTools::FileExists(command.c_str())) {
this->OutputFile = cmSystemTools::CollapseFullPath(command);
diff --git a/Source/cmCreateTestSourceList.h b/Source/cmCreateTestSourceList.h
index f1f1e4b8a..005b32c30 100644
--- a/Source/cmCreateTestSourceList.h
+++ b/Source/cmCreateTestSourceList.h
@@ -3,7 +3,7 @@
#ifndef cmCreateTestSourceList_h
#define cmCreateTestSourceList_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmCreateTestSourceList; }
+ cmCommand* Clone() override { return new cmCreateTestSourceList; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmCryptoHash.cxx b/Source/cmCryptoHash.cxx
index 7995b2cb3..d914eb142 100644
--- a/Source/cmCryptoHash.cxx
+++ b/Source/cmCryptoHash.cxx
@@ -2,11 +2,14 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmCryptoHash.h"
+#include "cmAlgorithms.h"
#include "cm_kwiml.h"
#include "cm_rhash.h"
#include "cmsys/FStream.hxx"
#include <string.h>
+#include <memory> // IWYU pragma: keep
+
static unsigned int const cmCryptoHashAlgoToId[] = {
/* clang-format needs this comment to break after the opening brace */
RHASH_MD5, //
@@ -43,39 +46,39 @@ cmCryptoHash::~cmCryptoHash()
rhash_free(this->CTX);
}
-CM_AUTO_PTR<cmCryptoHash> cmCryptoHash::New(const char* algo)
+std::unique_ptr<cmCryptoHash> cmCryptoHash::New(const char* algo)
{
if (strcmp(algo, "MD5") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoMD5));
+ return cm::make_unique<cmCryptoHash>(AlgoMD5);
}
if (strcmp(algo, "SHA1") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA1));
+ return cm::make_unique<cmCryptoHash>(AlgoSHA1);
}
if (strcmp(algo, "SHA224") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA224));
+ return cm::make_unique<cmCryptoHash>(AlgoSHA224);
}
if (strcmp(algo, "SHA256") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA256));
+ return cm::make_unique<cmCryptoHash>(AlgoSHA256);
}
if (strcmp(algo, "SHA384") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA384));
+ return cm::make_unique<cmCryptoHash>(AlgoSHA384);
}
if (strcmp(algo, "SHA512") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA512));
+ return cm::make_unique<cmCryptoHash>(AlgoSHA512);
}
if (strcmp(algo, "SHA3_224") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_224));
+ return cm::make_unique<cmCryptoHash>(AlgoSHA3_224);
}
if (strcmp(algo, "SHA3_256") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_256));
+ return cm::make_unique<cmCryptoHash>(AlgoSHA3_256);
}
if (strcmp(algo, "SHA3_384") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_384));
+ return cm::make_unique<cmCryptoHash>(AlgoSHA3_384);
}
if (strcmp(algo, "SHA3_512") == 0) {
- return CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(AlgoSHA3_512));
+ return cm::make_unique<cmCryptoHash>(AlgoSHA3_512);
}
- return CM_AUTO_PTR<cmCryptoHash>(CM_NULLPTR);
+ return std::unique_ptr<cmCryptoHash>(nullptr);
}
bool cmCryptoHash::IntFromHexDigit(char input, char& output)
@@ -103,10 +106,9 @@ std::string cmCryptoHash::ByteHashToString(
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
std::string res;
- for (std::vector<unsigned char>::const_iterator vit = hash.begin();
- vit != hash.end(); ++vit) {
- res.push_back(hex[(*vit) >> 4]);
- res.push_back(hex[(*vit) & 0xF]);
+ for (unsigned char v : hash) {
+ res.push_back(hex[v >> 4]);
+ res.push_back(hex[v & 0xF]);
}
return res;
}
diff --git a/Source/cmCryptoHash.h b/Source/cmCryptoHash.h
index c380d85ff..1f2a1b52c 100644
--- a/Source/cmCryptoHash.h
+++ b/Source/cmCryptoHash.h
@@ -3,14 +3,13 @@
#ifndef cmCryptoHash_h
#define cmCryptoHash_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
+#include <memory> // IWYU pragma: keep
#include <stddef.h>
#include <string>
#include <vector>
-#include "cm_auto_ptr.hxx"
-
/**
* @brief Abstract base class for cryptographic hash generators
*/
@@ -42,7 +41,7 @@ public:
/// SHA3_224, SHA3_256, SHA3_384, SHA3_512
/// @return A valid auto pointer if algo is supported or
/// an invalid/NULL pointer otherwise
- static CM_AUTO_PTR<cmCryptoHash> New(const char* algo);
+ static std::unique_ptr<cmCryptoHash> New(const char* algo);
/// @brief Converts a hex character to its binary value (4 bits)
/// @arg input Hex character [0-9a-fA-F].
diff --git a/Source/cmCurl.h b/Source/cmCurl.h
index a2fa4b1c0..0688bb2d7 100644
--- a/Source/cmCurl.h
+++ b/Source/cmCurl.h
@@ -3,11 +3,11 @@
#ifndef cmCurl_h
#define cmCurl_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cm_curl.h"
#include <string>
-std::string cmCurlSetCAInfo(::CURL* curl, const char* cafile = CM_NULLPTR);
+std::string cmCurlSetCAInfo(::CURL* curl, const char* cafile = nullptr);
#endif
diff --git a/Source/cmCustomCommand.cxx b/Source/cmCustomCommand.cxx
index 5e377b574..cfd260c23 100644
--- a/Source/cmCustomCommand.cxx
+++ b/Source/cmCustomCommand.cxx
@@ -4,8 +4,6 @@
#include "cmMakefile.h"
-#include "cmConfigure.h"
-
cmCustomCommand::cmCustomCommand()
: Backtrace()
{
@@ -30,7 +28,7 @@ cmCustomCommand::cmCustomCommand(cmMakefile const* mf,
, Backtrace()
, Comment(comment ? comment : "")
, WorkingDirectory(workingDirectory ? workingDirectory : "")
- , HaveComment(comment != CM_NULLPTR)
+ , HaveComment(comment != nullptr)
, EscapeAllowMakeVars(false)
, EscapeOldStyle(true)
, CommandExpandLists(false)
@@ -62,7 +60,7 @@ const cmCustomCommandLines& cmCustomCommand::GetCommandLines() const
const char* cmCustomCommand::GetComment() const
{
- const char* no_comment = CM_NULLPTR;
+ const char* no_comment = nullptr;
return this->HaveComment ? this->Comment.c_str() : no_comment;
}
diff --git a/Source/cmCustomCommandGenerator.cxx b/Source/cmCustomCommandGenerator.cxx
index 67213ecaa..3d816d562 100644
--- a/Source/cmCustomCommandGenerator.cxx
+++ b/Source/cmCustomCommandGenerator.cxx
@@ -11,9 +11,9 @@
#include "cmOutputConverter.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
-#include "cmConfigure.h"
+#include <memory> // IWYU pragma: keep
+#include <stddef.h>
cmCustomCommandGenerator::cmCustomCommandGenerator(cmCustomCommand const& cc,
const std::string& config,
@@ -24,15 +24,13 @@ cmCustomCommandGenerator::cmCustomCommandGenerator(cmCustomCommand const& cc,
, OldStyle(cc.GetEscapeOldStyle())
, MakeVars(cc.GetEscapeAllowMakeVars())
, GE(new cmGeneratorExpression(cc.GetBacktrace()))
- , DependsDone(false)
{
const cmCustomCommandLines& cmdlines = this->CC.GetCommandLines();
- for (cmCustomCommandLines::const_iterator cmdline = cmdlines.begin();
- cmdline != cmdlines.end(); ++cmdline) {
+ for (cmCustomCommandLine const& cmdline : cmdlines) {
cmCustomCommandLine argv;
- for (cmCustomCommandLine::const_iterator clarg = cmdline->begin();
- clarg != cmdline->end(); ++clarg) {
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = this->GE->Parse(*clarg);
+ for (std::string const& clarg : cmdline) {
+ std::unique_ptr<cmCompiledGeneratorExpression> cge =
+ this->GE->Parse(clarg);
std::string parsed_arg = cge->Evaluate(this->LG, this->Config);
if (this->CC.GetCommandExpandLists()) {
std::vector<std::string> ExpandedArg;
@@ -44,6 +42,20 @@ cmCustomCommandGenerator::cmCustomCommandGenerator(cmCustomCommand const& cc,
}
this->CommandLines.push_back(argv);
}
+
+ std::vector<std::string> depends = this->CC.GetDepends();
+ for (std::string const& d : depends) {
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = this->GE->Parse(d);
+ std::vector<std::string> result;
+ cmSystemTools::ExpandListArgument(cge->Evaluate(this->LG, this->Config),
+ result);
+ for (std::string& it : result) {
+ if (cmSystemTools::FileIsFullPath(it.c_str())) {
+ it = cmSystemTools::CollapseFullPath(it);
+ }
+ }
+ this->Depends.insert(this->Depends.end(), result.begin(), result.end());
+ }
}
cmCustomCommandGenerator::~cmCustomCommandGenerator()
@@ -60,7 +72,7 @@ const char* cmCustomCommandGenerator::GetCrossCompilingEmulator(
unsigned int c) const
{
if (!this->LG->GetMakefile()->IsOn("CMAKE_CROSSCOMPILING")) {
- return CM_NULLPTR;
+ return nullptr;
}
std::string const& argv0 = this->CommandLines[c][0];
cmGeneratorTarget* target = this->LG->FindGeneratorTargetToUse(argv0);
@@ -68,7 +80,7 @@ const char* cmCustomCommandGenerator::GetCrossCompilingEmulator(
!target->IsImported()) {
return target->GetProperty("CROSSCOMPILING_EMULATOR");
}
- return CM_NULLPTR;
+ return nullptr;
}
const char* cmCustomCommandGenerator::GetArgv0Location(unsigned int c) const
@@ -81,7 +93,19 @@ const char* cmCustomCommandGenerator::GetArgv0Location(unsigned int c) const
!this->LG->GetMakefile()->IsOn("CMAKE_CROSSCOMPILING"))) {
return target->GetLocation(this->Config);
}
- return CM_NULLPTR;
+ return nullptr;
+}
+
+bool cmCustomCommandGenerator::HasOnlyEmptyCommandLines() const
+{
+ for (size_t i = 0; i < this->CommandLines.size(); ++i) {
+ for (size_t j = 0; j < this->CommandLines[i].size(); ++j) {
+ if (!this->CommandLines[i][j].empty()) {
+ return false;
+ }
+ }
+ }
+ return true;
}
std::string cmCustomCommandGenerator::GetCommand(unsigned int c) const
@@ -125,14 +149,13 @@ void cmCustomCommandGenerator::AppendArguments(unsigned int c,
std::string& cmd) const
{
unsigned int offset = 1;
- if (this->GetCrossCompilingEmulator(c) != CM_NULLPTR) {
+ if (this->GetCrossCompilingEmulator(c) != nullptr) {
offset = 0;
}
cmCustomCommandLine const& commandLine = this->CommandLines[c];
for (unsigned int j = offset; j < commandLine.size(); ++j) {
std::string arg;
- if (const char* location =
- j == 0 ? this->GetArgv0Location(c) : CM_NULLPTR) {
+ if (const char* location = j == 0 ? this->GetArgv0Location(c) : nullptr) {
// GetCommand returned the emulator instead of the argv0 location,
// so transform the latter now.
arg = location;
@@ -171,23 +194,5 @@ std::vector<std::string> const& cmCustomCommandGenerator::GetByproducts() const
std::vector<std::string> const& cmCustomCommandGenerator::GetDepends() const
{
- if (!this->DependsDone) {
- this->DependsDone = true;
- std::vector<std::string> depends = this->CC.GetDepends();
- for (std::vector<std::string>::const_iterator i = depends.begin();
- i != depends.end(); ++i) {
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = this->GE->Parse(*i);
- std::vector<std::string> result;
- cmSystemTools::ExpandListArgument(cge->Evaluate(this->LG, this->Config),
- result);
- for (std::vector<std::string>::iterator it = result.begin();
- it != result.end(); ++it) {
- if (cmSystemTools::FileIsFullPath(it->c_str())) {
- *it = cmSystemTools::CollapseFullPath(*it);
- }
- }
- this->Depends.insert(this->Depends.end(), result.begin(), result.end());
- }
- }
return this->Depends;
}
diff --git a/Source/cmCustomCommandGenerator.h b/Source/cmCustomCommandGenerator.h
index 0a2adb524..34fd653a5 100644
--- a/Source/cmCustomCommandGenerator.h
+++ b/Source/cmCustomCommandGenerator.h
@@ -21,9 +21,8 @@ class cmCustomCommandGenerator
bool OldStyle;
bool MakeVars;
cmGeneratorExpression* GE;
- mutable bool DependsDone;
- mutable std::vector<std::string> Depends;
cmCustomCommandLines CommandLines;
+ std::vector<std::string> Depends;
const char* GetCrossCompilingEmulator(unsigned int c) const;
const char* GetArgv0Location(unsigned int c) const;
@@ -41,6 +40,7 @@ public:
std::vector<std::string> const& GetOutputs() const;
std::vector<std::string> const& GetByproducts() const;
std::vector<std::string> const& GetDepends() const;
+ bool HasOnlyEmptyCommandLines() const;
};
#endif
diff --git a/Source/cmDefinePropertyCommand.h b/Source/cmDefinePropertyCommand.h
index bc120c564..a9c185618 100644
--- a/Source/cmDefinePropertyCommand.h
+++ b/Source/cmDefinePropertyCommand.h
@@ -3,7 +3,7 @@
#ifndef cmDefinesPropertyCommand_h
#define cmDefinesPropertyCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,14 +15,14 @@ class cmExecutionStatus;
class cmDefinePropertyCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmDefinePropertyCommand; }
+ cmCommand* Clone() override { return new cmDefinePropertyCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
std::string PropertyName;
diff --git a/Source/cmDefinitions.cxx b/Source/cmDefinitions.cxx
index 7aa7641e1..e766854a6 100644
--- a/Source/cmDefinitions.cxx
+++ b/Source/cmDefinitions.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmDefinitions.h"
-#include "cmConfigure.h"
#include <assert.h>
#include <set>
#include <utility>
@@ -35,7 +34,7 @@ const char* cmDefinitions::Get(const std::string& key, StackIter begin,
StackIter end)
{
Def const& def = cmDefinitions::GetInternal(key, begin, end, false);
- return def.Exists ? def.c_str() : CM_NULLPTR;
+ return def.Exists ? def.c_str() : nullptr;
}
void cmDefinitions::Raise(const std::string& key, StackIter begin,
@@ -67,10 +66,9 @@ std::vector<std::string> cmDefinitions::UnusedKeys() const
std::vector<std::string> keys;
keys.reserve(this->Map.size());
// Consider local definitions.
- for (MapType::const_iterator mi = this->Map.begin(); mi != this->Map.end();
- ++mi) {
- if (!mi->second.Used) {
- keys.push_back(mi->first);
+ for (auto const& mi : this->Map) {
+ if (!mi.second.Used) {
+ keys.push_back(mi.first);
}
}
return keys;
@@ -82,15 +80,14 @@ cmDefinitions cmDefinitions::MakeClosure(StackIter begin, StackIter end)
std::set<std::string> undefined;
for (StackIter it = begin; it != end; ++it) {
// Consider local definitions.
- for (MapType::const_iterator mi = it->Map.begin(); mi != it->Map.end();
- ++mi) {
+ for (auto const& mi : it->Map) {
// Use this key if it is not already set or unset.
- if (closure.Map.find(mi->first) == closure.Map.end() &&
- undefined.find(mi->first) == undefined.end()) {
- if (mi->second.Exists) {
- closure.Map.insert(*mi);
+ if (closure.Map.find(mi.first) == closure.Map.end() &&
+ undefined.find(mi.first) == undefined.end()) {
+ if (mi.second.Exists) {
+ closure.Map.insert(mi);
} else {
- undefined.insert(mi->first);
+ undefined.insert(mi.first);
}
}
}
@@ -106,11 +103,10 @@ std::vector<std::string> cmDefinitions::ClosureKeys(StackIter begin,
for (StackIter it = begin; it != end; ++it) {
defined.reserve(defined.size() + it->Map.size());
- for (MapType::const_iterator mi = it->Map.begin(); mi != it->Map.end();
- ++mi) {
+ for (auto const& mi : it->Map) {
// Use this key if it is not already set or unset.
- if (bound.insert(mi->first).second && mi->second.Exists) {
- defined.push_back(mi->first);
+ if (bound.insert(mi.first).second && mi.second.Exists) {
+ defined.push_back(mi.first);
}
}
}
diff --git a/Source/cmDefinitions.h b/Source/cmDefinitions.h
index ddb89188c..528b15748 100644
--- a/Source/cmDefinitions.h
+++ b/Source/cmDefinitions.h
@@ -6,10 +6,10 @@
#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
+#include <unordered_map>
#include <vector>
#include "cmLinkedTree.h"
-#include "cm_unordered_map.hxx"
/** \class cmDefinitions
* \brief Store a scope of variable definitions for CMake language.
@@ -70,7 +70,7 @@ private:
};
static Def NoDef;
- typedef CM_UNORDERED_MAP<std::string, Def> MapType;
+ typedef std::unordered_map<std::string, Def> MapType;
MapType Map;
static Def const& GetInternal(const std::string& key, StackIter begin,
diff --git a/Source/cmDepends.cxx b/Source/cmDepends.cxx
index c898d12ba..cdab671a7 100644
--- a/Source/cmDepends.cxx
+++ b/Source/cmDepends.cxx
@@ -18,7 +18,7 @@ cmDepends::cmDepends(cmLocalGenerator* lg, const char* targetDir)
: CompileDirectory()
, LocalGenerator(lg)
, Verbose(false)
- , FileComparison(CM_NULLPTR)
+ , FileComparison(nullptr)
, TargetDirectory(targetDir)
, MaxPath(16384)
, Dependee(new char[MaxPath])
@@ -42,7 +42,7 @@ bool cmDepends::Write(std::ostream& makeDepends, std::ostream& internalDepends)
std::vector<std::string> pairs;
cmSystemTools::ExpandListArgument(srcStr, pairs);
- std::map<std::string, std::set<std::string> > dependencies;
+ std::map<std::string, std::set<std::string>> dependencies;
for (std::vector<std::string>::iterator si = pairs.begin();
si != pairs.end();) {
// Get the source and object file.
@@ -53,12 +53,10 @@ bool cmDepends::Write(std::ostream& makeDepends, std::ostream& internalDepends)
std::string const& obj = *si++;
dependencies[obj].insert(src);
}
- for (std::map<std::string, std::set<std::string> >::const_iterator it =
- dependencies.begin();
- it != dependencies.end(); ++it) {
+ for (auto const& d : dependencies) {
// Write the dependencies for this pair.
- if (!this->WriteDependencies(it->second, it->first, makeDepends,
+ if (!this->WriteDependencies(d.second, d.first, makeDepends,
internalDepends)) {
return false;
}
@@ -125,7 +123,7 @@ bool cmDepends::CheckDependencies(
// regenerated.
bool okay = true;
bool dependerExists = false;
- DependencyVector* currentDependencies = CM_NULLPTR;
+ DependencyVector* currentDependencies = nullptr;
while (internalDepends.getline(this->Dependee, this->MaxPath)) {
if (this->Dependee[0] == 0 || this->Dependee[0] == '#' ||
@@ -167,7 +165,7 @@ bool cmDepends::CheckDependencies(
bool regenerate = false;
const char* dependee = this->Dependee + 1;
const char* depender = this->Depender;
- if (currentDependencies != CM_NULLPTR) {
+ if (currentDependencies != nullptr) {
currentDependencies->push_back(dependee);
}
@@ -227,9 +225,9 @@ bool cmDepends::CheckDependencies(
// Remove the information of this depender from the map, it needs
// to be rescanned
- if (currentDependencies != CM_NULLPTR) {
+ if (currentDependencies != nullptr) {
validDeps.erase(this->Depender);
- currentDependencies = CM_NULLPTR;
+ currentDependencies = nullptr;
}
// Remove the depender to be sure it is rebuilt.
@@ -246,7 +244,7 @@ bool cmDepends::CheckDependencies(
void cmDepends::SetIncludePathFromLanguage(const std::string& lang)
{
// Look for the new per "TARGET_" variant first:
- const char* includePath = CM_NULLPTR;
+ const char* includePath = nullptr;
std::string includePathVar = "CMAKE_";
includePathVar += lang;
includePathVar += "_TARGET_INCLUDE_PATH";
diff --git a/Source/cmDepends.h b/Source/cmDepends.h
index b33feb902..a4fee3c8a 100644
--- a/Source/cmDepends.h
+++ b/Source/cmDepends.h
@@ -3,7 +3,7 @@
#ifndef cmDepends_h
#define cmDepends_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <map>
@@ -29,7 +29,7 @@ class cmDepends
public:
/** Instances need to know the build directory name and the relative
path from the build directory to the target file. */
- cmDepends(cmLocalGenerator* lg = CM_NULLPTR, const char* targetDir = "");
+ cmDepends(cmLocalGenerator* lg = nullptr, const char* targetDir = "");
/** at what level will the compile be done from */
void SetCompileDirectory(const char* dir) { this->CompileDirectory = dir; }
diff --git a/Source/cmDependsC.cxx b/Source/cmDependsC.cxx
index 2c464cc9c..1ab3fa244 100644
--- a/Source/cmDependsC.cxx
+++ b/Source/cmDependsC.cxx
@@ -20,7 +20,7 @@
#define INCLUDE_REGEX_TRANSFORM_MARKER "#IncludeRegexTransform: "
cmDependsC::cmDependsC()
- : ValidDeps(CM_NULLPTR)
+ : ValidDeps(nullptr)
{
}
@@ -96,7 +96,7 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources,
std::set<std::string> dependencies;
bool haveDeps = false;
- if (this->ValidDeps != CM_NULLPTR) {
+ if (this->ValidDeps != nullptr) {
std::map<std::string, DependencyVector>::const_iterator tmpIt =
this->ValidDeps->find(obj);
if (tmpIt != this->ValidDeps->end()) {
@@ -107,15 +107,14 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources,
if (!haveDeps) {
// Walk the dependency graph starting with the source file.
- int srcFiles = (int)sources.size();
+ int srcFiles = static_cast<int>(sources.size());
this->Encountered.clear();
- for (std::set<std::string>::const_iterator srcIt = sources.begin();
- srcIt != sources.end(); ++srcIt) {
+ for (std::string const& src : sources) {
UnscannedEntry root;
- root.FileName = *srcIt;
+ root.FileName = src;
this->Unscanned.push(root);
- this->Encountered.insert(*srcIt);
+ this->Encountered.insert(src);
}
std::set<std::string> scanned;
@@ -150,14 +149,12 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources,
if (headerLocationIt != this->HeaderLocationCache.end()) {
fullName = headerLocationIt->second;
} else {
- for (std::vector<std::string>::const_iterator i =
- this->IncludePath.begin();
- i != this->IncludePath.end(); ++i) {
+ for (std::string const& i : this->IncludePath) {
// Construct the name of the file as if it were in the current
// include directory. Avoid using a leading "./".
tempPathStr =
- cmSystemTools::CollapseCombinedPath(*i, current.FileName);
+ cmSystemTools::CollapseCombinedPath(i, current.FileName);
// Look for the file in this location.
if (cmSystemTools::FileExists(tempPathStr.c_str(), true)) {
@@ -189,13 +186,11 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources,
if (fileIt != this->FileCache.end()) {
fileIt->second->Used = true;
dependencies.insert(fullName);
- for (std::vector<UnscannedEntry>::const_iterator incIt =
- fileIt->second->UnscannedEntries.begin();
- incIt != fileIt->second->UnscannedEntries.end(); ++incIt) {
- if (this->Encountered.find(incIt->FileName) ==
+ for (UnscannedEntry const& inc : fileIt->second->UnscannedEntries) {
+ if (this->Encountered.find(inc.FileName) ==
this->Encountered.end()) {
- this->Encountered.insert(incIt->FileName);
- this->Unscanned.push(*incIt);
+ this->Encountered.insert(inc.FileName);
+ this->Unscanned.push(inc);
}
}
} else {
@@ -234,14 +229,13 @@ bool cmDependsC::WriteDependencies(const std::set<std::string>& sources,
std::string obj_m = cmSystemTools::ConvertToOutputPath(obj_i.c_str());
internalDepends << obj_i << std::endl;
- for (std::set<std::string>::const_iterator i = dependencies.begin();
- i != dependencies.end(); ++i) {
+ for (std::string const& dep : dependencies) {
makeDepends
<< obj_m << ": "
<< cmSystemTools::ConvertToOutputPath(
- this->LocalGenerator->ConvertToRelativePath(binDir, *i).c_str())
+ this->LocalGenerator->ConvertToRelativePath(binDir, dep).c_str())
<< std::endl;
- internalDepends << " " << *i << std::endl;
+ internalDepends << " " << dep << std::endl;
}
makeDepends << std::endl;
@@ -259,12 +253,12 @@ void cmDependsC::ReadCacheFile()
}
std::string line;
- cmIncludeLines* cacheEntry = CM_NULLPTR;
+ cmIncludeLines* cacheEntry = nullptr;
bool haveFileName = false;
while (cmSystemTools::GetLineFromStream(fin, line)) {
if (line.empty()) {
- cacheEntry = CM_NULLPTR;
+ cacheEntry = nullptr;
haveFileName = false;
continue;
}
@@ -302,7 +296,7 @@ void cmDependsC::ReadCacheFile()
}
}
}
- } else if (cacheEntry != CM_NULLPTR) {
+ } else if (cacheEntry != nullptr) {
UnscannedEntry entry;
entry.FileName = line;
if (cmSystemTools::GetLineFromStream(fin, line)) {
@@ -330,20 +324,16 @@ void cmDependsC::WriteCacheFile() const
cacheOut << this->IncludeRegexComplainString << "\n\n";
cacheOut << this->IncludeRegexTransformString << "\n\n";
- for (std::map<std::string, cmIncludeLines*>::const_iterator fileIt =
- this->FileCache.begin();
- fileIt != this->FileCache.end(); ++fileIt) {
- if (fileIt->second->Used) {
- cacheOut << fileIt->first << std::endl;
-
- for (std::vector<UnscannedEntry>::const_iterator incIt =
- fileIt->second->UnscannedEntries.begin();
- incIt != fileIt->second->UnscannedEntries.end(); ++incIt) {
- cacheOut << incIt->FileName << std::endl;
- if (incIt->QuotedLocation.empty()) {
+ for (auto const& fileIt : this->FileCache) {
+ if (fileIt.second->Used) {
+ cacheOut << fileIt.first << std::endl;
+
+ for (UnscannedEntry const& inc : fileIt.second->UnscannedEntries) {
+ cacheOut << inc.FileName << std::endl;
+ if (inc.QuotedLocation.empty()) {
cacheOut << "-" << std::endl;
} else {
- cacheOut << incIt->QuotedLocation << std::endl;
+ cacheOut << inc.QuotedLocation << std::endl;
}
}
cacheOut << std::endl;
@@ -411,9 +401,8 @@ void cmDependsC::SetupTransforms()
if (const char* xform = mf->GetDefinition("CMAKE_INCLUDE_TRANSFORMS")) {
cmSystemTools::ExpandListArgument(xform, transformRules, true);
}
- for (std::vector<std::string>::const_iterator tri = transformRules.begin();
- tri != transformRules.end(); ++tri) {
- this->ParseTransform(*tri);
+ for (std::string const& tr : transformRules) {
+ this->ParseTransform(tr);
}
this->IncludeRegexTransformString = INCLUDE_REGEX_TRANSFORM_MARKER;
@@ -422,10 +411,9 @@ void cmDependsC::SetupTransforms()
// transformed.
std::string xform = "^([ \t]*[#%][ \t]*(include|import)[ \t]*)(";
const char* sep = "";
- for (TransformRulesType::const_iterator tri = this->TransformRules.begin();
- tri != this->TransformRules.end(); ++tri) {
+ for (auto const& tr : this->TransformRules) {
xform += sep;
- xform += tri->first;
+ xform += tr.first;
sep = "|";
}
xform += ")[ \t]*\\(([^),]*)\\)";
@@ -434,12 +422,11 @@ void cmDependsC::SetupTransforms()
// Build a string that encodes all transformation rules and will
// change when rules are changed.
this->IncludeRegexTransformString += xform;
- for (TransformRulesType::const_iterator tri = this->TransformRules.begin();
- tri != this->TransformRules.end(); ++tri) {
+ for (auto const& tr : this->TransformRules) {
this->IncludeRegexTransformString += " ";
- this->IncludeRegexTransformString += tri->first;
+ this->IncludeRegexTransformString += tr.first;
this->IncludeRegexTransformString += "(%)=";
- this->IncludeRegexTransformString += tri->second;
+ this->IncludeRegexTransformString += tr.second;
}
}
}
diff --git a/Source/cmDependsC.h b/Source/cmDependsC.h
index 250d40f8a..2f76f6275 100644
--- a/Source/cmDependsC.h
+++ b/Source/cmDependsC.h
@@ -3,7 +3,7 @@
#ifndef cmDependsC_h
#define cmDependsC_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmDepends.h"
@@ -33,13 +33,13 @@ public:
const std::map<std::string, DependencyVector>* validDeps);
/** Virtual destructor to cleanup subclasses properly. */
- ~cmDependsC() CM_OVERRIDE;
+ ~cmDependsC() override;
protected:
// Implement writing/checking methods required by superclass.
bool WriteDependencies(const std::set<std::string>& sources,
const std::string& obj, std::ostream& makeDepends,
- std::ostream& internalDepends) CM_OVERRIDE;
+ std::ostream& internalDepends) override;
// Method to scan a single file.
void Scan(std::istream& is, const char* directory,
diff --git a/Source/cmDependsFortran.cxx b/Source/cmDependsFortran.cxx
index 8b05fab49..fdbc08627 100644
--- a/Source/cmDependsFortran.cxx
+++ b/Source/cmDependsFortran.cxx
@@ -52,7 +52,7 @@ public:
};
cmDependsFortran::cmDependsFortran()
- : Internal(CM_NULLPTR)
+ : Internal(nullptr)
{
}
@@ -73,12 +73,10 @@ cmDependsFortran::cmDependsFortran(cmLocalGenerator* lg)
// translate i.e. FOO=BAR to FOO and add it to the list of defined
// preprocessor symbols
- for (std::vector<std::string>::const_iterator it = definitions.begin();
- it != definitions.end(); ++it) {
- std::string def = *it;
+ for (std::string def : definitions) {
std::string::size_type assignment = def.find('=');
if (assignment != std::string::npos) {
- def = it->substr(0, assignment);
+ def = def.substr(0, assignment);
}
this->PPDefinitions.insert(def);
}
@@ -105,9 +103,7 @@ bool cmDependsFortran::WriteDependencies(const std::set<std::string>& sources,
}
bool okay = true;
- for (std::set<std::string>::const_iterator it = sources.begin();
- it != sources.end(); ++it) {
- const std::string& src = *it;
+ for (std::string const& src : sources) {
// Get the information object for this source.
cmFortranSourceInfo& info =
this->Internal->CreateObjectInfo(obj.c_str(), src.c_str());
@@ -154,9 +150,8 @@ bool cmDependsFortran::Finalize(std::ostream& makeDepends,
// Actually write dependencies to the streams.
typedef cmDependsFortranInternals::ObjectInfoMap ObjectInfoMap;
ObjectInfoMap const& objInfo = this->Internal->ObjectInfo;
- for (ObjectInfoMap::const_iterator i = objInfo.begin(); i != objInfo.end();
- ++i) {
- if (!this->WriteDependenciesReal(i->first.c_str(), i->second, mod_dir,
+ for (auto const& i : objInfo) {
+ if (!this->WriteDependenciesReal(i.first.c_str(), i.second, mod_dir,
stamp_dir, makeDepends,
internalDepends)) {
return false;
@@ -170,9 +165,8 @@ bool cmDependsFortran::Finalize(std::ostream& makeDepends,
fiStream << "# The fortran modules provided by this target.\n";
fiStream << "provides\n";
std::set<std::string> const& provides = this->Internal->TargetProvides;
- for (std::set<std::string>::const_iterator i = provides.begin();
- i != provides.end(); ++i) {
- fiStream << " " << *i << "\n";
+ for (std::string const& i : provides) {
+ fiStream << " " << i << "\n";
}
// Create a script to clean the modules.
@@ -184,19 +178,18 @@ bool cmDependsFortran::Finalize(std::ostream& makeDepends,
fcStream << "FILE(REMOVE";
std::string currentBinDir =
this->LocalGenerator->GetCurrentBinaryDirectory();
- for (std::set<std::string>::const_iterator i = provides.begin();
- i != provides.end(); ++i) {
+ for (std::string const& i : provides) {
std::string mod_upper = mod_dir;
mod_upper += "/";
- mod_upper += cmSystemTools::UpperCase(*i);
+ mod_upper += cmSystemTools::UpperCase(i);
mod_upper += ".mod";
std::string mod_lower = mod_dir;
mod_lower += "/";
- mod_lower += *i;
+ mod_lower += i;
mod_lower += ".mod";
std::string stamp = stamp_dir;
stamp += "/";
- stamp += *i;
+ stamp += i;
stamp += ".mod.stamp";
fcStream << "\n";
fcStream << " \""
@@ -219,16 +212,14 @@ void cmDependsFortran::LocateModules()
// Collect the set of modules provided and required by all sources.
typedef cmDependsFortranInternals::ObjectInfoMap ObjectInfoMap;
ObjectInfoMap const& objInfo = this->Internal->ObjectInfo;
- for (ObjectInfoMap::const_iterator infoI = objInfo.begin();
- infoI != objInfo.end(); ++infoI) {
- cmFortranSourceInfo const& info = infoI->second;
+ for (auto const& infoI : objInfo) {
+ cmFortranSourceInfo const& info = infoI.second;
// Include this module in the set provided by this target.
this->Internal->TargetProvides.insert(info.Provides.begin(),
info.Provides.end());
- for (std::set<std::string>::const_iterator i = info.Requires.begin();
- i != info.Requires.end(); ++i) {
- this->Internal->TargetRequires[*i] = "";
+ for (std::string const& r : info.Requires) {
+ this->Internal->TargetRequires[r].clear();
}
}
@@ -247,9 +238,8 @@ void cmDependsFortran::LocateModules()
mf->GetDefinition("CMAKE_TARGET_LINKED_INFO_FILES")) {
cmSystemTools::ExpandListArgument(infoFilesValue, infoFiles);
}
- for (std::vector<std::string>::const_iterator i = infoFiles.begin();
- i != infoFiles.end(); ++i) {
- std::string targetDir = cmSystemTools::GetFilenamePath(*i);
+ for (std::string const& i : infoFiles) {
+ std::string targetDir = cmSystemTools::GetFilenamePath(i);
std::string fname = targetDir + "/fortran.internal";
cmsys::ifstream fin(fname.c_str());
if (fin) {
@@ -262,9 +252,8 @@ void cmDependsFortran::MatchLocalModules()
{
const char* stampDir = this->TargetDirectory.c_str();
std::set<std::string> const& provides = this->Internal->TargetProvides;
- for (std::set<std::string>::const_iterator i = provides.begin();
- i != provides.end(); ++i) {
- this->ConsiderModule(i->c_str(), stampDir);
+ for (std::string const& i : provides) {
+ this->ConsiderModule(i.c_str(), stampDir);
}
}
@@ -326,35 +315,32 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
std::string obj_m = cmSystemTools::ConvertToOutputPath(obj_i.c_str());
internalDepends << obj_i << std::endl;
internalDepends << " " << src << std::endl;
- for (std::set<std::string>::const_iterator i = info.Includes.begin();
- i != info.Includes.end(); ++i) {
+ for (std::string const& i : info.Includes) {
makeDepends << obj_m << ": "
<< cmSystemTools::ConvertToOutputPath(
- this->MaybeConvertToRelativePath(binDir, *i).c_str())
+ this->MaybeConvertToRelativePath(binDir, i).c_str())
<< std::endl;
- internalDepends << " " << *i << std::endl;
+ internalDepends << " " << i << std::endl;
}
makeDepends << std::endl;
// Write module requirements to the output stream.
- for (std::set<std::string>::const_iterator i = info.Requires.begin();
- i != info.Requires.end(); ++i) {
+ for (std::string const& i : info.Requires) {
// Require only modules not provided in the same source.
- if (std::set<std::string>::const_iterator(info.Provides.find(*i)) !=
- info.Provides.end()) {
+ if (info.Provides.find(i) != info.Provides.cend()) {
continue;
}
// If the module is provided in this target special handling is
// needed.
- if (this->Internal->TargetProvides.find(*i) !=
+ if (this->Internal->TargetProvides.find(i) !=
this->Internal->TargetProvides.end()) {
// The module is provided by a different source in the same
// target. Add the proxy dependency to make sure the other
// source builds first.
std::string proxy = stamp_dir;
proxy += "/";
- proxy += *i;
+ proxy += i;
proxy += ".mod.proxy";
proxy = cmSystemTools::ConvertToOutputPath(
this->MaybeConvertToRelativePath(binDir, proxy).c_str());
@@ -366,7 +352,7 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
// The object file should depend on timestamped files for the
// modules it uses.
TargetRequiresMap::const_iterator required =
- this->Internal->TargetRequires.find(*i);
+ this->Internal->TargetRequires.find(i);
if (required == this->Internal->TargetRequires.end()) {
abort();
}
@@ -379,7 +365,7 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
// This module is not known to CMake. Try to locate it where
// the compiler will and depend on that.
std::string module;
- if (this->FindModule(*i, module)) {
+ if (this->FindModule(i, module)) {
module = cmSystemTools::ConvertToOutputPath(
this->MaybeConvertToRelativePath(binDir, module).c_str());
makeDepends << obj_m << ": " << module << "\n";
@@ -388,11 +374,10 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
}
// Write provided modules to the output stream.
- for (std::set<std::string>::const_iterator i = info.Provides.begin();
- i != info.Provides.end(); ++i) {
+ for (std::string const& i : info.Provides) {
std::string proxy = stamp_dir;
proxy += "/";
- proxy += *i;
+ proxy += i;
proxy += ".mod.proxy";
proxy = cmSystemTools::ConvertToOutputPath(
this->MaybeConvertToRelativePath(binDir, proxy).c_str());
@@ -404,18 +389,17 @@ bool cmDependsFortran::WriteDependenciesReal(const char* obj,
// Create a target to copy the module after the object file
// changes.
makeDepends << obj_m << ".provides.build:\n";
- for (std::set<std::string>::const_iterator i = info.Provides.begin();
- i != info.Provides.end(); ++i) {
+ for (std::string const& i : info.Provides) {
// Include this module in the set provided by this target.
- this->Internal->TargetProvides.insert(*i);
+ this->Internal->TargetProvides.insert(i);
// Always use lower case for the mod stamp file name. The
// cmake_copy_f90_mod will call back to this class, which will
// try various cases for the real mod file name.
- std::string m = cmSystemTools::LowerCase(*i);
+ std::string m = cmSystemTools::LowerCase(i);
std::string modFile = mod_dir;
modFile += "/";
- modFile += *i;
+ modFile += i;
modFile = this->LocalGenerator->ConvertToOutputFormat(
this->MaybeConvertToRelativePath(binDir, modFile),
cmOutputConverter::SHELL);
@@ -462,10 +446,9 @@ bool cmDependsFortran::FindModule(std::string const& name, std::string& module)
// Search the include path for the module.
std::string fullName;
- for (std::vector<std::string>::const_iterator i = this->IncludePath.begin();
- i != this->IncludePath.end(); ++i) {
+ for (std::string const& ip : this->IncludePath) {
// Try the lower-case name.
- fullName = *i;
+ fullName = ip;
fullName += "/";
fullName += mod_lower;
if (cmSystemTools::FileExists(fullName.c_str(), true)) {
@@ -474,7 +457,7 @@ bool cmDependsFortran::FindModule(std::string const& name, std::string& module)
}
// Try the upper-case name.
- fullName = *i;
+ fullName = ip;
fullName += "/";
fullName += mod_upper;
if (cmSystemTools::FileExists(fullName.c_str(), true)) {
diff --git a/Source/cmDependsFortran.h b/Source/cmDependsFortran.h
index ec208af3a..ccf267b2f 100644
--- a/Source/cmDependsFortran.h
+++ b/Source/cmDependsFortran.h
@@ -3,7 +3,7 @@
#ifndef cmFortran_h
#define cmFortran_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <set>
@@ -35,7 +35,7 @@ public:
cmDependsFortran(cmLocalGenerator* lg);
/** Virtual destructor to cleanup subclasses properly. */
- ~cmDependsFortran() CM_OVERRIDE;
+ ~cmDependsFortran() override;
/** Callback from build system after a .mod file has been generated
by a Fortran90 compiler to copy the .mod file to the
@@ -50,7 +50,7 @@ public:
protected:
// Finalize the dependency information for the target.
bool Finalize(std::ostream& makeDepends,
- std::ostream& internalDepends) CM_OVERRIDE;
+ std::ostream& internalDepends) override;
// Find all the modules required by the target.
void LocateModules();
@@ -62,7 +62,7 @@ protected:
// Implement writing/checking methods required by superclass.
bool WriteDependencies(const std::set<std::string>& sources,
const std::string& file, std::ostream& makeDepends,
- std::ostream& internalDepends) CM_OVERRIDE;
+ std::ostream& internalDepends) override;
// Actually write the depenencies to the streams.
bool WriteDependenciesReal(const char* obj, cmFortranSourceInfo const& info,
diff --git a/Source/cmDependsJava.h b/Source/cmDependsJava.h
index a07bf0979..d070840ad 100644
--- a/Source/cmDependsJava.h
+++ b/Source/cmDependsJava.h
@@ -3,7 +3,7 @@
#ifndef cmDependsJava_h
#define cmDependsJava_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmDepends.h"
@@ -25,16 +25,16 @@ public:
cmDependsJava();
/** Virtual destructor to cleanup subclasses properly. */
- ~cmDependsJava() CM_OVERRIDE;
+ ~cmDependsJava() override;
protected:
// Implement writing/checking methods required by superclass.
bool WriteDependencies(const std::set<std::string>& sources,
const std::string& file, std::ostream& makeDepends,
- std::ostream& internalDepends) CM_OVERRIDE;
+ std::ostream& internalDepends) override;
bool CheckDependencies(
std::istream& internalDepends, const char* internalDependsFileName,
- std::map<std::string, DependencyVector>& validDeps) CM_OVERRIDE;
+ std::map<std::string, DependencyVector>& validDeps) override;
};
#endif
diff --git a/Source/cmDependsJavaParserHelper.cxx b/Source/cmDependsJavaParserHelper.cxx
index 7bc91bfd4..f227cf25b 100644
--- a/Source/cmDependsJavaParserHelper.cxx
+++ b/Source/cmDependsJavaParserHelper.cxx
@@ -2,8 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmDependsJavaParserHelper.h"
-#include "cmConfigure.h"
-
#include "cmDependsJavaLexer.h"
#include "cmSystemTools.h"
@@ -42,10 +40,8 @@ void cmDependsJavaParserHelper::CurrentClass::AddFileNamesForPrinting(
}
rname += this->Name;
files->push_back(rname);
- std::vector<CurrentClass>::const_iterator it;
- for (it = this->NestedClasses.begin(); it != this->NestedClasses.end();
- ++it) {
- it->AddFileNamesForPrinting(files, rname.c_str(), sep);
+ for (CurrentClass const& nc : this->NestedClasses) {
+ nc.AddFileNamesForPrinting(files, rname.c_str(), sep);
}
}
@@ -57,7 +53,7 @@ void cmDependsJavaParserHelper::DeallocateParserType(char** pt)
if (!*pt) {
return;
}
- *pt = CM_NULLPTR;
+ *pt = nullptr;
this->UnionsAvailable--;
}
@@ -66,9 +62,8 @@ void cmDependsJavaParserHelper::AddClassFound(const char* sclass)
if (!sclass) {
return;
}
- std::vector<std::string>::iterator it;
- for (it = this->ClassesFound.begin(); it != this->ClassesFound.end(); it++) {
- if (*it == sclass) {
+ for (std::string const& cf : this->ClassesFound) {
+ if (cf == sclass) {
return;
}
}
@@ -77,10 +72,8 @@ void cmDependsJavaParserHelper::AddClassFound(const char* sclass)
void cmDependsJavaParserHelper::AddPackagesImport(const char* sclass)
{
- std::vector<std::string>::iterator it;
- for (it = this->PackagesImport.begin(); it != this->PackagesImport.end();
- it++) {
- if (*it == sclass) {
+ for (std::string const& pi : this->PackagesImport) {
+ if (pi == sclass) {
return;
}
}
@@ -96,9 +89,9 @@ void cmDependsJavaParserHelper::SafePrintMissing(const char* str, int line,
for (cc = 0; cc < strlen(str); cc++) {
unsigned char ch = str[cc];
if (ch >= 32 && ch <= 126) {
- std::cout << (char)ch;
+ std::cout << static_cast<char>(ch);
} else {
- std::cout << "<" << (int)ch << ">";
+ std::cout << "<" << static_cast<int>(ch) << ">";
break;
}
}
@@ -158,15 +151,15 @@ void cmDependsJavaParserHelper::PrepareElement(
cmDependsJavaParserHelper::ParserType* me)
{
// Inititalize self
- me->str = CM_NULLPTR;
+ me->str = nullptr;
}
void cmDependsJavaParserHelper::AllocateParserType(
cmDependsJavaParserHelper::ParserType* pt, const char* str, int len)
{
- pt->str = CM_NULLPTR;
+ pt->str = nullptr;
if (len == 0) {
- len = (int)strlen(str);
+ len = static_cast<int>(strlen(str));
}
if (len == 0) {
return;
@@ -210,10 +203,8 @@ void cmDependsJavaParserHelper::PrintClasses()
std::cerr << "Error when parsing. No classes on class stack" << std::endl;
abort();
}
- std::vector<std::string> files = this->GetFilesProduced();
- std::vector<std::string>::iterator sit;
- for (sit = files.begin(); sit != files.end(); ++sit) {
- std::cout << " " << *sit << ".class" << std::endl;
+ for (std::string const& f : this->GetFilesProduced()) {
+ std::cout << " " << f << ".class" << std::endl;
}
}
@@ -221,10 +212,8 @@ std::vector<std::string> cmDependsJavaParserHelper::GetFilesProduced()
{
std::vector<std::string> files;
CurrentClass const& toplevel = this->ClassStack.front();
- std::vector<CurrentClass>::const_iterator it;
- for (it = toplevel.NestedClasses.begin(); it != toplevel.NestedClasses.end();
- ++it) {
- it->AddFileNamesForPrinting(&files, CM_NULLPTR, "$");
+ for (CurrentClass const& nc : toplevel.NestedClasses) {
+ nc.AddFileNamesForPrinting(&files, nullptr, "$");
}
return files;
}
@@ -264,10 +253,8 @@ int cmDependsJavaParserHelper::ParseString(const char* str, int verb)
std::cout << std::endl;
std::cout << "Depends on:";
if (!this->ClassesFound.empty()) {
- std::vector<std::string>::iterator it;
- for (it = this->ClassesFound.begin(); it != this->ClassesFound.end();
- ++it) {
- std::cout << " " << *it;
+ for (std::string const& cf : this->ClassesFound) {
+ std::cout << " " << cf;
}
}
std::cout << std::endl;
@@ -284,9 +271,8 @@ int cmDependsJavaParserHelper::ParseString(const char* str, int verb)
void cmDependsJavaParserHelper::CleanupParser()
{
- std::vector<char*>::iterator it;
- for (it = this->Allocates.begin(); it != this->Allocates.end(); ++it) {
- delete[] * it;
+ for (char* allocate : this->Allocates) {
+ delete[] allocate;
}
this->Allocates.erase(this->Allocates.begin(), this->Allocates.end());
}
@@ -324,7 +310,7 @@ void cmDependsJavaParserHelper::Error(const char* str)
void cmDependsJavaParserHelper::UpdateCombine(const char* str1,
const char* str2)
{
- if (this->CurrentCombine == "" && str1 != CM_NULLPTR) {
+ if (this->CurrentCombine.empty() && str1 != nullptr) {
this->CurrentCombine = str1;
}
this->CurrentCombine += ".";
diff --git a/Source/cmDisallowedCommand.h b/Source/cmDisallowedCommand.h
index 0030116b8..d85c00f8c 100644
--- a/Source/cmDisallowedCommand.h
+++ b/Source/cmDisallowedCommand.h
@@ -3,7 +3,7 @@
#ifndef cmDisallowedCommand_h
#define cmDisallowedCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,23 +24,20 @@ public:
{
}
- ~cmDisallowedCommand() CM_OVERRIDE { delete this->Command; }
+ ~cmDisallowedCommand() override { delete this->Command; }
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
return new cmDisallowedCommand(this->Command->Clone(), this->Policy,
this->Message);
}
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
- void FinalPass() CM_OVERRIDE { this->Command->FinalPass(); }
+ void FinalPass() override { this->Command->FinalPass(); }
- bool HasFinalPass() const CM_OVERRIDE
- {
- return this->Command->HasFinalPass();
- }
+ bool HasFinalPass() const override { return this->Command->HasFinalPass(); }
private:
cmCommand* Command;
diff --git a/Source/cmDocumentation.cxx b/Source/cmDocumentation.cxx
index c6286b35a..0c9686087 100644
--- a/Source/cmDocumentation.cxx
+++ b/Source/cmDocumentation.cxx
@@ -41,12 +41,12 @@ static const char* cmDocumentationStandardOptions[][2] = {
{ "--help-variable-list [<f>]",
"List variables with help available and exit." },
{ "--help-variables [<f>]", "Print cmake-variables manual and exit." },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, nullptr }
};
static const char* cmDocumentationGeneratorsHeader[][2] = {
- { CM_NULLPTR, "The following generators are available on this platform:" },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, "The following generators are available on this platform:" },
+ { nullptr, nullptr }
};
cmDocumentation::cmDocumentation()
@@ -123,23 +123,21 @@ bool cmDocumentation::PrintRequestedDocumentation(std::ostream& os)
bool result = true;
// Loop over requested documentation types.
- for (std::vector<RequestedHelpItem>::const_iterator i =
- this->RequestedHelpItems.begin();
- i != this->RequestedHelpItems.end(); ++i) {
- this->CurrentArgument = i->Argument;
+ for (RequestedHelpItem const& rhi : this->RequestedHelpItems) {
+ this->CurrentArgument = rhi.Argument;
// If a file name was given, use it. Otherwise, default to the
// given stream.
cmsys::ofstream fout;
std::ostream* s = &os;
- if (!i->Filename.empty()) {
- fout.open(i->Filename.c_str());
+ if (!rhi.Filename.empty()) {
+ fout.open(rhi.Filename.c_str());
s = &fout;
} else if (++count > 1) {
os << "\n\n";
}
// Print this documentation type to the stream.
- if (!this->PrintDocumentation(i->HelpType, *s) || s->fail()) {
+ if (!this->PrintDocumentation(rhi.HelpType, *s) || s->fail()) {
result = false;
}
}
@@ -394,16 +392,14 @@ void cmDocumentation::SetSection(const char* name, const char* docs[][2])
void cmDocumentation::SetSections(
std::map<std::string, cmDocumentationSection*>& sections)
{
- for (std::map<std::string, cmDocumentationSection*>::const_iterator it =
- sections.begin();
- it != sections.end(); ++it) {
- this->SetSection(it->first.c_str(), it->second);
+ for (auto const& s : sections) {
+ this->SetSection(s.first.c_str(), s.second);
}
}
void cmDocumentation::PrependSection(const char* name, const char* docs[][2])
{
- cmDocumentationSection* sec = CM_NULLPTR;
+ cmDocumentationSection* sec = nullptr;
if (this->AllSections.find(name) == this->AllSections.end()) {
sec =
new cmDocumentationSection(name, cmSystemTools::UpperCase(name).c_str());
@@ -417,7 +413,7 @@ void cmDocumentation::PrependSection(const char* name, const char* docs[][2])
void cmDocumentation::PrependSection(const char* name,
std::vector<cmDocumentationEntry>& docs)
{
- cmDocumentationSection* sec = CM_NULLPTR;
+ cmDocumentationSection* sec = nullptr;
if (this->AllSections.find(name) == this->AllSections.end()) {
sec =
new cmDocumentationSection(name, cmSystemTools::UpperCase(name).c_str());
@@ -430,7 +426,7 @@ void cmDocumentation::PrependSection(const char* name,
void cmDocumentation::AppendSection(const char* name, const char* docs[][2])
{
- cmDocumentationSection* sec = CM_NULLPTR;
+ cmDocumentationSection* sec = nullptr;
if (this->AllSections.find(name) == this->AllSections.end()) {
sec =
new cmDocumentationSection(name, cmSystemTools::UpperCase(name).c_str());
@@ -444,7 +440,7 @@ void cmDocumentation::AppendSection(const char* name, const char* docs[][2])
void cmDocumentation::AppendSection(const char* name,
std::vector<cmDocumentationEntry>& docs)
{
- cmDocumentationSection* sec = CM_NULLPTR;
+ cmDocumentationSection* sec = nullptr;
if (this->AllSections.find(name) == this->AllSections.end()) {
sec =
new cmDocumentationSection(name, cmSystemTools::UpperCase(name).c_str());
@@ -489,10 +485,9 @@ void cmDocumentation::PrintNames(std::ostream& os, std::string const& pattern)
std::vector<std::string> files;
this->GlobHelp(files, pattern);
std::vector<std::string> names;
- for (std::vector<std::string>::const_iterator i = files.begin();
- i != files.end(); ++i) {
+ for (std::string const& f : files) {
std::string line;
- cmsys::ifstream fin(i->c_str());
+ cmsys::ifstream fin(f.c_str());
while (fin && cmSystemTools::GetLineFromStream(fin, line)) {
if (!line.empty() && (isalnum(line[0]) || line[0] == '<')) {
names.push_back(line);
@@ -501,9 +496,8 @@ void cmDocumentation::PrintNames(std::ostream& os, std::string const& pattern)
}
}
std::sort(names.begin(), names.end());
- for (std::vector<std::string>::iterator i = names.begin(); i != names.end();
- ++i) {
- os << *i << "\n";
+ for (std::string const& n : names) {
+ os << n << "\n";
}
}
@@ -514,9 +508,8 @@ bool cmDocumentation::PrintFiles(std::ostream& os, std::string const& pattern)
this->GlobHelp(files, pattern);
std::sort(files.begin(), files.end());
cmRST r(os, cmSystemTools::GetCMakeRoot() + "/Help");
- for (std::vector<std::string>::const_iterator i = files.begin();
- i != files.end(); ++i) {
- found = r.ProcessFile(*i) || found;
+ for (std::string const& f : files) {
+ found = r.ProcessFile(f) || found;
}
return found;
}
@@ -586,15 +579,13 @@ bool cmDocumentation::PrintHelpListModules(std::ostream& os)
std::vector<std::string> files;
this->GlobHelp(files, "module/*");
std::vector<std::string> modules;
- for (std::vector<std::string>::iterator fi = files.begin();
- fi != files.end(); ++fi) {
- std::string module = cmSystemTools::GetFilenameName(*fi);
+ for (std::string const& f : files) {
+ std::string module = cmSystemTools::GetFilenameName(f);
modules.push_back(module.substr(0, module.size() - 4));
}
std::sort(modules.begin(), modules.end());
- for (std::vector<std::string>::iterator i = modules.begin();
- i != modules.end(); ++i) {
- os << *i << "\n";
+ for (std::string const& m : modules) {
+ os << m << "\n";
}
return true;
}
diff --git a/Source/cmDocumentation.h b/Source/cmDocumentation.h
index 2866fef03..c80bed1cd 100644
--- a/Source/cmDocumentation.h
+++ b/Source/cmDocumentation.h
@@ -3,7 +3,7 @@
#ifndef _cmDocumentation_h
#define _cmDocumentation_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmDocumentationFormatter.h"
@@ -32,7 +32,7 @@ public:
* help arguments.
*/
bool CheckOptions(int argc, const char* const* argv,
- const char* exitOpt = CM_NULLPTR);
+ const char* exitOpt = nullptr);
/**
* Print help requested on the command line. Call after
diff --git a/Source/cmDocumentationFormatter.cxx b/Source/cmDocumentationFormatter.cxx
index 001826318..6b996e4b0 100644
--- a/Source/cmDocumentationFormatter.cxx
+++ b/Source/cmDocumentationFormatter.cxx
@@ -168,26 +168,25 @@ void cmDocumentationFormatter::PrintSection(
os << section.GetName() << "\n";
const std::vector<cmDocumentationEntry>& entries = section.GetEntries();
- for (std::vector<cmDocumentationEntry>::const_iterator op = entries.begin();
- op != entries.end(); ++op) {
- if (!op->Name.empty()) {
- os << " " << op->Name;
+ for (cmDocumentationEntry const& entry : entries) {
+ if (!entry.Name.empty()) {
+ os << " " << entry.Name;
this->TextIndent = " ";
int align = static_cast<int>(strlen(this->TextIndent)) - 4;
- for (int i = static_cast<int>(op->Name.size()); i < align; ++i) {
+ for (int i = static_cast<int>(entry.Name.size()); i < align; ++i) {
os << " ";
}
- if (op->Name.size() > strlen(this->TextIndent) - 4) {
+ if (entry.Name.size() > strlen(this->TextIndent) - 4) {
os << "\n";
os.write(this->TextIndent, strlen(this->TextIndent) - 2);
}
os << "= ";
- this->PrintColumn(os, op->Brief.c_str());
+ this->PrintColumn(os, entry.Brief.c_str());
os << "\n";
} else {
os << "\n";
this->TextIndent = "";
- this->PrintFormatted(os, op->Brief.c_str());
+ this->PrintFormatted(os, entry.Brief.c_str());
}
}
os << "\n";
diff --git a/Source/cmDynamicLoader.cxx b/Source/cmDynamicLoader.cxx
index 7fbe75c7b..7da6ff54b 100644
--- a/Source/cmDynamicLoader.cxx
+++ b/Source/cmDynamicLoader.cxx
@@ -22,7 +22,7 @@ private:
static cmDynamicLoaderCache* Instance;
};
-cmDynamicLoaderCache* cmDynamicLoaderCache::Instance = CM_NULLPTR;
+cmDynamicLoaderCache* cmDynamicLoaderCache::Instance = nullptr;
cmDynamicLoaderCache::~cmDynamicLoaderCache()
{
@@ -65,13 +65,11 @@ bool cmDynamicLoaderCache::FlushCache(const char* path)
void cmDynamicLoaderCache::FlushCache()
{
- for (std::map<std::string, cmsys::DynamicLoader::LibraryHandle>::iterator
- it = this->CacheMap.begin();
- it != this->CacheMap.end(); it++) {
- cmsys::DynamicLoader::CloseLibrary(it->second);
+ for (auto const& it : this->CacheMap) {
+ cmsys::DynamicLoader::CloseLibrary(it.second);
}
delete cmDynamicLoaderCache::Instance;
- cmDynamicLoaderCache::Instance = CM_NULLPTR;
+ cmDynamicLoaderCache::Instance = nullptr;
}
cmDynamicLoaderCache* cmDynamicLoaderCache::GetInstance()
diff --git a/Source/cmDynamicLoader.h b/Source/cmDynamicLoader.h
index 7c46dd5d4..61d3b468b 100644
--- a/Source/cmDynamicLoader.h
+++ b/Source/cmDynamicLoader.h
@@ -8,7 +8,7 @@
#ifndef cmDynamicLoader_h
#define cmDynamicLoader_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmsys/DynamicLoader.hxx" // IWYU pragma: export
diff --git a/Source/cmELF.cxx b/Source/cmELF.cxx
index fc97bf3b3..76374b2f5 100644
--- a/Source/cmELF.cxx
+++ b/Source/cmELF.cxx
@@ -2,10 +2,10 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmELF.h"
-#include "cm_auto_ptr.hxx"
#include "cm_kwiml.h"
#include "cmsys/FStream.hxx"
#include <map>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stddef.h>
#include <utility>
@@ -108,7 +108,7 @@ public:
};
// Construct and take ownership of the file stream object.
- cmELFInternal(cmELF* external, CM_AUTO_PTR<cmsys::ifstream>& fin,
+ cmELFInternal(cmELF* external, std::unique_ptr<cmsys::ifstream>& fin,
ByteOrderType order)
: External(external)
, Stream(*fin.release())
@@ -231,27 +231,27 @@ public:
typedef typename Types::tagtype tagtype;
// Construct with a stream and byte swap indicator.
- cmELFInternalImpl(cmELF* external, CM_AUTO_PTR<cmsys::ifstream>& fin,
+ cmELFInternalImpl(cmELF* external, std::unique_ptr<cmsys::ifstream>& fin,
ByteOrderType order);
// Return the number of sections as specified by the ELF header.
- unsigned int GetNumberOfSections() const CM_OVERRIDE
+ unsigned int GetNumberOfSections() const override
{
return static_cast<unsigned int>(this->ELFHeader.e_shnum);
}
// Get the file position of a dynamic section entry.
- unsigned long GetDynamicEntryPosition(int j) CM_OVERRIDE;
+ unsigned long GetDynamicEntryPosition(int j) override;
- cmELF::DynamicEntryList GetDynamicEntries() CM_OVERRIDE;
- std::vector<char> EncodeDynamicEntries(const cmELF::DynamicEntryList&)
- CM_OVERRIDE;
+ cmELF::DynamicEntryList GetDynamicEntries() override;
+ std::vector<char> EncodeDynamicEntries(
+ const cmELF::DynamicEntryList&) override;
// Lookup a string from the dynamic section with the given tag.
- StringEntry const* GetDynamicSectionString(unsigned int tag) CM_OVERRIDE;
+ StringEntry const* GetDynamicSectionString(unsigned int tag) override;
// Print information about the ELF file.
- void PrintInfo(std::ostream& os) const CM_OVERRIDE
+ void PrintInfo(std::ostream& os) const override
{
os << "ELF " << Types::GetName();
if (this->ByteOrder == ByteOrderMSB) {
@@ -424,9 +424,8 @@ private:
};
template <class Types>
-cmELFInternalImpl<Types>::cmELFInternalImpl(cmELF* external,
- CM_AUTO_PTR<cmsys::ifstream>& fin,
- ByteOrderType order)
+cmELFInternalImpl<Types>::cmELFInternalImpl(
+ cmELF* external, std::unique_ptr<cmsys::ifstream>& fin, ByteOrderType order)
: cmELFInternal(external, fin, order)
{
// Read the main header.
@@ -547,10 +546,7 @@ cmELF::DynamicEntryList cmELFInternalImpl<Types>::GetDynamicEntries()
// Copy into public array
result.reserve(this->DynamicSectionEntries.size());
- for (typename std::vector<ELF_Dyn>::iterator di =
- this->DynamicSectionEntries.begin();
- di != this->DynamicSectionEntries.end(); ++di) {
- ELF_Dyn& dyn = *di;
+ for (ELF_Dyn& dyn : this->DynamicSectionEntries) {
result.push_back(
std::pair<unsigned long, unsigned long>(dyn.d_tag, dyn.d_un.d_val));
}
@@ -565,12 +561,11 @@ std::vector<char> cmELFInternalImpl<Types>::EncodeDynamicEntries(
std::vector<char> result;
result.reserve(sizeof(ELF_Dyn) * entries.size());
- for (cmELF::DynamicEntryList::const_iterator it = entries.begin();
- it != entries.end(); it++) {
+ for (auto const& entry : entries) {
// Store the entry in an ELF_Dyn, byteswap it, then serialize to chars
ELF_Dyn dyn;
- dyn.d_tag = static_cast<tagtype>(it->first);
- dyn.d_un.d_val = static_cast<tagtype>(it->second);
+ dyn.d_tag = static_cast<tagtype>(entry.first);
+ dyn.d_un.d_val = static_cast<tagtype>(entry.second);
if (this->NeedSwap) {
ByteSwap(dyn);
@@ -594,7 +589,7 @@ cmELF::StringEntry const* cmELFInternalImpl<Types>::GetDynamicSectionString(
if (dssi->second.Position > 0) {
return &dssi->second;
}
- return CM_NULLPTR;
+ return nullptr;
}
// Create an entry for this tag. Assume it is missing until found.
@@ -605,14 +600,14 @@ cmELF::StringEntry const* cmELFInternalImpl<Types>::GetDynamicSectionString(
// Try reading the dynamic section.
if (!this->LoadDynamicSection()) {
- return CM_NULLPTR;
+ return nullptr;
}
// Get the string table referenced by the DYNAMIC section.
ELF_Shdr const& sec = this->SectionHeaders[this->DynamicSectionIndex];
if (sec.sh_link >= this->SectionHeaders.size()) {
this->SetErrorMessage("Section DYNAMIC has invalid string table index.");
- return CM_NULLPTR;
+ return nullptr;
}
ELF_Shdr const& strtab = this->SectionHeaders[sec.sh_link];
@@ -627,7 +622,7 @@ cmELF::StringEntry const* cmELFInternalImpl<Types>::GetDynamicSectionString(
if (dyn.d_un.d_val >= strtab.sh_size) {
this->SetErrorMessage("Section DYNAMIC references string beyond "
"the end of its string section.");
- return CM_NULLPTR;
+ return nullptr;
}
// Seek to the position reported by the entry.
@@ -656,7 +651,7 @@ cmELF::StringEntry const* cmELFInternalImpl<Types>::GetDynamicSectionString(
if (!this->Stream) {
this->SetErrorMessage("Dynamic section specifies unreadable RPATH.");
se.Value = "";
- return CM_NULLPTR;
+ return nullptr;
}
// The value has been read successfully. Report it.
@@ -667,7 +662,7 @@ cmELF::StringEntry const* cmELFInternalImpl<Types>::GetDynamicSectionString(
return &se;
}
}
- return CM_NULLPTR;
+ return nullptr;
}
//============================================================================
@@ -683,10 +678,10 @@ const long cmELF::TagMipsRldMapRel = 0;
#endif
cmELF::cmELF(const char* fname)
- : Internal(CM_NULLPTR)
+ : Internal(nullptr)
{
// Try to open the file.
- CM_AUTO_PTR<cmsys::ifstream> fin(new cmsys::ifstream(fname));
+ std::unique_ptr<cmsys::ifstream> fin(new cmsys::ifstream(fname));
// Quit now if the file could not be opened.
if (!fin.get() || !*fin) {
@@ -811,7 +806,7 @@ cmELF::StringEntry const* cmELF::GetSOName()
this->Internal->GetFileType() == cmELF::FileTypeSharedLibrary) {
return this->Internal->GetSOName();
}
- return CM_NULLPTR;
+ return nullptr;
}
cmELF::StringEntry const* cmELF::GetRPath()
@@ -821,7 +816,7 @@ cmELF::StringEntry const* cmELF::GetRPath()
this->Internal->GetFileType() == cmELF::FileTypeSharedLibrary)) {
return this->Internal->GetRPath();
}
- return CM_NULLPTR;
+ return nullptr;
}
cmELF::StringEntry const* cmELF::GetRunPath()
@@ -831,7 +826,7 @@ cmELF::StringEntry const* cmELF::GetRunPath()
this->Internal->GetFileType() == cmELF::FileTypeSharedLibrary)) {
return this->Internal->GetRunPath();
}
- return CM_NULLPTR;
+ return nullptr;
}
void cmELF::PrintInfo(std::ostream& os) const
diff --git a/Source/cmELF.h b/Source/cmELF.h
index a6e407fe1..8c1734888 100644
--- a/Source/cmELF.h
+++ b/Source/cmELF.h
@@ -3,7 +3,7 @@
#ifndef cmELF_h
#define cmELF_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <string>
@@ -64,7 +64,7 @@ public:
};
/** Represent entire dynamic section header */
- typedef std::vector<std::pair<long, unsigned long> > DynamicEntryList;
+ typedef std::vector<std::pair<long, unsigned long>> DynamicEntryList;
/** Get the type of the file opened. */
FileType GetFileType() const;
diff --git a/Source/cmEnableLanguageCommand.cxx b/Source/cmEnableLanguageCommand.cxx
index c57b7b15c..ddd26de9e 100644
--- a/Source/cmEnableLanguageCommand.cxx
+++ b/Source/cmEnableLanguageCommand.cxx
@@ -16,12 +16,11 @@ bool cmEnableLanguageCommand::InitialPass(std::vector<std::string> const& args,
this->SetError("called with incorrect number of arguments");
return false;
}
- for (std::vector<std::string>::const_iterator it = args.begin();
- it != args.end(); ++it) {
- if ((*it) == "OPTIONAL") {
+ for (std::string const& it : args) {
+ if (it == "OPTIONAL") {
optional = true;
} else {
- languages.push_back(*it);
+ languages.push_back(it);
}
}
diff --git a/Source/cmEnableLanguageCommand.h b/Source/cmEnableLanguageCommand.h
index 33c1c22bf..97645a98c 100644
--- a/Source/cmEnableLanguageCommand.h
+++ b/Source/cmEnableLanguageCommand.h
@@ -3,7 +3,7 @@
#ifndef cmEnableLanguageCommand_h
#define cmEnableLanguageCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -26,14 +26,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmEnableLanguageCommand; }
+ cmCommand* Clone() override { return new cmEnableLanguageCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmEnableTestingCommand.h b/Source/cmEnableTestingCommand.h
index e24966221..88a17b9bf 100644
--- a/Source/cmEnableTestingCommand.h
+++ b/Source/cmEnableTestingCommand.h
@@ -3,7 +3,7 @@
#ifndef cmEnableTestingCommand_h
#define cmEnableTestingCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -31,14 +31,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmEnableTestingCommand; }
+ cmCommand* Clone() override { return new cmEnableTestingCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const&,
- cmExecutionStatus&) CM_OVERRIDE;
+ cmExecutionStatus&) override;
};
#endif
diff --git a/Source/cmExecProgramCommand.cxx b/Source/cmExecProgramCommand.cxx
index fcc3c45c6..88e085d5d 100644
--- a/Source/cmExecProgramCommand.cxx
+++ b/Source/cmExecProgramCommand.cxx
@@ -26,8 +26,8 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args,
bool haveoutput_variable = false;
std::string return_variable;
bool havereturn_variable = false;
- for (size_t i = 0; i < args.size(); ++i) {
- if (args[i] == "OUTPUT_VARIABLE") {
+ for (std::string const& arg : args) {
+ if (arg == "OUTPUT_VARIABLE") {
count++;
doingargs = false;
havereturn_variable = false;
@@ -37,10 +37,10 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args,
this->SetError("called with incorrect number of arguments");
return false;
}
- output_variable = args[i];
+ output_variable = arg;
haveoutput_variable = false;
count++;
- } else if (args[i] == "RETURN_VALUE") {
+ } else if (arg == "RETURN_VALUE") {
count++;
doingargs = false;
haveoutput_variable = false;
@@ -50,16 +50,16 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args,
this->SetError("called with incorrect number of arguments");
return false;
}
- return_variable = args[i];
+ return_variable = arg;
havereturn_variable = false;
count++;
- } else if (args[i] == "ARGS") {
+ } else if (arg == "ARGS") {
count++;
havereturn_variable = false;
haveoutput_variable = false;
doingargs = true;
} else if (doingargs) {
- arguments += args[i];
+ arguments += arg;
arguments += " ";
count++;
}
@@ -86,7 +86,7 @@ bool cmExecProgramCommand::InitialPass(std::vector<std::string> const& args,
args[1].c_str(), verbose);
} else {
result = cmExecProgramCommand::RunCommand(command.c_str(), output, retVal,
- CM_NULLPTR, verbose);
+ nullptr, verbose);
}
if (!result) {
retVal = -1;
@@ -205,7 +205,7 @@ bool cmExecProgramCommand::RunCommand(const char* command, std::string& output,
}
fflush(stdout);
fflush(stderr);
- const char* cmd[] = { "/bin/sh", "-c", command, CM_NULLPTR };
+ const char* cmd[] = { "/bin/sh", "-c", command, nullptr };
cmsysProcess_SetCommand(cp, cmd);
#endif
@@ -217,7 +217,7 @@ bool cmExecProgramCommand::RunCommand(const char* command, std::string& output,
int p;
cmProcessOutput processOutput(encoding);
std::string strdata;
- while ((p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR), p)) {
+ while ((p = cmsysProcess_WaitForData(cp, &data, &length, nullptr), p)) {
if (p == cmsysProcess_Pipe_STDOUT || p == cmsysProcess_Pipe_STDERR) {
if (verbose) {
processOutput.DecodeText(data, length, strdata);
@@ -235,7 +235,7 @@ bool cmExecProgramCommand::RunCommand(const char* command, std::string& output,
}
// All output has been read. Wait for the process to exit.
- cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ cmsysProcess_WaitForExit(cp, nullptr);
processOutput.DecodeText(output, output);
// Check the result of running the process.
diff --git a/Source/cmExecProgramCommand.h b/Source/cmExecProgramCommand.h
index 6463c4db5..dc5da740d 100644
--- a/Source/cmExecProgramCommand.h
+++ b/Source/cmExecProgramCommand.h
@@ -3,7 +3,7 @@
#ifndef cmExecProgramCommand_h
#define cmExecProgramCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -27,19 +27,18 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmExecProgramCommand; }
+ cmCommand* Clone() override { return new cmExecProgramCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
static bool RunCommand(const char* command, std::string& output, int& retVal,
- const char* directory = CM_NULLPTR,
- bool verbose = true,
+ const char* directory = nullptr, bool verbose = true,
Encoding encoding = cmProcessOutput::Auto);
};
diff --git a/Source/cmExecuteProcessCommand.cxx b/Source/cmExecuteProcessCommand.cxx
index 8c10dbe29..39e774e83 100644
--- a/Source/cmExecuteProcessCommand.cxx
+++ b/Source/cmExecuteProcessCommand.cxx
@@ -7,6 +7,7 @@
#include <sstream>
#include <stdio.h>
+#include "cmAlgorithms.h"
#include "cmMakefile.h"
#include "cmProcessOutput.h"
#include "cmSystemTools.h"
@@ -15,7 +16,7 @@ class cmExecutionStatus;
static bool cmExecuteProcessCommandIsWhitespace(char c)
{
- return (isspace((int)c) || c == '\n' || c == '\r');
+ return (isspace(static_cast<int>(c)) || c == '\n' || c == '\r');
}
void cmExecuteProcessCommandFixText(std::vector<char>& output,
@@ -31,7 +32,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
this->SetError("called with incorrect number of arguments");
return false;
}
- std::vector<std::vector<const char*> > cmds;
+ std::vector<std::vector<const char*>> cmds;
std::string arguments;
bool doing_command = false;
size_t command_index = 0;
@@ -46,6 +47,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
std::string output_variable;
std::string error_variable;
std::string result_variable;
+ std::string results_variable;
std::string working_directory;
cmProcessOutput::Encoding encoding = cmProcessOutput::None;
for (size_t i = 0; i < args.size(); ++i) {
@@ -77,6 +79,14 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
this->SetError(" called with no value for RESULT_VARIABLE.");
return false;
}
+ } else if (args[i] == "RESULTS_VARIABLE") {
+ doing_command = false;
+ if (++i < args.size()) {
+ results_variable = args[i];
+ } else {
+ this->SetError(" called with no value for RESULTS_VARIABLE.");
+ return false;
+ }
} else if (args[i] == "WORKING_DIRECTORY") {
doing_command = false;
if (++i < args.size()) {
@@ -160,13 +170,13 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
this->SetError(" called with no COMMAND argument.");
return false;
}
- for (unsigned int i = 0; i < cmds.size(); ++i) {
- if (cmds[i].empty()) {
+ for (auto& cmd : cmds) {
+ if (cmd.empty()) {
this->SetError(" given COMMAND argument with no value.");
return false;
}
// Add the null terminating pointer to the command argument list.
- cmds[i].push_back(CM_NULLPTR);
+ cmd.push_back(nullptr);
}
// Parse the timeout string.
@@ -182,8 +192,8 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
cmsysProcess* cp = cmsysProcess_New();
// Set the command sequence.
- for (unsigned int i = 0; i < cmds.size(); ++i) {
- cmsysProcess_AddCommand(cp, &*cmds[i].begin());
+ for (auto const& cmd : cmds) {
+ cmsysProcess_AddCommand(cp, &*cmd.begin());
}
// Set the process working directory.
@@ -234,7 +244,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
int p;
cmProcessOutput processOutput(encoding);
std::string strdata;
- while ((p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR), p)) {
+ while ((p = cmsysProcess_WaitForData(cp, &data, &length, nullptr), p)) {
// Put the output in the right place.
if (p == cmsysProcess_Pipe_STDOUT && !output_quiet) {
if (output_variable.empty()) {
@@ -266,7 +276,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
}
// All output has been read. Wait for the process to exit.
- cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ cmsysProcess_WaitForExit(cp, nullptr);
processOutput.DecodeText(tempOutput, tempOutput);
processOutput.DecodeText(tempError, tempError);
@@ -287,7 +297,7 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
switch (cmsysProcess_GetState(cp)) {
case cmsysProcess_State_Exited: {
int v = cmsysProcess_GetExitValue(cp);
- char buf[100];
+ char buf[16];
sprintf(buf, "%d", v);
this->Makefile->AddDefinition(result_variable, buf);
} break;
@@ -305,6 +315,47 @@ bool cmExecuteProcessCommand::InitialPass(std::vector<std::string> const& args,
break;
}
}
+ // Store the result of running the processes.
+ if (!results_variable.empty()) {
+ switch (cmsysProcess_GetState(cp)) {
+ case cmsysProcess_State_Exited: {
+ std::vector<std::string> res;
+ for (size_t i = 0; i < cmds.size(); ++i) {
+ switch (cmsysProcess_GetStateByIndex(cp, static_cast<int>(i))) {
+ case kwsysProcess_StateByIndex_Exited: {
+ int exitCode =
+ cmsysProcess_GetExitValueByIndex(cp, static_cast<int>(i));
+ char buf[16];
+ sprintf(buf, "%d", exitCode);
+ res.push_back(buf);
+ } break;
+ case kwsysProcess_StateByIndex_Exception:
+ res.push_back(cmsysProcess_GetExceptionStringByIndex(
+ cp, static_cast<int>(i)));
+ break;
+ case kwsysProcess_StateByIndex_Error:
+ default:
+ res.push_back("Error getting the child return code");
+ break;
+ }
+ }
+ this->Makefile->AddDefinition(results_variable,
+ cmJoin(res, ";").c_str());
+ } break;
+ case cmsysProcess_State_Exception:
+ this->Makefile->AddDefinition(results_variable,
+ cmsysProcess_GetExceptionString(cp));
+ break;
+ case cmsysProcess_State_Error:
+ this->Makefile->AddDefinition(results_variable,
+ cmsysProcess_GetErrorString(cp));
+ break;
+ case cmsysProcess_State_Expired:
+ this->Makefile->AddDefinition(results_variable,
+ "Process terminated due to timeout");
+ break;
+ }
+ }
// Delete the process instance.
cmsysProcess_Delete(cp);
diff --git a/Source/cmExecuteProcessCommand.h b/Source/cmExecuteProcessCommand.h
index 08fde0adc..b415deb58 100644
--- a/Source/cmExecuteProcessCommand.h
+++ b/Source/cmExecuteProcessCommand.h
@@ -3,7 +3,7 @@
#ifndef cmExecuteProcessCommand_h
#define cmExecuteProcessCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmExecuteProcessCommand; }
+ cmCommand* Clone() override { return new cmExecuteProcessCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmExportBuildAndroidMKGenerator.cxx b/Source/cmExportBuildAndroidMKGenerator.cxx
index b443fb0b4..5e2cd535d 100644
--- a/Source/cmExportBuildAndroidMKGenerator.cxx
+++ b/Source/cmExportBuildAndroidMKGenerator.cxx
@@ -3,7 +3,7 @@
#include "cmExportBuildAndroidMKGenerator.h"
#include <algorithm>
-#include <map>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <utility>
@@ -16,13 +16,12 @@
#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
cmExportBuildAndroidMKGenerator::cmExportBuildAndroidMKGenerator()
{
- this->LG = CM_NULLPTR;
- this->ExportSet = CM_NULLPTR;
+ this->LG = nullptr;
+ this->ExportSet = nullptr;
}
void cmExportBuildAndroidMKGenerator::GenerateImportHeaderCode(
@@ -98,43 +97,41 @@ void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties(
}
if (!properties.empty()) {
os << "LOCAL_CPP_FEATURES := rtti exceptions\n";
- for (ImportPropertyMap::const_iterator pi = properties.begin();
- pi != properties.end(); ++pi) {
- if (pi->first == "INTERFACE_COMPILE_OPTIONS") {
+ for (auto const& property : properties) {
+ if (property.first == "INTERFACE_COMPILE_OPTIONS") {
os << "LOCAL_CPP_FEATURES += ";
- os << (pi->second) << "\n";
- } else if (pi->first == "INTERFACE_LINK_LIBRARIES") {
+ os << (property.second) << "\n";
+ } else if (property.first == "INTERFACE_LINK_LIBRARIES") {
// need to look at list in pi->second and see if static or shared
// FindTargetToLink
// target->GetLocalGenerator()->FindGeneratorTargetToUse()
// then add to LOCAL_CPPFLAGS
std::vector<std::string> libraries;
- cmSystemTools::ExpandListArgument(pi->second, libraries);
+ cmSystemTools::ExpandListArgument(property.second, libraries);
std::string staticLibs;
std::string sharedLibs;
std::string ldlibs;
- for (std::vector<std::string>::iterator i = libraries.begin();
- i != libraries.end(); ++i) {
+ for (std::string const& lib : libraries) {
cmGeneratorTarget* gt =
- target->GetLocalGenerator()->FindGeneratorTargetToUse(*i);
+ target->GetLocalGenerator()->FindGeneratorTargetToUse(lib);
if (gt) {
if (gt->GetType() == cmStateEnums::SHARED_LIBRARY ||
gt->GetType() == cmStateEnums::MODULE_LIBRARY) {
- sharedLibs += " " + *i;
+ sharedLibs += " " + lib;
} else {
- staticLibs += " " + *i;
+ staticLibs += " " + lib;
}
} else {
// evaluate any generator expressions with the current
// build type of the makefile
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*i);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(lib);
std::string evaluated =
cge->Evaluate(target->GetLocalGenerator(), config);
bool relpath = false;
if (type == cmExportBuildAndroidMKGenerator::INSTALL) {
- relpath = i->substr(0, 3) == "../";
+ relpath = lib.substr(0, 3) == "../";
}
// check for full path or if it already has a -l, or
// in the case of an install check for relative paths
@@ -157,20 +154,19 @@ void cmExportBuildAndroidMKGenerator::GenerateInterfaceProperties(
if (!ldlibs.empty()) {
os << "LOCAL_EXPORT_LDLIBS :=" << ldlibs << "\n";
}
- } else if (pi->first == "INTERFACE_INCLUDE_DIRECTORIES") {
- std::string includes = pi->second;
+ } else if (property.first == "INTERFACE_INCLUDE_DIRECTORIES") {
+ std::string includes = property.second;
std::vector<std::string> includeList;
cmSystemTools::ExpandListArgument(includes, includeList);
os << "LOCAL_EXPORT_C_INCLUDES := ";
std::string end;
- for (std::vector<std::string>::iterator i = includeList.begin();
- i != includeList.end(); ++i) {
- os << end << *i;
+ for (std::string const& i : includeList) {
+ os << end << i;
end = "\\\n";
}
os << "\n";
} else {
- os << "# " << pi->first << " " << (pi->second) << "\n";
+ os << "# " << property.first << " " << (property.second) << "\n";
}
}
}
diff --git a/Source/cmExportBuildAndroidMKGenerator.h b/Source/cmExportBuildAndroidMKGenerator.h
index d028ef48d..c80839bd4 100644
--- a/Source/cmExportBuildAndroidMKGenerator.h
+++ b/Source/cmExportBuildAndroidMKGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmExportBuildAndroidMKGenerator_h
#define cmExportBuildAndroidMKGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <string>
@@ -42,25 +42,24 @@ public:
protected:
// Implement virtual methods from the superclass.
- void GeneratePolicyHeaderCode(std::ostream&) CM_OVERRIDE {}
- void GeneratePolicyFooterCode(std::ostream&) CM_OVERRIDE {}
+ void GeneratePolicyHeaderCode(std::ostream&) override {}
+ void GeneratePolicyFooterCode(std::ostream&) override {}
void GenerateImportHeaderCode(std::ostream& os,
- const std::string& config = "") CM_OVERRIDE;
- void GenerateImportFooterCode(std::ostream& os) CM_OVERRIDE;
+ const std::string& config = "") override;
+ void GenerateImportFooterCode(std::ostream& os) override;
void GenerateImportTargetCode(std::ostream& os,
- const cmGeneratorTarget* target) CM_OVERRIDE;
+ const cmGeneratorTarget* target) override;
void GenerateExpectedTargetsCode(
- std::ostream& os, const std::string& expectedTargets) CM_OVERRIDE;
- void GenerateImportPropertyCode(std::ostream& os, const std::string& config,
- cmGeneratorTarget const* target,
- ImportPropertyMap const& properties)
- CM_OVERRIDE;
+ std::ostream& os, const std::string& expectedTargets) override;
+ void GenerateImportPropertyCode(
+ std::ostream& os, const std::string& config,
+ cmGeneratorTarget const* target,
+ ImportPropertyMap const& properties) override;
void GenerateMissingTargetsCheckCode(
- std::ostream& os,
- const std::vector<std::string>& missingTargets) CM_OVERRIDE;
+ std::ostream& os, const std::vector<std::string>& missingTargets) override;
void GenerateInterfaceProperties(
cmGeneratorTarget const* target, std::ostream& os,
- const ImportPropertyMap& properties) CM_OVERRIDE;
+ const ImportPropertyMap& properties) override;
};
#endif
diff --git a/Source/cmExportBuildFileGenerator.cxx b/Source/cmExportBuildFileGenerator.cxx
index a1c424aca..bb1dda329 100644
--- a/Source/cmExportBuildFileGenerator.cxx
+++ b/Source/cmExportBuildFileGenerator.cxx
@@ -26,8 +26,8 @@ class cmSourceFile;
cmExportBuildFileGenerator::cmExportBuildFileGenerator()
{
- this->LG = CM_NULLPTR;
- this->ExportSet = CM_NULLPTR;
+ this->LG = nullptr;
+ this->ExportSet = nullptr;
}
void cmExportBuildFileGenerator::Compute(cmLocalGenerator* lg)
@@ -45,9 +45,8 @@ bool cmExportBuildFileGenerator::GenerateMainFile(std::ostream& os)
std::string sep;
std::vector<std::string> targets;
this->GetTargets(targets);
- for (std::vector<std::string>::const_iterator tei = targets.begin();
- tei != targets.end(); ++tei) {
- cmGeneratorTarget* te = this->LG->FindGeneratorTargetToUse(*tei);
+ for (std::string const& tei : targets) {
+ cmGeneratorTarget* te = this->LG->FindGeneratorTargetToUse(tei);
expectedTargets += sep + this->Namespace + te->GetExportName();
sep = " ";
if (this->ExportedTargets.insert(te).second) {
@@ -71,10 +70,7 @@ bool cmExportBuildFileGenerator::GenerateMainFile(std::ostream& os)
std::vector<std::string> missingTargets;
// Create all the imported targets.
- for (std::vector<cmGeneratorTarget*>::const_iterator tei =
- this->Exports.begin();
- tei != this->Exports.end(); ++tei) {
- cmGeneratorTarget* gte = *tei;
+ for (cmGeneratorTarget* gte : this->Exports) {
this->GenerateImportTargetCode(os, gte);
gte->Target->AppendBuildInterfaceIncludes();
@@ -115,10 +111,8 @@ bool cmExportBuildFileGenerator::GenerateMainFile(std::ostream& os)
}
// Generate import file content for each configuration.
- for (std::vector<std::string>::const_iterator ci =
- this->Configurations.begin();
- ci != this->Configurations.end(); ++ci) {
- this->GenerateImportConfig(os, *ci, missingTargets);
+ for (std::string const& c : this->Configurations) {
+ this->GenerateImportConfig(os, c, missingTargets);
}
this->GenerateMissingTargetsCheckCode(os, missingTargets);
@@ -130,11 +124,8 @@ void cmExportBuildFileGenerator::GenerateImportTargetsConfig(
std::ostream& os, const std::string& config, std::string const& suffix,
std::vector<std::string>& missingTargets)
{
- for (std::vector<cmGeneratorTarget*>::const_iterator tei =
- this->Exports.begin();
- tei != this->Exports.end(); ++tei) {
+ for (cmGeneratorTarget* target : this->Exports) {
// Collect import properties for this target.
- cmGeneratorTarget* target = *tei;
ImportPropertyMap properties;
if (target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
@@ -184,10 +175,8 @@ void cmExportBuildFileGenerator::SetImportLocationProperty(
target->GetObjectSources(objectSources, config);
std::string const obj_dir = target->GetObjectDirectory(config);
std::vector<std::string> objects;
- for (std::vector<cmSourceFile const*>::const_iterator si =
- objectSources.begin();
- si != objectSources.end(); ++si) {
- const std::string& obj = target->GetObjectName(*si);
+ for (cmSourceFile const* sf : objectSources) {
+ const std::string& obj = target->GetObjectName(sf);
objects.push_back(obj_dir + obj);
}
@@ -233,7 +222,7 @@ void cmExportBuildFileGenerator::HandleMissingTarget(
dependee->GetLocalGenerator()->GetGlobalGenerator();
std::vector<std::string> namespaces = this->FindNamespaces(gg, name);
- int targetOccurrences = (int)namespaces.size();
+ int targetOccurrences = static_cast<int>(namespaces.size());
if (targetOccurrences == 1) {
std::string missingTarget = namespaces[0];
@@ -256,10 +245,8 @@ void cmExportBuildFileGenerator::GetTargets(
std::vector<std::string>& targets) const
{
if (this->ExportSet) {
- for (std::vector<cmTargetExport*>::const_iterator tei =
- this->ExportSet->GetTargetExports()->begin();
- tei != this->ExportSet->GetTargetExports()->end(); ++tei) {
- targets.push_back((*tei)->TargetName);
+ for (cmTargetExport* te : *this->ExportSet->GetTargetExports()) {
+ targets.push_back(te->TargetName);
}
return;
}
@@ -274,10 +261,8 @@ std::vector<std::string> cmExportBuildFileGenerator::FindNamespaces(
std::map<std::string, cmExportBuildFileGenerator*>& exportSets =
gg->GetBuildExportSets();
- for (std::map<std::string, cmExportBuildFileGenerator*>::const_iterator
- expIt = exportSets.begin();
- expIt != exportSets.end(); ++expIt) {
- const cmExportBuildFileGenerator* exportSet = expIt->second;
+ for (auto const& exp : exportSets) {
+ const cmExportBuildFileGenerator* exportSet = exp.second;
std::vector<std::string> targets;
exportSet->GetTargets(targets);
if (std::find(targets.begin(), targets.end(), name) != targets.end()) {
diff --git a/Source/cmExportBuildFileGenerator.h b/Source/cmExportBuildFileGenerator.h
index 0556983ac..6457a7787 100644
--- a/Source/cmExportBuildFileGenerator.h
+++ b/Source/cmExportBuildFileGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmExportBuildFileGenerator_h
#define cmExportBuildFileGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmExportFileGenerator.h"
@@ -49,14 +49,14 @@ public:
protected:
// Implement virtual methods from the superclass.
- bool GenerateMainFile(std::ostream& os) CM_OVERRIDE;
+ bool GenerateMainFile(std::ostream& os) override;
void GenerateImportTargetsConfig(
std::ostream& os, const std::string& config, std::string const& suffix,
- std::vector<std::string>& missingTargets) CM_OVERRIDE;
+ std::vector<std::string>& missingTargets) override;
void HandleMissingTarget(std::string& link_libs,
std::vector<std::string>& missingTargets,
cmGeneratorTarget* depender,
- cmGeneratorTarget* dependee) CM_OVERRIDE;
+ cmGeneratorTarget* dependee) override;
void ComplainAboutMissingTarget(cmGeneratorTarget* depender,
cmGeneratorTarget* dependee,
@@ -69,7 +69,7 @@ protected:
ImportPropertyMap& properties);
std::string InstallNameDir(cmGeneratorTarget* target,
- const std::string& config) CM_OVERRIDE;
+ const std::string& config) override;
std::vector<std::string> FindNamespaces(cmGlobalGenerator* gg,
const std::string& name);
diff --git a/Source/cmExportCommand.cxx b/Source/cmExportCommand.cxx
index 38cd511ea..991312983 100644
--- a/Source/cmExportCommand.cxx
+++ b/Source/cmExportCommand.cxx
@@ -35,7 +35,7 @@ cmExportCommand::cmExportCommand()
, ExportOld(&Helper, "EXPORT_LINK_INTERFACE_LIBRARIES", &ArgumentGroup)
, AndroidMKFile(&Helper, "ANDROID_MK")
{
- this->ExportSet = CM_NULLPTR;
+ this->ExportSet = nullptr;
}
// cmExportCommand
@@ -51,10 +51,10 @@ bool cmExportCommand::InitialPass(std::vector<std::string> const& args,
return this->HandlePackage(args);
}
if (args[0] == "EXPORT") {
- this->ExportSetName.Follows(CM_NULLPTR);
+ this->ExportSetName.Follows(nullptr);
this->ArgumentGroup.Follows(&this->ExportSetName);
} else {
- this->Targets.Follows(CM_NULLPTR);
+ this->Targets.Follows(nullptr);
this->ArgumentGroup.Follows(&this->Targets);
}
@@ -136,42 +136,40 @@ bool cmExportCommand::InitialPass(std::vector<std::string> const& args,
}
this->ExportSet = setMap[setName];
} else if (this->Targets.WasFound()) {
- for (std::vector<std::string>::const_iterator currentTarget =
- this->Targets.GetVector().begin();
- currentTarget != this->Targets.GetVector().end(); ++currentTarget) {
- if (this->Makefile->IsAlias(*currentTarget)) {
+ for (std::string const& currentTarget : this->Targets.GetVector()) {
+ if (this->Makefile->IsAlias(currentTarget)) {
std::ostringstream e;
- e << "given ALIAS target \"" << *currentTarget
+ e << "given ALIAS target \"" << currentTarget
<< "\" which may not be exported.";
this->SetError(e.str());
return false;
}
- if (cmTarget* target = gg->FindTarget(*currentTarget)) {
+ if (cmTarget* target = gg->FindTarget(currentTarget)) {
if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
std::string reason;
if (!this->Makefile->GetGlobalGenerator()
->HasKnownObjectFileLocation(&reason)) {
std::ostringstream e;
- e << "given OBJECT library \"" << *currentTarget
+ e << "given OBJECT library \"" << currentTarget
<< "\" which may not be exported" << reason << ".";
this->SetError(e.str());
return false;
}
}
if (target->GetType() == cmStateEnums::UTILITY) {
- this->SetError("given custom target \"" + *currentTarget +
+ this->SetError("given custom target \"" + currentTarget +
"\" which may not be exported.");
return false;
}
} else {
std::ostringstream e;
- e << "given target \"" << *currentTarget
+ e << "given target \"" << currentTarget
<< "\" which is not built by this project.";
this->SetError(e.str());
return false;
}
- targets.push_back(*currentTarget);
+ targets.push_back(currentTarget);
}
if (this->Append.IsEnabled()) {
if (cmExportBuildFileGenerator* ebfg =
@@ -186,7 +184,7 @@ bool cmExportCommand::InitialPass(std::vector<std::string> const& args,
}
// Setup export file generation.
- cmExportBuildFileGenerator* ebfg = CM_NULLPTR;
+ cmExportBuildFileGenerator* ebfg = nullptr;
if (android) {
ebfg = new cmExportBuildAndroidMKGenerator;
} else {
@@ -209,10 +207,8 @@ bool cmExportCommand::InitialPass(std::vector<std::string> const& args,
if (configurationTypes.empty()) {
configurationTypes.push_back("");
}
- for (std::vector<std::string>::const_iterator ci =
- configurationTypes.begin();
- ci != configurationTypes.end(); ++ci) {
- ebfg->AddConfiguration(*ci);
+ for (std::string const& ct : configurationTypes) {
+ ebfg->AddConfiguration(ct);
}
if (this->ExportSet) {
gg->AddBuildExportExportSet(ebfg);
diff --git a/Source/cmExportCommand.h b/Source/cmExportCommand.h
index c47bc42b9..a5c6751bf 100644
--- a/Source/cmExportCommand.h
+++ b/Source/cmExportCommand.h
@@ -3,7 +3,7 @@
#ifndef cmExportCommand_h
#define cmExportCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -27,14 +27,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmExportCommand; }
+ cmCommand* Clone() override { return new cmExportCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
cmCommandArgumentsHelper Helper;
diff --git a/Source/cmExportFileGenerator.cxx b/Source/cmExportFileGenerator.cxx
index 972f4b9d1..7f0cb9729 100644
--- a/Source/cmExportFileGenerator.cxx
+++ b/Source/cmExportFileGenerator.cxx
@@ -17,9 +17,9 @@
#include "cmTargetExport.h"
#include "cmake.h"
-#include "cm_auto_ptr.hxx"
#include "cmsys/FStream.hxx"
#include <assert.h>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <string.h>
#include <utility>
@@ -65,18 +65,17 @@ const char* cmExportFileGenerator::GetMainExportFileName() const
bool cmExportFileGenerator::GenerateImportFile()
{
// Open the output file to generate it.
- CM_AUTO_PTR<cmsys::ofstream> foutPtr;
+ std::unique_ptr<cmsys::ofstream> foutPtr;
if (this->AppendMode) {
// Open for append.
- CM_AUTO_PTR<cmsys::ofstream> ap(
- new cmsys::ofstream(this->MainImportFile.c_str(), std::ios::app));
- foutPtr = ap;
+ foutPtr = cm::make_unique<cmsys::ofstream>(this->MainImportFile.c_str(),
+ std::ios::app);
} else {
// Generate atomically and with copy-if-different.
- CM_AUTO_PTR<cmGeneratedFileStream> ap(
+ std::unique_ptr<cmGeneratedFileStream> ap(
new cmGeneratedFileStream(this->MainImportFile.c_str(), true));
ap->SetCopyIfDifferent(true);
- foutPtr = ap;
+ foutPtr = std::move(ap);
}
if (!foutPtr.get() || !*foutPtr) {
std::string se = cmSystemTools::GetLastSystemError();
@@ -137,7 +136,7 @@ void cmExportFileGenerator::PopulateInterfaceProperty(
if (input) {
if (!*input) {
// Set to empty
- properties[outputName] = "";
+ properties[outputName].clear();
return;
}
@@ -206,9 +205,8 @@ static bool checkInterfaceDirs(const std::string& prepro,
bool hadFatalError = false;
- for (std::vector<std::string>::iterator li = parts.begin();
- li != parts.end(); ++li) {
- size_t genexPos = cmGeneratorExpression::Find(*li);
+ for (std::string const& li : parts) {
+ size_t genexPos = cmGeneratorExpression::Find(li);
if (genexPos == 0) {
continue;
}
@@ -233,20 +231,20 @@ static bool checkInterfaceDirs(const std::string& prepro,
hadFatalError = true;
}
}
- if (cmHasLiteralPrefix(li->c_str(), "${_IMPORT_PREFIX}")) {
+ if (cmHasLiteralPrefix(li.c_str(), "${_IMPORT_PREFIX}")) {
continue;
}
- if (!cmSystemTools::FileIsFullPath(li->c_str())) {
+ if (!cmSystemTools::FileIsFullPath(li.c_str())) {
/* clang-format off */
e << "Target \"" << target->GetName() << "\" " << prop <<
" property contains relative path:\n"
- " \"" << *li << "\"";
+ " \"" << li << "\"";
/* clang-format on */
target->GetLocalGenerator()->IssueMessage(messageType, e.str());
}
- bool inBinary = isSubDirectory(li->c_str(), topBinaryDir);
- bool inSource = isSubDirectory(li->c_str(), topSourceDir);
- if (isSubDirectory(li->c_str(), installDir)) {
+ bool inBinary = isSubDirectory(li.c_str(), topBinaryDir);
+ bool inSource = isSubDirectory(li.c_str(), topSourceDir);
+ if (isSubDirectory(li.c_str(), installDir)) {
// The include directory is inside the install tree. If the
// install tree is not inside the source tree or build tree then
// fall through to the checks below that the include directory is not
@@ -261,7 +259,7 @@ static bool checkInterfaceDirs(const std::string& prepro,
case cmPolicies::WARN: {
std::ostringstream s;
s << cmPolicies::GetPolicyWarning(cmPolicies::CMP0052) << "\n";
- s << "Directory:\n \"" << *li
+ s << "Directory:\n \"" << li
<< "\"\nin "
"INTERFACE_INCLUDE_DIRECTORIES of target \""
<< target->GetName() << "\" is a subdirectory of the install "
@@ -293,7 +291,7 @@ static bool checkInterfaceDirs(const std::string& prepro,
/* clang-format off */
e << "Target \"" << target->GetName() << "\" " << prop <<
" property contains path:\n"
- " \"" << *li << "\"\nwhich is prefixed in the build directory.";
+ " \"" << li << "\"\nwhich is prefixed in the build directory.";
/* clang-format on */
target->GetLocalGenerator()->IssueMessage(messageType, e.str());
}
@@ -302,7 +300,7 @@ static bool checkInterfaceDirs(const std::string& prepro,
e << "Target \"" << target->GetName() << "\" " << prop
<< " property contains path:\n"
" \""
- << *li << "\"\nwhich is prefixed in the source directory.";
+ << li << "\"\nwhich is prefixed in the source directory.";
target->GetLocalGenerator()->IssueMessage(messageType, e.str());
}
}
@@ -314,17 +312,16 @@ static void prefixItems(std::string& exportDirs)
{
std::vector<std::string> entries;
cmGeneratorExpression::Split(exportDirs, entries);
- exportDirs = "";
+ exportDirs.clear();
const char* sep = "";
- for (std::vector<std::string>::const_iterator ei = entries.begin();
- ei != entries.end(); ++ei) {
+ for (std::string const& e : entries) {
exportDirs += sep;
sep = ";";
- if (!cmSystemTools::FileIsFullPath(ei->c_str()) &&
- ei->find("${_IMPORT_PREFIX}") == std::string::npos) {
+ if (!cmSystemTools::FileIsFullPath(e.c_str()) &&
+ e.find("${_IMPORT_PREFIX}") == std::string::npos) {
exportDirs += "${_IMPORT_PREFIX}/";
}
- exportDirs += *ei;
+ exportDirs += e;
}
}
@@ -343,7 +340,7 @@ void cmExportFileGenerator::PopulateSourcesInterface(
}
if (!*input) {
- properties[propName] = "";
+ properties[propName].clear();
return;
}
@@ -374,7 +371,7 @@ void cmExportFileGenerator::PopulateIncludeDirectoriesInterface(
std::string dirs = cmGeneratorExpression::Preprocess(
tei->InterfaceIncludeDirectories, preprocessRule, true);
this->ReplaceInstallPrefix(dirs);
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(dirs);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(dirs);
std::string exportDirs =
cge->Evaluate(target->GetLocalGenerator(), "", false, target);
@@ -396,7 +393,7 @@ void cmExportFileGenerator::PopulateIncludeDirectoriesInterface(
}
if ((input && !*input) && exportDirs.empty()) {
// Set to empty
- properties[propName] = "";
+ properties[propName].clear();
return;
}
@@ -461,18 +458,17 @@ void getCompatibleInterfaceProperties(cmGeneratorTarget* target,
const cmComputeLinkInformation::ItemVector& deps = info->GetItems();
- for (cmComputeLinkInformation::ItemVector::const_iterator li = deps.begin();
- li != deps.end(); ++li) {
- if (!li->Target) {
+ for (auto const& dep : deps) {
+ if (!dep.Target) {
continue;
}
- getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_BOOL",
+ getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_BOOL",
ifaceProperties);
- getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_STRING",
+ getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_STRING",
ifaceProperties);
- getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_NUMBER_MIN",
+ getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MIN",
ifaceProperties);
- getPropertyContents(li->Target, "COMPATIBLE_INTERFACE_NUMBER_MAX",
+ getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MAX",
ifaceProperties);
}
}
@@ -504,15 +500,13 @@ void cmExportFileGenerator::PopulateCompatibleInterfaceProperties(
std::vector<std::string> configNames;
gtarget->Target->GetMakefile()->GetConfigurations(configNames);
- for (std::vector<std::string>::const_iterator ci = configNames.begin();
- ci != configNames.end(); ++ci) {
- getCompatibleInterfaceProperties(gtarget, ifaceProperties, *ci);
+ for (std::string const& cn : configNames) {
+ getCompatibleInterfaceProperties(gtarget, ifaceProperties, cn);
}
}
- for (std::set<std::string>::const_iterator it = ifaceProperties.begin();
- it != ifaceProperties.end(); ++it) {
- this->PopulateInterfaceProperty("INTERFACE_" + *it, gtarget, properties);
+ for (std::string const& ip : ifaceProperties) {
+ this->PopulateInterfaceProperty("INTERFACE_" + ip, gtarget, properties);
}
}
@@ -524,10 +518,9 @@ void cmExportFileGenerator::GenerateInterfaceProperties(
std::string targetName = this->Namespace;
targetName += target->GetExportName();
os << "set_target_properties(" << targetName << " PROPERTIES\n";
- for (ImportPropertyMap::const_iterator pi = properties.begin();
- pi != properties.end(); ++pi) {
- os << " " << pi->first << " " << cmExportFileGeneratorEscape(pi->second)
- << "\n";
+ for (auto const& property : properties) {
+ os << " " << property.first << " "
+ << cmExportFileGeneratorEscape(property.second) << "\n";
}
os << ")\n\n";
}
@@ -571,15 +564,14 @@ void cmExportFileGenerator::ResolveTargetsInGeneratorExpressions(
cmGeneratorExpression::Split(input, parts);
std::string sep;
- input = "";
- for (std::vector<std::string>::iterator li = parts.begin();
- li != parts.end(); ++li) {
- if (cmGeneratorExpression::Find(*li) == std::string::npos) {
- this->AddTargetNamespace(*li, target, missingTargets);
+ input.clear();
+ for (std::string& li : parts) {
+ if (cmGeneratorExpression::Find(li) == std::string::npos) {
+ this->AddTargetNamespace(li, target, missingTargets);
} else {
- this->ResolveTargetsInGeneratorExpression(*li, target, missingTargets);
+ this->ResolveTargetsInGeneratorExpression(li, target, missingTargets);
}
- input += sep + *li;
+ input += sep + li;
sep = ";";
}
}
@@ -720,7 +712,7 @@ void cmExportFileGenerator::SetImportLinkInterface(
}
if (!*propContent) {
- properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = "";
+ properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix].clear();
return;
}
@@ -797,13 +789,12 @@ void cmExportFileGenerator::SetImportLinkProperty(
// Construct the property value.
std::string link_entries;
const char* sep = "";
- for (typename std::vector<T>::const_iterator li = entries.begin();
- li != entries.end(); ++li) {
+ for (T const& l : entries) {
// Separate this from the previous entry.
link_entries += sep;
sep = ";";
- std::string temp = *li;
+ std::string temp = l;
this->AddTargetNamespace(temp, target, missingTargets);
link_entries += temp;
}
@@ -988,10 +979,9 @@ void cmExportFileGenerator::GenerateImportPropertyCode(
}
os << ")\n";
os << "set_target_properties(" << targetName << " PROPERTIES\n";
- for (ImportPropertyMap::const_iterator pi = properties.begin();
- pi != properties.end(); ++pi) {
- os << " " << pi->first << " " << cmExportFileGeneratorEscape(pi->second)
- << "\n";
+ for (auto const& property : properties) {
+ os << " " << property.first << " "
+ << cmExportFileGeneratorEscape(property.second) << "\n";
}
os << " )\n"
<< "\n";
@@ -1015,9 +1005,9 @@ void cmExportFileGenerator::GenerateMissingTargetsCheckCode(
"foreach(_target ";
/* clang-format on */
std::set<std::string> emitted;
- for (unsigned int i = 0; i < missingTargets.size(); ++i) {
- if (emitted.insert(missingTargets[i]).second) {
- os << "\"" << missingTargets[i] << "\" ";
+ for (std::string const& missingTarget : missingTargets) {
+ if (emitted.insert(missingTarget).second) {
+ os << "\"" << missingTarget << "\" ";
}
}
/* clang-format off */
@@ -1094,9 +1084,8 @@ void cmExportFileGenerator::GenerateImportedFileChecksCode(
"list(APPEND _IMPORT_CHECK_FILES_FOR_"
<< targetName << " ";
- for (std::set<std::string>::const_iterator li = importedLocations.begin();
- li != importedLocations.end(); ++li) {
- ImportPropertyMap::const_iterator pi = properties.find(*li);
+ for (std::string const& li : importedLocations) {
+ ImportPropertyMap::const_iterator pi = properties.find(li);
if (pi != properties.end()) {
os << cmExportFileGeneratorEscape(pi->second) << " ";
}
diff --git a/Source/cmExportInstallAndroidMKGenerator.cxx b/Source/cmExportInstallAndroidMKGenerator.cxx
index 9a1c647d3..fe565e623 100644
--- a/Source/cmExportInstallAndroidMKGenerator.cxx
+++ b/Source/cmExportInstallAndroidMKGenerator.cxx
@@ -34,11 +34,8 @@ void cmExportInstallAndroidMKGenerator::GenerateImportHeaderCode(
}
os << "_IMPORT_PREFIX := "
<< "$(LOCAL_PATH)" << path << "\n\n";
- for (std::vector<cmTargetExport*>::const_iterator tei =
- this->IEGen->GetExportSet()->GetTargetExports()->begin();
- tei != this->IEGen->GetExportSet()->GetTargetExports()->end(); ++tei) {
+ for (cmTargetExport* te : *this->IEGen->GetExportSet()->GetTargetExports()) {
// Collect import properties for this target.
- cmTargetExport const* te = *tei;
if (te->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
diff --git a/Source/cmExportInstallAndroidMKGenerator.h b/Source/cmExportInstallAndroidMKGenerator.h
index ebef78365..316598290 100644
--- a/Source/cmExportInstallAndroidMKGenerator.h
+++ b/Source/cmExportInstallAndroidMKGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmExportInstallAndroidMKGenerator_h
#define cmExportInstallAndroidMKGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <set>
@@ -36,37 +36,36 @@ public:
protected:
// Implement virtual methods from the superclass.
- void GeneratePolicyHeaderCode(std::ostream&) CM_OVERRIDE {}
- void GeneratePolicyFooterCode(std::ostream&) CM_OVERRIDE {}
+ void GeneratePolicyHeaderCode(std::ostream&) override {}
+ void GeneratePolicyFooterCode(std::ostream&) override {}
void GenerateImportHeaderCode(std::ostream& os,
- const std::string& config = "") CM_OVERRIDE;
- void GenerateImportFooterCode(std::ostream& os) CM_OVERRIDE;
+ const std::string& config = "") override;
+ void GenerateImportFooterCode(std::ostream& os) override;
void GenerateImportTargetCode(std::ostream& os,
- const cmGeneratorTarget* target) CM_OVERRIDE;
+ const cmGeneratorTarget* target) override;
void GenerateExpectedTargetsCode(
- std::ostream& os, const std::string& expectedTargets) CM_OVERRIDE;
- void GenerateImportPropertyCode(std::ostream& os, const std::string& config,
- cmGeneratorTarget const* target,
- ImportPropertyMap const& properties)
- CM_OVERRIDE;
+ std::ostream& os, const std::string& expectedTargets) override;
+ void GenerateImportPropertyCode(
+ std::ostream& os, const std::string& config,
+ cmGeneratorTarget const* target,
+ ImportPropertyMap const& properties) override;
void GenerateMissingTargetsCheckCode(
- std::ostream& os,
- const std::vector<std::string>& missingTargets) CM_OVERRIDE;
+ std::ostream& os, const std::vector<std::string>& missingTargets) override;
void GenerateInterfaceProperties(
cmGeneratorTarget const* target, std::ostream& os,
- const ImportPropertyMap& properties) CM_OVERRIDE;
- void GenerateImportPrefix(std::ostream& os) CM_OVERRIDE;
- void LoadConfigFiles(std::ostream&) CM_OVERRIDE;
+ const ImportPropertyMap& properties) override;
+ void GenerateImportPrefix(std::ostream& os) override;
+ void LoadConfigFiles(std::ostream&) override;
void GenerateRequiredCMakeVersion(std::ostream& os,
- const char* versionString) CM_OVERRIDE;
- void CleanupTemporaryVariables(std::ostream&) CM_OVERRIDE;
- void GenerateImportedFileCheckLoop(std::ostream& os) CM_OVERRIDE;
+ const char* versionString) override;
+ void CleanupTemporaryVariables(std::ostream&) override;
+ void GenerateImportedFileCheckLoop(std::ostream& os) override;
void GenerateImportedFileChecksCode(
std::ostream& os, cmGeneratorTarget* target,
ImportPropertyMap const& properties,
- const std::set<std::string>& importedLocations) CM_OVERRIDE;
+ const std::set<std::string>& importedLocations) override;
bool GenerateImportFileConfig(const std::string& config,
- std::vector<std::string>&) CM_OVERRIDE;
+ std::vector<std::string>&) override;
};
#endif
diff --git a/Source/cmExportInstallFileGenerator.cxx b/Source/cmExportInstallFileGenerator.cxx
index 664a34276..9b65e9e5c 100644
--- a/Source/cmExportInstallFileGenerator.cxx
+++ b/Source/cmExportInstallFileGenerator.cxx
@@ -4,7 +4,6 @@
#include "cmAlgorithms.h"
#include "cmExportSet.h"
-#include "cmExportSetMap.h"
#include "cmGeneratedFileStream.h"
#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
@@ -22,6 +21,8 @@
#include <sstream>
#include <utility>
+class cmExportSetMap;
+
cmExportInstallFileGenerator::cmExportInstallFileGenerator(
cmInstallExportGenerator* iegen)
: IEGen(iegen)
@@ -42,14 +43,10 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os)
{
std::string expectedTargets;
std::string sep;
- for (std::vector<cmTargetExport*>::const_iterator tei =
- this->IEGen->GetExportSet()->GetTargetExports()->begin();
- tei != this->IEGen->GetExportSet()->GetTargetExports()->end();
- ++tei) {
- expectedTargets +=
- sep + this->Namespace + (*tei)->Target->GetExportName();
+ for (cmTargetExport* te :
+ *this->IEGen->GetExportSet()->GetTargetExports()) {
+ expectedTargets += sep + this->Namespace + te->Target->GetExportName();
sep = " ";
- cmTargetExport* te = *tei;
if (this->ExportedTargets.insert(te->Target).second) {
allTargets.push_back(te);
} else {
@@ -76,9 +73,8 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os)
bool require3_1_0 = false;
bool requiresConfigFiles = false;
// Create all the imported targets.
- for (std::vector<cmTargetExport*>::const_iterator tei = allTargets.begin();
- tei != allTargets.end(); ++tei) {
- cmGeneratorTarget* gt = (*tei)->Target;
+ for (cmTargetExport* te : allTargets) {
+ cmGeneratorTarget* gt = te->Target;
requiresConfigFiles =
requiresConfigFiles || gt->GetType() != cmStateEnums::INTERFACE_LIBRARY;
@@ -88,10 +84,8 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os)
ImportPropertyMap properties;
this->PopulateIncludeDirectoriesInterface(
- *tei, cmGeneratorExpression::InstallInterface, properties,
- missingTargets);
- this->PopulateSourcesInterface(*tei,
- cmGeneratorExpression::InstallInterface,
+ te, cmGeneratorExpression::InstallInterface, properties, missingTargets);
+ this->PopulateSourcesInterface(te, cmGeneratorExpression::InstallInterface,
properties, missingTargets);
this->PopulateInterfaceProperty("INTERFACE_SYSTEM_INCLUDE_DIRECTORIES", gt,
cmGeneratorExpression::InstallInterface,
@@ -154,10 +148,8 @@ bool cmExportInstallFileGenerator::GenerateMainFile(std::ostream& os)
// Generate an import file for each configuration.
// Don't do this if we only export INTERFACE_LIBRARY targets.
if (requiresConfigFiles) {
- for (std::vector<std::string>::const_iterator ci =
- this->Configurations.begin();
- ci != this->Configurations.end(); ++ci) {
- if (!this->GenerateImportFileConfig(*ci, missingTargets)) {
+ for (std::string const& c : this->Configurations) {
+ if (!this->GenerateImportFileConfig(c, missingTargets)) {
result = false;
}
}
@@ -314,11 +306,8 @@ void cmExportInstallFileGenerator::GenerateImportTargetsConfig(
std::vector<std::string>& missingTargets)
{
// Add each target in the set to the export.
- for (std::vector<cmTargetExport*>::const_iterator tei =
- this->IEGen->GetExportSet()->GetTargetExports()->begin();
- tei != this->IEGen->GetExportSet()->GetTargetExports()->end(); ++tei) {
+ for (cmTargetExport* te : *this->IEGen->GetExportSet()->GetTargetExports()) {
// Collect import properties for this target.
- cmTargetExport const* te = *tei;
if (te->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
@@ -409,9 +398,8 @@ void cmExportInstallFileGenerator::SetImportLocationProperty(
// IMPORTED_OBJECTS as a list of object files
std::vector<std::string> objects;
itgen->GetInstallObjectNames(config, objects);
- for (std::vector<std::string>::iterator i = objects.begin();
- i != objects.end(); ++i) {
- *i = value + *i;
+ for (std::string& obj : objects) {
+ obj = value + obj;
}
// Store the property.
@@ -445,7 +433,7 @@ void cmExportInstallFileGenerator::HandleMissingTarget(
const std::string name = dependee->GetName();
cmGlobalGenerator* gg = dependee->GetLocalGenerator()->GetGlobalGenerator();
std::vector<std::string> namespaces = this->FindNamespaces(gg, name);
- int targetOccurrences = (int)namespaces.size();
+ int targetOccurrences = static_cast<int>(namespaces.size());
if (targetOccurrences == 1) {
std::string missingTarget = namespaces[0];
@@ -465,15 +453,14 @@ std::vector<std::string> cmExportInstallFileGenerator::FindNamespaces(
std::vector<std::string> namespaces;
const cmExportSetMap& exportSets = gg->GetExportSets();
- for (cmExportSetMap::const_iterator expIt = exportSets.begin();
- expIt != exportSets.end(); ++expIt) {
- const cmExportSet* exportSet = expIt->second;
+ for (auto const& expIt : exportSets) {
+ const cmExportSet* exportSet = expIt.second;
std::vector<cmTargetExport*> const* targets =
exportSet->GetTargetExports();
bool containsTarget = false;
- for (unsigned int i = 0; i < targets->size(); i++) {
- if (name == (*targets)[i]->TargetName) {
+ for (cmTargetExport* target : *targets) {
+ if (name == target->TargetName) {
containsTarget = true;
break;
}
@@ -482,8 +469,8 @@ std::vector<std::string> cmExportInstallFileGenerator::FindNamespaces(
if (containsTarget) {
std::vector<cmInstallExportGenerator const*> const* installs =
exportSet->GetInstallations();
- for (unsigned int i = 0; i < installs->size(); i++) {
- namespaces.push_back((*installs)[i]->GetNamespace());
+ for (cmInstallExportGenerator const* install : *installs) {
+ namespaces.push_back(install->GetNamespace());
}
}
}
diff --git a/Source/cmExportInstallFileGenerator.h b/Source/cmExportInstallFileGenerator.h
index 8fa9b7f88..cda8433a2 100644
--- a/Source/cmExportInstallFileGenerator.h
+++ b/Source/cmExportInstallFileGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmExportInstallFileGenerator_h
#define cmExportInstallFileGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmExportFileGenerator.h"
@@ -53,16 +53,16 @@ public:
protected:
// Implement virtual methods from the superclass.
- bool GenerateMainFile(std::ostream& os) CM_OVERRIDE;
+ bool GenerateMainFile(std::ostream& os) override;
void GenerateImportTargetsConfig(
std::ostream& os, const std::string& config, std::string const& suffix,
- std::vector<std::string>& missingTargets) CM_OVERRIDE;
+ std::vector<std::string>& missingTargets) override;
void HandleMissingTarget(std::string& link_libs,
std::vector<std::string>& missingTargets,
cmGeneratorTarget* depender,
- cmGeneratorTarget* dependee) CM_OVERRIDE;
+ cmGeneratorTarget* dependee) override;
- void ReplaceInstallPrefix(std::string& input) CM_OVERRIDE;
+ void ReplaceInstallPrefix(std::string& input) override;
void ComplainAboutMissingTarget(cmGeneratorTarget* depender,
cmGeneratorTarget* dependee,
@@ -91,7 +91,7 @@ protected:
std::set<std::string>& importedLocations);
std::string InstallNameDir(cmGeneratorTarget* target,
- const std::string& config) CM_OVERRIDE;
+ const std::string& config) override;
cmInstallExportGenerator* IEGen;
diff --git a/Source/cmExportLibraryDependenciesCommand.cxx b/Source/cmExportLibraryDependenciesCommand.cxx
index 69150aee4..50f8cb014 100644
--- a/Source/cmExportLibraryDependenciesCommand.cxx
+++ b/Source/cmExportLibraryDependenciesCommand.cxx
@@ -4,8 +4,10 @@
#include "cmsys/FStream.hxx"
#include <map>
+#include <memory> // IWYU pragma: keep
#include <utility>
+#include "cmAlgorithms.h"
#include "cmGeneratedFileStream.h"
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
@@ -13,8 +15,6 @@
#include "cmSystemTools.h"
#include "cmTarget.h"
#include "cmTargetLinkLibraryType.h"
-#include "cm_auto_ptr.hxx"
-#include "cm_unordered_map.hxx"
#include "cmake.h"
class cmExecutionStatus;
@@ -48,16 +48,15 @@ void cmExportLibraryDependenciesCommand::FinalPass()
void cmExportLibraryDependenciesCommand::ConstFinalPass() const
{
// Use copy-if-different if not appending.
- CM_AUTO_PTR<cmsys::ofstream> foutPtr;
+ std::unique_ptr<cmsys::ofstream> foutPtr;
if (this->Append) {
- CM_AUTO_PTR<cmsys::ofstream> ap(
- new cmsys::ofstream(this->Filename.c_str(), std::ios::app));
- foutPtr = ap;
+ foutPtr =
+ cm::make_unique<cmsys::ofstream>(this->Filename.c_str(), std::ios::app);
} else {
- CM_AUTO_PTR<cmGeneratedFileStream> ap(
+ std::unique_ptr<cmGeneratedFileStream> ap(
new cmGeneratedFileStream(this->Filename.c_str(), true));
ap->SetCopyIfDifferent(true);
- foutPtr = ap;
+ foutPtr = std::move(ap);
}
std::ostream& fout = *foutPtr;
@@ -75,12 +74,11 @@ void cmExportLibraryDependenciesCommand::ConstFinalPass() const
std::map<std::string, std::string> libDepsOld;
std::map<std::string, std::string> libDepsNew;
std::map<std::string, std::string> libTypes;
- for (std::vector<cmMakefile*>::const_iterator i = locals.begin();
- i != locals.end(); ++i) {
- const cmTargets& tgts = (*i)->GetTargets();
- for (cmTargets::const_iterator l = tgts.begin(); l != tgts.end(); ++l) {
+ for (cmMakefile* local : locals) {
+ const cmTargets& tgts = local->GetTargets();
+ for (auto const& tgt : tgts) {
// Get the current target.
- cmTarget const& target = l->second;
+ cmTarget const& target = tgt.second;
// Skip non-library targets.
if (target.GetType() < cmStateEnums::STATIC_LIBRARY ||
@@ -98,12 +96,11 @@ void cmExportLibraryDependenciesCommand::ConstFinalPass() const
std::string valueNew;
cmTarget::LinkLibraryVectorType const& libs =
target.GetOriginalLinkLibraries();
- for (cmTarget::LinkLibraryVectorType::const_iterator li = libs.begin();
- li != libs.end(); ++li) {
- std::string ltVar = li->first;
+ for (cmTarget::LibraryID const& li : libs) {
+ std::string ltVar = li.first;
ltVar += "_LINK_TYPE";
std::string ltValue;
- switch (li->second) {
+ switch (li.second) {
case GENERAL_LibraryType:
valueNew += "general;";
ltValue = "general";
@@ -117,7 +114,7 @@ void cmExportLibraryDependenciesCommand::ConstFinalPass() const
ltValue = "optimized";
break;
}
- std::string lib = li->first;
+ std::string lib = li.first;
if (cmTarget* libtgt = global->FindTarget(lib)) {
// Handle simple output name changes. This command is
// deprecated so we do not support full target name
@@ -150,26 +147,21 @@ void cmExportLibraryDependenciesCommand::ConstFinalPass() const
fout << "# Generated by CMake\n\n";
fout << "if(" << vertest << ")\n";
fout << " # Information for CMake 2.6 and above.\n";
- for (std::map<std::string, std::string>::const_iterator i =
- libDepsNew.begin();
- i != libDepsNew.end(); ++i) {
- if (!i->second.empty()) {
- fout << " set(\"" << i->first << "\" \"" << i->second << "\")\n";
+ for (auto const& i : libDepsNew) {
+ if (!i.second.empty()) {
+ fout << " set(\"" << i.first << "\" \"" << i.second << "\")\n";
}
}
fout << "else()\n";
fout << " # Information for CMake 2.4 and lower.\n";
- for (std::map<std::string, std::string>::const_iterator i =
- libDepsOld.begin();
- i != libDepsOld.end(); ++i) {
- if (!i->second.empty()) {
- fout << " set(\"" << i->first << "\" \"" << i->second << "\")\n";
+ for (auto const& i : libDepsOld) {
+ if (!i.second.empty()) {
+ fout << " set(\"" << i.first << "\" \"" << i.second << "\")\n";
}
}
- for (std::map<std::string, std::string>::const_iterator i = libTypes.begin();
- i != libTypes.end(); ++i) {
- if (i->second != "general") {
- fout << " set(\"" << i->first << "\" \"" << i->second << "\")\n";
+ for (auto const& i : libTypes) {
+ if (i.second != "general") {
+ fout << " set(\"" << i.first << "\" \"" << i.second << "\")\n";
}
}
fout << "endif()\n";
diff --git a/Source/cmExportLibraryDependenciesCommand.h b/Source/cmExportLibraryDependenciesCommand.h
index 5559af94b..bf5e9bc54 100644
--- a/Source/cmExportLibraryDependenciesCommand.h
+++ b/Source/cmExportLibraryDependenciesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmExportLibraryDependenciesCommand_h
#define cmExportLibraryDependenciesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,15 +15,15 @@ class cmExecutionStatus;
class cmExportLibraryDependenciesCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
return new cmExportLibraryDependenciesCommand;
}
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
- void FinalPass() CM_OVERRIDE;
- bool HasFinalPass() const CM_OVERRIDE { return true; }
+ void FinalPass() override;
+ bool HasFinalPass() const override { return true; }
private:
std::string Filename;
diff --git a/Source/cmExportSet.cxx b/Source/cmExportSet.cxx
index a93667994..a6fa186c7 100644
--- a/Source/cmExportSet.cxx
+++ b/Source/cmExportSet.cxx
@@ -13,9 +13,8 @@ cmExportSet::~cmExportSet()
void cmExportSet::Compute(cmLocalGenerator* lg)
{
- for (std::vector<cmTargetExport*>::iterator it = this->TargetExports.begin();
- it != this->TargetExports.end(); ++it) {
- (*it)->Target = lg->FindGeneratorTargetToUse((*it)->TargetName);
+ for (cmTargetExport* tgtExport : this->TargetExports) {
+ tgtExport->Target = lg->FindGeneratorTargetToUse(tgtExport->TargetName);
}
}
diff --git a/Source/cmExportTryCompileFileGenerator.cxx b/Source/cmExportTryCompileFileGenerator.cxx
index cd0a7e69a..1fb9cf818 100644
--- a/Source/cmExportTryCompileFileGenerator.cxx
+++ b/Source/cmExportTryCompileFileGenerator.cxx
@@ -11,9 +11,9 @@
#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
-#include "cm_auto_ptr.hxx"
#include <map>
+#include <memory> // IWYU pragma: keep
#include <utility>
cmExportTryCompileFileGenerator::cmExportTryCompileFileGenerator(
@@ -62,10 +62,10 @@ std::string cmExportTryCompileFileGenerator::FindTargets(
cmGeneratorExpression ge;
- cmGeneratorExpressionDAGChecker dagChecker(tgt->GetName(), propName,
- CM_NULLPTR, CM_NULLPTR);
+ cmGeneratorExpressionDAGChecker dagChecker(tgt->GetName(), propName, nullptr,
+ nullptr);
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
cmTarget dummyHead("try_compile_dummy_exe", cmStateEnums::EXECUTABLE,
cmTarget::VisibilityNormal, tgt->Target->GetMakefile());
@@ -77,11 +77,9 @@ std::string cmExportTryCompileFileGenerator::FindTargets(
const std::set<cmGeneratorTarget const*>& allTargets =
cge->GetAllTargetsSeen();
- for (std::set<cmGeneratorTarget const*>::const_iterator li =
- allTargets.begin();
- li != allTargets.end(); ++li) {
- if (emitted.insert(*li).second) {
- this->Exports.push_back(*li);
+ for (cmGeneratorTarget const* target : allTargets) {
+ if (emitted.insert(target).second) {
+ this->Exports.push_back(target);
}
}
return result;
@@ -92,22 +90,20 @@ void cmExportTryCompileFileGenerator::PopulateProperties(
std::set<cmGeneratorTarget const*>& emitted)
{
std::vector<std::string> props = target->GetPropertyKeys();
- for (std::vector<std::string>::const_iterator i = props.begin();
- i != props.end(); ++i) {
+ for (std::string const& p : props) {
- properties[*i] = target->GetProperty(*i);
+ properties[p] = target->GetProperty(p);
- if (i->find("IMPORTED_LINK_INTERFACE_LIBRARIES") == 0 ||
- i->find("IMPORTED_LINK_DEPENDENT_LIBRARIES") == 0 ||
- i->find("INTERFACE_LINK_LIBRARIES") == 0) {
- std::string evalResult = this->FindTargets(*i, target, emitted);
+ if (p.find("IMPORTED_LINK_INTERFACE_LIBRARIES") == 0 ||
+ p.find("IMPORTED_LINK_DEPENDENT_LIBRARIES") == 0 ||
+ p.find("INTERFACE_LINK_LIBRARIES") == 0) {
+ std::string evalResult = this->FindTargets(p, target, emitted);
std::vector<std::string> depends;
cmSystemTools::ExpandListArgument(evalResult, depends);
- for (std::vector<std::string>::const_iterator li = depends.begin();
- li != depends.end(); ++li) {
+ for (std::string const& li : depends) {
cmGeneratorTarget* tgt =
- target->GetLocalGenerator()->FindGeneratorTargetToUse(*li);
+ target->GetLocalGenerator()->FindGeneratorTargetToUse(li);
if (tgt && emitted.insert(tgt).second) {
this->Exports.push_back(tgt);
}
diff --git a/Source/cmExportTryCompileFileGenerator.h b/Source/cmExportTryCompileFileGenerator.h
index 9671fac8f..70c385728 100644
--- a/Source/cmExportTryCompileFileGenerator.h
+++ b/Source/cmExportTryCompileFileGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmExportTryCompileFileGenerator_h
#define cmExportTryCompileFileGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmExportFileGenerator.h"
@@ -27,15 +27,15 @@ public:
void SetConfig(const std::string& config) { this->Config = config; }
protected:
// Implement virtual methods from the superclass.
- bool GenerateMainFile(std::ostream& os) CM_OVERRIDE;
+ bool GenerateMainFile(std::ostream& os) override;
void GenerateImportTargetsConfig(std::ostream&, const std::string&,
std::string const&,
- std::vector<std::string>&) CM_OVERRIDE
+ std::vector<std::string>&) override
{
}
void HandleMissingTarget(std::string&, std::vector<std::string>&,
- cmGeneratorTarget*, cmGeneratorTarget*) CM_OVERRIDE
+ cmGeneratorTarget*, cmGeneratorTarget*) override
{
}
@@ -44,7 +44,7 @@ protected:
std::set<const cmGeneratorTarget*>& emitted);
std::string InstallNameDir(cmGeneratorTarget* target,
- const std::string& config) CM_OVERRIDE;
+ const std::string& config) override;
private:
std::string FindTargets(const std::string& prop,
diff --git a/Source/cmExprParserHelper.cxx b/Source/cmExprParserHelper.cxx
index c3f026a4e..fe7159a8d 100644
--- a/Source/cmExprParserHelper.cxx
+++ b/Source/cmExprParserHelper.cxx
@@ -2,8 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmExprParserHelper.h"
-#include "cmConfigure.h"
-
#include "cmExprLexer.h"
#include <iostream>
@@ -14,7 +12,7 @@ int cmExpr_yyparse(yyscan_t yyscanner);
cmExprParserHelper::cmExprParserHelper()
{
this->FileLine = -1;
- this->FileName = CM_NULLPTR;
+ this->FileName = nullptr;
}
cmExprParserHelper::~cmExprParserHelper()
diff --git a/Source/cmExternalMakefileProjectGenerator.h b/Source/cmExternalMakefileProjectGenerator.h
index 6b8903790..a1734eef2 100644
--- a/Source/cmExternalMakefileProjectGenerator.h
+++ b/Source/cmExternalMakefileProjectGenerator.h
@@ -99,7 +99,7 @@ public:
}
cmExternalMakefileProjectGenerator* CreateExternalMakefileProjectGenerator()
- const CM_OVERRIDE
+ const override
{
T* p = new T;
p->SetName(GetName());
diff --git a/Source/cmExtraCodeBlocksGenerator.cxx b/Source/cmExtraCodeBlocksGenerator.cxx
index 5b7b82762..9c9b75b17 100644
--- a/Source/cmExtraCodeBlocksGenerator.cxx
+++ b/Source/cmExtraCodeBlocksGenerator.cxx
@@ -4,6 +4,7 @@
#include <map>
#include <ostream>
+#include <set>
#include <string.h>
#include <utility>
@@ -62,11 +63,9 @@ cmExtraCodeBlocksGenerator::GetFactory()
void cmExtraCodeBlocksGenerator::Generate()
{
// for each sub project in the project create a codeblocks project
- for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
- it = this->GlobalGenerator->GetProjectMap().begin();
- it != this->GlobalGenerator->GetProjectMap().end(); ++it) {
+ for (auto const& it : this->GlobalGenerator->GetProjectMap()) {
// create a project file
- this->CreateProjectFile(it->second);
+ this->CreateProjectFile(it.second);
}
}
@@ -95,7 +94,7 @@ struct Tree
{
std::string path; // only one component of the path
std::vector<Tree> folders;
- std::vector<std::string> files;
+ std::set<std::string> files;
void InsertPath(const std::vector<std::string>& splitted,
std::vector<std::string>::size_type start,
const std::string& fileName);
@@ -112,18 +111,17 @@ void Tree::InsertPath(const std::vector<std::string>& splitted,
const std::string& fileName)
{
if (start == splitted.size()) {
- files.push_back(fileName);
+ files.insert(fileName);
return;
}
- for (std::vector<Tree>::iterator it = folders.begin(); it != folders.end();
- ++it) {
- if ((*it).path == splitted[start]) {
+ for (Tree& folder : folders) {
+ if (folder.path == splitted[start]) {
if (start + 1 < splitted.size()) {
- it->InsertPath(splitted, start + 1, fileName);
+ folder.InsertPath(splitted, start + 1, fileName);
return;
}
// last part of splitted
- it->files.push_back(fileName);
+ folder.files.insert(fileName);
return;
}
}
@@ -136,7 +134,7 @@ void Tree::InsertPath(const std::vector<std::string>& splitted,
return;
}
// last part of splitted
- newFolder.files.push_back(fileName);
+ newFolder.files.insert(fileName);
folders.push_back(newFolder);
}
@@ -144,9 +142,8 @@ void Tree::BuildVirtualFolder(cmXMLWriter& xml) const
{
xml.StartElement("Option");
std::string virtualFolders = "CMake Files\\;";
- for (std::vector<Tree>::const_iterator it = folders.begin();
- it != folders.end(); ++it) {
- it->BuildVirtualFolderImpl(virtualFolders, "");
+ for (Tree const& folder : folders) {
+ folder.BuildVirtualFolderImpl(virtualFolders, "");
}
xml.Attribute("virtualFolders", virtualFolders);
xml.EndElement();
@@ -156,18 +153,16 @@ void Tree::BuildVirtualFolderImpl(std::string& virtualFolders,
const std::string& prefix) const
{
virtualFolders += "CMake Files\\" + prefix + path + "\\;";
- for (std::vector<Tree>::const_iterator it = folders.begin();
- it != folders.end(); ++it) {
- it->BuildVirtualFolderImpl(virtualFolders, prefix + path + "\\");
+ for (Tree const& folder : folders) {
+ folder.BuildVirtualFolderImpl(virtualFolders, prefix + path + "\\");
}
}
void Tree::BuildUnit(cmXMLWriter& xml, const std::string& fsPath) const
{
- for (std::vector<std::string>::const_iterator it = files.begin();
- it != files.end(); ++it) {
+ for (std::string const& f : files) {
xml.StartElement("Unit");
- xml.Attribute("filename", fsPath + *it);
+ xml.Attribute("filename", fsPath + f);
xml.StartElement("Option");
xml.Attribute("virtualFolder", "CMake Files\\");
@@ -175,9 +170,8 @@ void Tree::BuildUnit(cmXMLWriter& xml, const std::string& fsPath) const
xml.EndElement();
}
- for (std::vector<Tree>::const_iterator it = folders.begin();
- it != folders.end(); ++it) {
- it->BuildUnitImpl(xml, "", fsPath);
+ for (Tree const& folder : folders) {
+ folder.BuildUnitImpl(xml, "", fsPath);
}
}
@@ -185,10 +179,9 @@ void Tree::BuildUnitImpl(cmXMLWriter& xml,
const std::string& virtualFolderPath,
const std::string& fsPath) const
{
- for (std::vector<std::string>::const_iterator it = files.begin();
- it != files.end(); ++it) {
+ for (std::string const& f : files) {
xml.StartElement("Unit");
- xml.Attribute("filename", fsPath + path + "/" + *it);
+ xml.Attribute("filename", fsPath + path + "/" + f);
xml.StartElement("Option");
xml.Attribute("virtualFolder",
@@ -197,10 +190,9 @@ void Tree::BuildUnitImpl(cmXMLWriter& xml,
xml.EndElement();
}
- for (std::vector<Tree>::const_iterator it = folders.begin();
- it != folders.end(); ++it) {
- it->BuildUnitImpl(xml, virtualFolderPath + path + "\\",
- fsPath + path + "/");
+ for (Tree const& folder : folders) {
+ folder.BuildUnitImpl(xml, virtualFolderPath + path + "\\",
+ fsPath + path + "/");
}
}
@@ -216,29 +208,24 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
Tree tree;
// build tree of virtual folders
- for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
- it = this->GlobalGenerator->GetProjectMap().begin();
- it != this->GlobalGenerator->GetProjectMap().end(); ++it) {
+ for (auto const& it : this->GlobalGenerator->GetProjectMap()) {
// Collect all files
std::vector<std::string> listFiles;
- for (std::vector<cmLocalGenerator*>::const_iterator jt =
- it->second.begin();
- jt != it->second.end(); ++jt) {
+ for (cmLocalGenerator* lg : it.second) {
const std::vector<std::string>& files =
- (*jt)->GetMakefile()->GetListFiles();
+ lg->GetMakefile()->GetListFiles();
listFiles.insert(listFiles.end(), files.begin(), files.end());
}
// Convert
- for (std::vector<std::string>::const_iterator jt = listFiles.begin();
- jt != listFiles.end(); ++jt) {
+ for (std::string const& listFile : listFiles) {
// don't put cmake's own files into the project (#12110):
- if (jt->find(cmSystemTools::GetCMakeRoot()) == 0) {
+ if (listFile.find(cmSystemTools::GetCMakeRoot()) == 0) {
continue;
}
const std::string& relative = cmSystemTools::RelativePath(
- it->second[0]->GetSourceDirectory(), jt->c_str());
+ it.second[0]->GetSourceDirectory(), listFile.c_str());
std::vector<std::string> splitted;
cmSystemTools::SplitPath(relative, splitted, false);
// Split filename from path
@@ -248,7 +235,14 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
// We don't want paths with CMakeFiles in them
// or do we?
// In speedcrunch those where purely internal
+ //
+ // Also we can disable external (outside the project) files by setting ON
+ // CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES variable.
+ const bool excludeExternal =
+ cmSystemTools::IsOn(it.second[0]->GetMakefile()->GetSafeDefinition(
+ "CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES"));
if (!splitted.empty() &&
+ (!excludeExternal || (relative.find("..") == std::string::npos)) &&
relative.find("CMakeFiles") == std::string::npos) {
tree.InsertPath(splitted, 1, fileName);
}
@@ -289,24 +283,22 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
xml.StartElement("Build");
- this->AppendTarget(xml, "all", CM_NULLPTR, make.c_str(), lgs[0],
+ this->AppendTarget(xml, "all", nullptr, make.c_str(), lgs[0],
compiler.c_str(), makeArgs);
// add all executable and library targets and some of the GLOBAL
// and UTILITY targets
- for (std::vector<cmLocalGenerator*>::const_iterator lg = lgs.begin();
- lg != lgs.end(); lg++) {
- std::vector<cmGeneratorTarget*> targets = (*lg)->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator ti = targets.begin();
- ti != targets.end(); ti++) {
- std::string targetName = (*ti)->GetName();
- switch ((*ti)->GetType()) {
+ for (cmLocalGenerator* lg : lgs) {
+ const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
+ std::string targetName = target->GetName();
+ switch (target->GetType()) {
case cmStateEnums::GLOBAL_TARGET: {
// Only add the global targets from CMAKE_BINARY_DIR,
// not from the subdirs
- if (strcmp((*lg)->GetCurrentBinaryDirectory(),
- (*lg)->GetBinaryDirectory()) == 0) {
- this->AppendTarget(xml, targetName, CM_NULLPTR, make.c_str(), *lg,
+ if (strcmp(lg->GetCurrentBinaryDirectory(),
+ lg->GetBinaryDirectory()) == 0) {
+ this->AppendTarget(xml, targetName, nullptr, make.c_str(), lg,
compiler.c_str(), makeArgs);
}
} break;
@@ -322,7 +314,7 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
break;
}
- this->AppendTarget(xml, targetName, CM_NULLPTR, make.c_str(), *lg,
+ this->AppendTarget(xml, targetName, nullptr, make.c_str(), lg,
compiler.c_str(), makeArgs);
break;
case cmStateEnums::EXECUTABLE:
@@ -330,12 +322,12 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
case cmStateEnums::SHARED_LIBRARY:
case cmStateEnums::MODULE_LIBRARY:
case cmStateEnums::OBJECT_LIBRARY: {
- cmGeneratorTarget* gt = *ti;
- this->AppendTarget(xml, targetName, gt, make.c_str(), *lg,
+ cmGeneratorTarget* gt = target;
+ this->AppendTarget(xml, targetName, gt, make.c_str(), lg,
compiler.c_str(), makeArgs);
std::string fastTarget = targetName;
fastTarget += "/fast";
- this->AppendTarget(xml, fastTarget, gt, make.c_str(), *lg,
+ this->AppendTarget(xml, fastTarget, gt, make.c_str(), lg,
compiler.c_str(), makeArgs);
} break;
default:
@@ -356,13 +348,11 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
std::vector<std::string> const& srcExts =
this->GlobalGenerator->GetCMakeInstance()->GetSourceExtensions();
- for (std::vector<cmLocalGenerator*>::const_iterator lg = lgs.begin();
- lg != lgs.end(); lg++) {
- cmMakefile* makefile = (*lg)->GetMakefile();
- std::vector<cmGeneratorTarget*> targets = (*lg)->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator ti = targets.begin();
- ti != targets.end(); ti++) {
- switch ((*ti)->GetType()) {
+ for (cmLocalGenerator* lg : lgs) {
+ cmMakefile* makefile = lg->GetMakefile();
+ const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
+ switch (target->GetType()) {
case cmStateEnums::EXECUTABLE:
case cmStateEnums::STATIC_LIBRARY:
case cmStateEnums::SHARED_LIBRARY:
@@ -371,41 +361,51 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
case cmStateEnums::UTILITY: // can have sources since 2.6.3
{
std::vector<cmSourceFile*> sources;
- cmGeneratorTarget* gt = *ti;
+ cmGeneratorTarget* gt = target;
gt->GetSourceFiles(sources,
makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
- for (std::vector<cmSourceFile*>::const_iterator si = sources.begin();
- si != sources.end(); si++) {
+ for (cmSourceFile* s : sources) {
// don't add source files from UTILITY target which have the
// GENERATED property set:
if (gt->GetType() == cmStateEnums::UTILITY &&
- (*si)->GetPropertyAsBool("GENERATED")) {
+ s->GetPropertyAsBool("GENERATED")) {
continue;
}
// check whether it is a C/C++ implementation file
bool isCFile = false;
- std::string lang = (*si)->GetLanguage();
+ std::string lang = s->GetLanguage();
if (lang == "C" || lang == "CXX") {
- std::string const& srcext = (*si)->GetExtension();
- for (std::vector<std::string>::const_iterator ext =
- srcExts.begin();
- ext != srcExts.end(); ++ext) {
- if (srcext == *ext) {
+ std::string const& srcext = s->GetExtension();
+ for (std::string const& ext : srcExts) {
+ if (srcext == ext) {
isCFile = true;
break;
}
}
}
- std::string const& fullPath = (*si)->GetFullPath();
+ std::string const& fullPath = s->GetFullPath();
+
+ // Check file position relative to project root dir.
+ const std::string& relative = cmSystemTools::RelativePath(
+ (*lg).GetSourceDirectory(), fullPath.c_str());
+ // Do not add this file if it has ".." in relative path and
+ // if CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES variable is on.
+ const bool excludeExternal =
+ cmSystemTools::IsOn((*lg).GetMakefile()->GetSafeDefinition(
+ "CMAKE_CODEBLOCKS_EXCLUDE_EXTERNAL_FILES"));
+ if (excludeExternal &&
+ (relative.find("..") != std::string::npos)) {
+ continue;
+ }
if (isCFile) {
cFiles.push_back(fullPath);
}
CbpUnit& cbpUnit = allFiles[fullPath];
- cbpUnit.Targets.push_back(*ti);
+ cbpUnit.Targets.push_back(target);
}
}
default: // intended fallthrough
@@ -424,19 +424,16 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
// file exists. If it does, it is inserted into the map of files.
// A very similar version of that code exists also in the kdevelop
// project generator.
- for (std::vector<std::string>::const_iterator sit = cFiles.begin();
- sit != cFiles.end(); ++sit) {
- std::string const& fileName = *sit;
+ for (std::string const& fileName : cFiles) {
std::string headerBasename = cmSystemTools::GetFilenamePath(fileName);
headerBasename += "/";
headerBasename += cmSystemTools::GetFilenameWithoutExtension(fileName);
// check if there's a matching header around
- for (std::vector<std::string>::const_iterator ext = headerExts.begin();
- ext != headerExts.end(); ++ext) {
+ for (std::string const& ext : headerExts) {
std::string hname = headerBasename;
hname += ".";
- hname += *ext;
+ hname += ext;
// if it's already in the set, don't check if it exists on disk
if (allFiles.find(hname) != allFiles.end()) {
break;
@@ -450,19 +447,16 @@ void cmExtraCodeBlocksGenerator::CreateNewProjectFile(
}
// insert all source files in the CodeBlocks project
- for (all_files_map_t::const_iterator sit = allFiles.begin();
- sit != allFiles.end(); ++sit) {
- std::string const& unitFilename = sit->first;
- CbpUnit const& unit = sit->second;
+ for (auto const& s : allFiles) {
+ std::string const& unitFilename = s.first;
+ CbpUnit const& unit = s.second;
xml.StartElement("Unit");
xml.Attribute("filename", unitFilename);
- for (std::vector<const cmGeneratorTarget*>::const_iterator ti =
- unit.Targets.begin();
- ti != unit.Targets.end(); ++ti) {
+ for (cmGeneratorTarget const* tgt : unit.Targets) {
xml.StartElement("Option");
- xml.Attribute("target", (*ti)->GetName());
+ xml.Attribute("target", tgt->GetName());
xml.EndElement();
}
@@ -515,7 +509,7 @@ void cmExtraCodeBlocksGenerator::AppendTarget(
xml.StartElement("Target");
xml.Attribute("title", targetName);
- if (target != CM_NULLPTR) {
+ if (target != nullptr) {
int cbTargetType = this->GetCBTargetType(target);
std::string workingDir = lg->GetCurrentBinaryDirectory();
if (target->GetType() == cmStateEnums::EXECUTABLE) {
@@ -523,12 +517,12 @@ void cmExtraCodeBlocksGenerator::AppendTarget(
// set the working directory to this dir.
const char* runtimeOutputDir =
makefile->GetDefinition("CMAKE_RUNTIME_OUTPUT_DIRECTORY");
- if (runtimeOutputDir != CM_NULLPTR) {
+ if (runtimeOutputDir != nullptr) {
workingDir = runtimeOutputDir;
} else {
const char* executableOutputDir =
makefile->GetDefinition("EXECUTABLE_OUTPUT_PATH");
- if (executableOutputDir != CM_NULLPTR) {
+ if (executableOutputDir != nullptr) {
workingDir = executableOutputDir;
}
}
@@ -572,10 +566,9 @@ void cmExtraCodeBlocksGenerator::AppendTarget(
target->GetCompileDefinitions(cdefs, buildType, "C");
// Expand the list.
- for (std::vector<std::string>::const_iterator di = cdefs.begin();
- di != cdefs.end(); ++di) {
+ for (std::string const& d : cdefs) {
xml.StartElement("Add");
- xml.Attribute("option", "-D" + *di);
+ xml.Attribute("option", "-D" + d);
xml.EndElement();
}
diff --git a/Source/cmExtraCodeBlocksGenerator.h b/Source/cmExtraCodeBlocksGenerator.h
index 450a9d02c..be3af2562 100644
--- a/Source/cmExtraCodeBlocksGenerator.h
+++ b/Source/cmExtraCodeBlocksGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmExtraCodeBlocksGenerator_h
#define cmExtraCodeBlocksGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmExternalMakefileProjectGenerator.h"
@@ -25,7 +25,7 @@ public:
static cmExternalMakefileProjectGeneratorFactory* GetFactory();
- void Generate() CM_OVERRIDE;
+ void Generate() override;
private:
struct CbpUnit
diff --git a/Source/cmExtraCodeLiteGenerator.cxx b/Source/cmExtraCodeLiteGenerator.cxx
index b478f34fa..5a02d54eb 100644
--- a/Source/cmExtraCodeLiteGenerator.cxx
+++ b/Source/cmExtraCodeLiteGenerator.cxx
@@ -54,26 +54,24 @@ void cmExtraCodeLiteGenerator::Generate()
std::string workspaceFileName;
std::string workspaceSourcePath;
- const std::map<std::string, std::vector<cmLocalGenerator*> >& projectMap =
+ const std::map<std::string, std::vector<cmLocalGenerator*>>& projectMap =
this->GlobalGenerator->GetProjectMap();
// loop projects and locate the root project.
// and extract the information for creating the worspace
// root makefile
- for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
- it = projectMap.begin();
- it != projectMap.end(); ++it) {
- const cmMakefile* mf = it->second[0]->GetMakefile();
+ for (auto const& it : projectMap) {
+ const cmMakefile* mf = it.second[0]->GetMakefile();
this->ConfigName = GetConfigurationName(mf);
- if (strcmp(it->second[0]->GetCurrentBinaryDirectory(),
- it->second[0]->GetBinaryDirectory()) == 0) {
- workspaceOutputDir = it->second[0]->GetCurrentBinaryDirectory();
- workspaceProjectName = it->second[0]->GetProjectName();
- workspaceSourcePath = it->second[0]->GetSourceDirectory();
+ if (strcmp(it.second[0]->GetCurrentBinaryDirectory(),
+ it.second[0]->GetBinaryDirectory()) == 0) {
+ workspaceOutputDir = it.second[0]->GetCurrentBinaryDirectory();
+ workspaceProjectName = it.second[0]->GetProjectName();
+ workspaceSourcePath = it.second[0]->GetSourceDirectory();
workspaceFileName = workspaceOutputDir + "/";
workspaceFileName += workspaceProjectName + ".workspace";
- this->WorkspacePath = it->second[0]->GetCurrentBinaryDirectory();
+ this->WorkspacePath = it.second[0]->GetCurrentBinaryDirectory();
;
break;
}
@@ -101,10 +99,9 @@ void cmExtraCodeLiteGenerator::Generate()
xml.Attribute("Name", this->ConfigName);
xml.Attribute("Selected", "yes");
- for (std::vector<std::string>::iterator it(ProjectNames.begin());
- it != ProjectNames.end(); it++) {
+ for (std::string const& it : ProjectNames) {
xml.StartElement("Project");
- xml.Attribute("Name", *it);
+ xml.Attribute("Name", it);
xml.Attribute("ConfigName", this->ConfigName);
xml.EndElement();
}
@@ -122,14 +119,11 @@ std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByTarget(
// for each target in the workspace create a codelite project
const std::vector<cmLocalGenerator*>& lgs =
this->GlobalGenerator->GetLocalGenerators();
- for (std::vector<cmLocalGenerator*>::const_iterator lg(lgs.begin());
- lg != lgs.end(); lg++) {
- for (std::vector<cmGeneratorTarget*>::const_iterator lt =
- (*lg)->GetGeneratorTargets().begin();
- lt != (*lg)->GetGeneratorTargets().end(); lt++) {
- cmStateEnums::TargetType type = (*lt)->GetType();
- std::string outputDir = (*lg)->GetCurrentBinaryDirectory();
- std::string targetName = (*lt)->GetName();
+ for (cmLocalGenerator* lg : lgs) {
+ for (cmGeneratorTarget* lt : lg->GetGeneratorTargets()) {
+ cmStateEnums::TargetType type = lt->GetType();
+ std::string outputDir = lg->GetCurrentBinaryDirectory();
+ std::string targetName = lt->GetName();
std::string filename = outputDir + "/" + targetName + ".project";
retval.push_back(targetName);
// Make the project file relative to the workspace
@@ -149,7 +143,7 @@ std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByTarget(
xml->Attribute("Active", "No");
xml->EndElement();
- CreateNewProjectFile(*lt, filename);
+ CreateNewProjectFile(lt, filename);
break;
default:
break;
@@ -165,12 +159,10 @@ std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByProjectMaps(
{
std::vector<std::string> retval;
// for each sub project in the workspace create a codelite project
- for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
- it = this->GlobalGenerator->GetProjectMap().begin();
- it != this->GlobalGenerator->GetProjectMap().end(); it++) {
+ for (auto const& it : this->GlobalGenerator->GetProjectMap()) {
- std::string outputDir = it->second[0]->GetCurrentBinaryDirectory();
- std::string projectName = it->second[0]->GetProjectName();
+ std::string outputDir = it.second[0]->GetCurrentBinaryDirectory();
+ std::string projectName = it.second[0]->GetProjectName();
retval.push_back(projectName);
std::string filename = outputDir + "/" + projectName + ".project";
@@ -179,7 +171,7 @@ std::vector<std::string> cmExtraCodeLiteGenerator::CreateProjectsByProjectMaps(
filename.c_str());
// create a project file
- this->CreateProjectFile(it->second);
+ this->CreateProjectFile(it.second);
xml->StartElement("Project");
xml->Attribute("Name", projectName);
xml->Attribute("Path", filename);
@@ -235,16 +227,14 @@ std::string cmExtraCodeLiteGenerator::CollectSourceFiles(
std::vector<cmSourceFile*> sources;
gt->GetSourceFiles(sources,
makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
- for (std::vector<cmSourceFile*>::const_iterator si = sources.begin();
- si != sources.end(); si++) {
+ for (cmSourceFile* s : sources) {
// check whether it is a C/C++ implementation file
bool isCFile = false;
- std::string lang = (*si)->GetLanguage();
+ std::string lang = s->GetLanguage();
if (lang == "C" || lang == "CXX") {
- std::string const& srcext = (*si)->GetExtension();
- for (std::vector<std::string>::const_iterator ext = srcExts.begin();
- ext != srcExts.end(); ++ext) {
- if (srcext == *ext) {
+ std::string const& srcext = s->GetExtension();
+ for (std::string const& ext : srcExts) {
+ if (srcext == ext) {
isCFile = true;
break;
}
@@ -253,9 +243,9 @@ std::string cmExtraCodeLiteGenerator::CollectSourceFiles(
// then put it accordingly into one of the two containers
if (isCFile) {
- cFiles[(*si)->GetFullPath()] = *si;
+ cFiles[s->GetFullPath()] = s;
} else {
- otherFiles.insert((*si)->GetFullPath());
+ otherFiles.insert(s->GetFullPath());
}
}
}
@@ -289,13 +279,11 @@ void cmExtraCodeLiteGenerator::CreateNewProjectFile(
std::map<std::string, cmSourceFile*> cFiles;
std::set<std::string> otherFiles;
- for (std::vector<cmLocalGenerator*>::const_iterator lg = lgs.begin();
- lg != lgs.end(); lg++) {
- cmMakefile* makefile = (*lg)->GetMakefile();
- std::vector<cmGeneratorTarget*> targets = (*lg)->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator ti = targets.begin();
- ti != targets.end(); ti++) {
- projectType = CollectSourceFiles(makefile, *ti, cFiles, otherFiles);
+ for (cmLocalGenerator* lg : lgs) {
+ cmMakefile* makefile = lg->GetMakefile();
+ const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
+ projectType = CollectSourceFiles(makefile, target, cFiles, otherFiles);
}
}
@@ -323,19 +311,16 @@ void cmExtraCodeLiteGenerator::FindMatchingHeaderfiles(
// file exists. If it does, it is inserted into the map of files.
// A very similar version of that code exists also in the kdevelop
// project generator.
- for (std::map<std::string, cmSourceFile*>::const_iterator sit =
- cFiles.begin();
- sit != cFiles.end(); ++sit) {
- std::string headerBasename = cmSystemTools::GetFilenamePath(sit->first);
+ for (auto const& sit : cFiles) {
+ std::string headerBasename = cmSystemTools::GetFilenamePath(sit.first);
headerBasename += "/";
- headerBasename += cmSystemTools::GetFilenameWithoutExtension(sit->first);
+ headerBasename += cmSystemTools::GetFilenameWithoutExtension(sit.first);
// check if there's a matching header around
- for (std::vector<std::string>::const_iterator ext = headerExts.begin();
- ext != headerExts.end(); ++ext) {
+ for (std::string const& ext : headerExts) {
std::string hname = headerBasename;
hname += ".";
- hname += *ext;
+ hname += ext;
// if it's already in the set, don't check if it exists on disk
std::set<std::string>::const_iterator headerIt = otherFiles.find(hname);
if (headerIt != otherFiles.end()) {
@@ -358,10 +343,9 @@ void cmExtraCodeLiteGenerator::CreateFoldersAndFiles(
std::vector<std::string> components;
size_t numOfEndEl = 0;
- for (std::set<std::string>::const_iterator it = cFiles.begin();
- it != cFiles.end(); ++it) {
+ for (std::string const& cFile : cFiles) {
std::string frelapath =
- cmSystemTools::RelativePath(projectPath.c_str(), it->c_str());
+ cmSystemTools::RelativePath(projectPath.c_str(), cFile.c_str());
cmsys::SystemTools::SplitPath(frelapath, components, false);
components.pop_back(); // erase last member -> it is file, not folder
components.erase(components.begin()); // erase "root"
@@ -423,10 +407,8 @@ void cmExtraCodeLiteGenerator::CreateFoldersAndFiles(
const std::string& projectPath)
{
std::set<std::string> s;
- for (std::map<std::string, cmSourceFile*>::const_iterator it =
- cFiles.begin();
- it != cFiles.end(); ++it) {
- s.insert(it->first);
+ for (auto const& it : cFiles) {
+ s.insert(it.first);
}
this->CreateFoldersAndFiles(s, xml, projectPath);
}
diff --git a/Source/cmExtraCodeLiteGenerator.h b/Source/cmExtraCodeLiteGenerator.h
index de330988d..029054fdd 100644
--- a/Source/cmExtraCodeLiteGenerator.h
+++ b/Source/cmExtraCodeLiteGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmGlobalCodeLiteGenerator_h
#define cmGlobalCodeLiteGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmExternalMakefileProjectGenerator.h"
@@ -60,7 +60,7 @@ public:
static cmExternalMakefileProjectGeneratorFactory* GetFactory();
- void Generate() CM_OVERRIDE;
+ void Generate() override;
void CreateProjectFile(const std::vector<cmLocalGenerator*>& lgs);
void CreateNewProjectFile(const std::vector<cmLocalGenerator*>& lgs,
diff --git a/Source/cmExtraEclipseCDT4Generator.cxx b/Source/cmExtraEclipseCDT4Generator.cxx
index 2a6ce98a7..a200385ee 100644
--- a/Source/cmExtraEclipseCDT4Generator.cxx
+++ b/Source/cmExtraEclipseCDT4Generator.cxx
@@ -5,7 +5,6 @@
#include "cmsys/RegularExpression.hxx"
#include <algorithm>
#include <assert.h>
-#include <map>
#include <sstream>
#include <stdio.h>
#include <utility>
@@ -78,16 +77,15 @@ void cmExtraEclipseCDT4Generator::EnableLanguage(
std::vector<std::string> const& languages, cmMakefile* /*unused*/,
bool /*optional*/)
{
- for (std::vector<std::string>::const_iterator lit = languages.begin();
- lit != languages.end(); ++lit) {
- if (*lit == "CXX") {
+ for (std::string const& l : languages) {
+ if (l == "CXX") {
this->Natures.insert("org.eclipse.cdt.core.ccnature");
this->Natures.insert("org.eclipse.cdt.core.cnature");
this->CXXEnabled = true;
- } else if (*lit == "C") {
+ } else if (l == "C") {
this->Natures.insert("org.eclipse.cdt.core.cnature");
this->CEnabled = true;
- } else if (*lit == "Java") {
+ } else if (l == "Java") {
this->Natures.insert("org.eclipse.jdt.core.javanature");
}
}
@@ -222,17 +220,17 @@ void cmExtraEclipseCDT4Generator::AddEnvVar(std::ostream& out,
// now we have both, decide which one to use
std::string valueToUse;
- if (!envVarSet && cacheValue == CM_NULLPTR) {
+ if (!envVarSet && cacheValue == nullptr) {
// nothing known, do nothing
- valueToUse = "";
- } else if (envVarSet && cacheValue == CM_NULLPTR) {
+ valueToUse.clear();
+ } else if (envVarSet && cacheValue == nullptr) {
// The variable is in the env, but not in the cache. Use it and put it
// in the cache
valueToUse = envVarValue;
mf->AddCacheDefinition(cacheEntryName, valueToUse.c_str(),
cacheEntryName.c_str(), cmStateEnums::STRING, true);
mf->GetCMakeInstance()->SaveCache(lg->GetBinaryDirectory());
- } else if (!envVarSet && cacheValue != CM_NULLPTR) {
+ } else if (!envVarSet && cacheValue != nullptr) {
// It is already in the cache, but not in the env, so use it from the cache
valueToUse = cacheValue;
} else {
@@ -382,18 +380,16 @@ void cmExtraEclipseCDT4Generator::CreateProjectFile()
xml.Element("nature", "org.eclipse.cdt.make.core.ScannerConfigNature");
;
- for (std::set<std::string>::const_iterator nit = this->Natures.begin();
- nit != this->Natures.end(); ++nit) {
- xml.Element("nature", *nit);
+ for (std::string const& n : this->Natures) {
+ xml.Element("nature", n);
}
if (const char* extraNaturesProp =
mf->GetState()->GetGlobalProperty("ECLIPSE_EXTRA_NATURES")) {
std::vector<std::string> extraNatures;
cmSystemTools::ExpandListArgument(extraNaturesProp, extraNatures);
- for (std::vector<std::string>::const_iterator nit = extraNatures.begin();
- nit != extraNatures.end(); ++nit) {
- xml.Element("nature", *nit);
+ for (std::string const& n : extraNatures) {
+ xml.Element("nature", n);
}
}
@@ -435,25 +431,22 @@ void cmExtraEclipseCDT4Generator::WriteGroups(
std::vector<cmSourceGroup> const& sourceGroups, std::string& linkName,
cmXMLWriter& xml)
{
- for (std::vector<cmSourceGroup>::const_iterator sgIt = sourceGroups.begin();
- sgIt != sourceGroups.end(); ++sgIt) {
+ for (cmSourceGroup const& sg : sourceGroups) {
std::string linkName3 = linkName;
linkName3 += "/";
- linkName3 += sgIt->GetFullName();
+ linkName3 += sg.GetFullName();
std::replace(linkName3.begin(), linkName3.end(), '\\', '/');
this->AppendLinkedResource(xml, linkName3, "virtual:/virtual",
VirtualFolder);
- std::vector<cmSourceGroup> const& children = sgIt->GetGroupChildren();
+ std::vector<cmSourceGroup> const& children = sg.GetGroupChildren();
if (!children.empty()) {
this->WriteGroups(children, linkName, xml);
}
- std::vector<const cmSourceFile*> sFiles = sgIt->GetSourceFiles();
- for (std::vector<const cmSourceFile*>::const_iterator fileIt =
- sFiles.begin();
- fileIt != sFiles.end(); ++fileIt) {
- std::string const& fullPath = (*fileIt)->GetFullPath();
+ std::vector<const cmSourceFile*> sFiles = sg.GetSourceFiles();
+ for (cmSourceFile const* file : sFiles) {
+ std::string const& fullPath = file->GetFullPath();
if (!cmSystemTools::FileIsDirectory(fullPath)) {
std::string linkName4 = linkName3;
@@ -471,28 +464,24 @@ void cmExtraEclipseCDT4Generator::CreateLinksForTargets(cmXMLWriter& xml)
std::string linkName = "[Targets]";
this->AppendLinkedResource(xml, linkName, "virtual:/virtual", VirtualFolder);
- for (std::vector<cmLocalGenerator*>::const_iterator lgIt =
- this->GlobalGenerator->GetLocalGenerators().begin();
- lgIt != this->GlobalGenerator->GetLocalGenerators().end(); ++lgIt) {
- cmMakefile* makefile = (*lgIt)->GetMakefile();
- const std::vector<cmGeneratorTarget*> targets =
- (*lgIt)->GetGeneratorTargets();
+ for (cmLocalGenerator* lg : this->GlobalGenerator->GetLocalGenerators()) {
+ cmMakefile* makefile = lg->GetMakefile();
+ const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin();
- ti != targets.end(); ++ti) {
+ for (cmGeneratorTarget* target : targets) {
std::string linkName2 = linkName;
linkName2 += "/";
- switch ((*ti)->GetType()) {
+ switch (target->GetType()) {
case cmStateEnums::EXECUTABLE:
case cmStateEnums::STATIC_LIBRARY:
case cmStateEnums::SHARED_LIBRARY:
case cmStateEnums::MODULE_LIBRARY:
case cmStateEnums::OBJECT_LIBRARY: {
const char* prefix =
- ((*ti)->GetType() == cmStateEnums::EXECUTABLE ? "[exe] "
- : "[lib] ");
+ (target->GetType() == cmStateEnums::EXECUTABLE ? "[exe] "
+ : "[lib] ");
linkName2 += prefix;
- linkName2 += (*ti)->GetName();
+ linkName2 += target->GetName();
this->AppendLinkedResource(xml, linkName2, "virtual:/virtual",
VirtualFolder);
if (!this->GenerateLinkedResources) {
@@ -501,17 +490,16 @@ void cmExtraEclipseCDT4Generator::CreateLinksForTargets(cmXMLWriter& xml)
std::vector<cmSourceGroup> sourceGroups =
makefile->GetSourceGroups();
// get the files from the source lists then add them to the groups
- cmGeneratorTarget* gt = const_cast<cmGeneratorTarget*>(*ti);
+ cmGeneratorTarget* gt = const_cast<cmGeneratorTarget*>(target);
std::vector<cmSourceFile*> files;
gt->GetSourceFiles(files,
makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
- for (std::vector<cmSourceFile*>::const_iterator sfIt = files.begin();
- sfIt != files.end(); sfIt++) {
+ for (cmSourceFile* sf : files) {
// Add the file to the list of sources.
- std::string const& source = (*sfIt)->GetFullPath();
+ std::string const& source = sf->GetFullPath();
cmSourceGroup* sourceGroup =
makefile->FindSourceGroup(source.c_str(), sourceGroups);
- sourceGroup->AssignSource(*sfIt);
+ sourceGroup->AssignSource(sf);
}
this->WriteGroups(sourceGroups, linkName2, xml);
@@ -536,17 +524,15 @@ void cmExtraEclipseCDT4Generator::CreateLinksToSubprojects(
this->AppendLinkedResource(xml, "[Subprojects]", "virtual:/virtual",
VirtualFolder);
- for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
- it = this->GlobalGenerator->GetProjectMap().begin();
- it != this->GlobalGenerator->GetProjectMap().end(); ++it) {
+ for (auto const& it : this->GlobalGenerator->GetProjectMap()) {
std::string linkSourceDirectory =
- this->GetEclipsePath(it->second[0]->GetCurrentSourceDirectory());
+ this->GetEclipsePath(it.second[0]->GetCurrentSourceDirectory());
// a linked resource must not point to a parent directory of .project or
// .project itself
if ((baseDir != linkSourceDirectory) &&
!cmSystemTools::IsSubDirectory(baseDir, linkSourceDirectory)) {
std::string linkName = "[Subprojects]/";
- linkName += it->first;
+ linkName += it.first;
this->AppendLinkedResource(xml, linkName,
this->GetEclipsePath(linkSourceDirectory),
LinkToFolder);
@@ -560,10 +546,9 @@ void cmExtraEclipseCDT4Generator::AppendIncludeDirectories(
cmXMLWriter& xml, const std::vector<std::string>& includeDirs,
std::set<std::string>& emittedDirs)
{
- for (std::vector<std::string>::const_iterator inc = includeDirs.begin();
- inc != includeDirs.end(); ++inc) {
- if (!inc->empty()) {
- std::string dir = cmSystemTools::CollapseFullPath(*inc);
+ for (std::string const& inc : includeDirs) {
+ if (!inc.empty()) {
+ std::string dir = cmSystemTools::CollapseFullPath(inc);
// handle framework include dirs on OSX, the remainder after the
// Frameworks/ part has to be stripped
@@ -712,19 +697,17 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
xml.EndElement();
}
- for (std::vector<std::string>::const_iterator it =
- this->SrcLinkedResources.begin();
- it != this->SrcLinkedResources.end(); ++it) {
+ for (std::string const& p : this->SrcLinkedResources) {
xml.StartElement("pathentry");
xml.Attribute("kind", "src");
- xml.Attribute("path", *it);
+ xml.Attribute("path", p);
xml.EndElement();
// exlude source directory from output search path
// - only if not named the same as an output directory
if (!cmSystemTools::FileIsDirectory(
- std::string(this->HomeOutputDirectory + "/" + *it))) {
- excludeFromOut += *it + "/|";
+ std::string(this->HomeOutputDirectory + "/" + p))) {
+ excludeFromOut += p + "/|";
}
}
@@ -738,34 +721,31 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
// add pre-processor definitions to allow eclipse to gray out sections
emmited.clear();
- for (std::vector<cmLocalGenerator*>::const_iterator it =
- this->GlobalGenerator->GetLocalGenerators().begin();
- it != this->GlobalGenerator->GetLocalGenerators().end(); ++it) {
+ for (cmLocalGenerator* lgen : this->GlobalGenerator->GetLocalGenerators()) {
if (const char* cdefs =
- (*it)->GetMakefile()->GetProperty("COMPILE_DEFINITIONS")) {
+ lgen->GetMakefile()->GetProperty("COMPILE_DEFINITIONS")) {
// Expand the list.
std::vector<std::string> defs;
cmGeneratorExpression::Split(cdefs, defs);
- for (std::vector<std::string>::const_iterator di = defs.begin();
- di != defs.end(); ++di) {
- if (cmGeneratorExpression::Find(*di) != std::string::npos) {
+ for (std::string const& d : defs) {
+ if (cmGeneratorExpression::Find(d) != std::string::npos) {
continue;
}
- std::string::size_type equals = di->find('=', 0);
- std::string::size_type enddef = di->length();
+ std::string::size_type equals = d.find('=', 0);
+ std::string::size_type enddef = d.length();
std::string def;
std::string val;
if (equals != std::string::npos && equals < enddef) {
// we have -DFOO=BAR
- def = di->substr(0, equals);
- val = di->substr(equals + 1, enddef - equals + 1);
+ def = d.substr(0, equals);
+ val = d.substr(equals + 1, enddef - equals + 1);
} else {
// we have -DFOO
- def = *di;
+ def = d;
}
// insert the definition if not already added.
@@ -850,15 +830,13 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
// include dirs
emmited.clear();
- for (std::vector<cmLocalGenerator*>::const_iterator it =
- this->GlobalGenerator->GetLocalGenerators().begin();
- it != this->GlobalGenerator->GetLocalGenerators().end(); ++it) {
- std::vector<cmGeneratorTarget*> targets = (*it)->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator l = targets.begin();
- l != targets.end(); ++l) {
+ for (cmLocalGenerator* lgen : this->GlobalGenerator->GetLocalGenerators()) {
+ const std::vector<cmGeneratorTarget*>& targets =
+ lgen->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
std::vector<std::string> includeDirs;
std::string config = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
- (*it)->GetIncludeDirectories(includeDirs, *l, "C", config);
+ lgen->GetIncludeDirectories(includeDirs, target, "C", config);
this->AppendIncludeDirectories(xml, includeDirs, emmited);
}
}
@@ -907,21 +885,18 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
// add all executable and library targets and some of the GLOBAL
// and UTILITY targets
- for (std::vector<cmLocalGenerator*>::const_iterator it =
- this->GlobalGenerator->GetLocalGenerators().begin();
- it != this->GlobalGenerator->GetLocalGenerators().end(); ++it) {
- const std::vector<cmGeneratorTarget*> targets =
- (*it)->GetGeneratorTargets();
- std::string subdir = (*it)->ConvertToRelativePath(
- this->HomeOutputDirectory, (*it)->GetCurrentBinaryDirectory());
+ for (cmLocalGenerator* lgen : this->GlobalGenerator->GetLocalGenerators()) {
+ const std::vector<cmGeneratorTarget*>& targets =
+ lgen->GetGeneratorTargets();
+ std::string subdir = lgen->ConvertToRelativePath(
+ this->HomeOutputDirectory, lgen->GetCurrentBinaryDirectory());
if (subdir == ".") {
- subdir = "";
+ subdir.clear();
}
- for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin();
- ti != targets.end(); ++ti) {
- std::string targetName = (*ti)->GetName();
- switch ((*ti)->GetType()) {
+ for (cmGeneratorTarget* target : targets) {
+ std::string targetName = target->GetName();
+ switch (target->GetType()) {
case cmStateEnums::GLOBAL_TARGET: {
// Only add the global targets from CMAKE_BINARY_DIR,
// not from the subdirs
@@ -949,8 +924,8 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
case cmStateEnums::MODULE_LIBRARY:
case cmStateEnums::OBJECT_LIBRARY: {
const char* prefix =
- ((*ti)->GetType() == cmStateEnums::EXECUTABLE ? "[exe] "
- : "[lib] ");
+ (target->GetType() == cmStateEnums::EXECUTABLE ? "[exe] "
+ : "[lib] ");
this->AppendTarget(xml, targetName, make, makeArgs, subdir, prefix);
std::string fastTarget = targetName;
fastTarget += "/fast";
@@ -962,19 +937,19 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
virtDir += prefix;
virtDir += targetName;
std::string buildArgs = "-C \"";
- buildArgs += (*it)->GetBinaryDirectory();
+ buildArgs += lgen->GetBinaryDirectory();
buildArgs += "\" ";
buildArgs += makeArgs;
this->AppendTarget(xml, "Build", make, buildArgs, virtDir, "",
targetName.c_str());
std::string cleanArgs = "-E chdir \"";
- cleanArgs += (*it)->GetCurrentBinaryDirectory();
+ cleanArgs += lgen->GetCurrentBinaryDirectory();
cleanArgs += "\" \"";
cleanArgs += cmSystemTools::GetCMakeCommand();
cleanArgs += "\" -P \"";
- cmGeneratorTarget* gt = *ti;
- cleanArgs += (*it)->GetTargetDirectory(gt);
+ cmGeneratorTarget* gt = target;
+ cleanArgs += lgen->GetTargetDirectory(gt);
cleanArgs += "/cmake_clean.cmake\"";
this->AppendTarget(xml, "Clean", cmSystemTools::GetCMakeCommand(),
cleanArgs, virtDir, "", "");
@@ -996,17 +971,15 @@ void cmExtraEclipseCDT4Generator::CreateCProjectFile() const
// insert rules for compiling, preprocessing and assembling individual
// files
std::vector<std::string> objectFileTargets;
- (*it)->GetIndividualFileTargets(objectFileTargets);
- for (std::vector<std::string>::const_iterator fit =
- objectFileTargets.begin();
- fit != objectFileTargets.end(); ++fit) {
+ lg->GetIndividualFileTargets(objectFileTargets);
+ for (std::string const& f : objectFileTargets) {
const char* prefix = "[obj] ";
- if ((*fit)[fit->length() - 1] == 's') {
+ if (f[f.length() - 1] == 's') {
prefix = "[to asm] ";
- } else if ((*fit)[fit->length() - 1] == 'i') {
+ } else if (f[f.length() - 1] == 'i') {
prefix = "[pre] ";
}
- this->AppendTarget(xml, *fit, make, makeArgs, subdir, prefix);
+ this->AppendTarget(xml, f, make, makeArgs, subdir, prefix);
}
}
diff --git a/Source/cmExtraEclipseCDT4Generator.h b/Source/cmExtraEclipseCDT4Generator.h
index 1380d1867..5136660fa 100644
--- a/Source/cmExtraEclipseCDT4Generator.h
+++ b/Source/cmExtraEclipseCDT4Generator.h
@@ -3,7 +3,7 @@
#ifndef cmExtraEclipseCDT4Generator_h
#define cmExtraEclipseCDT4Generator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmExternalMakefileProjectGenerator.h"
@@ -35,9 +35,9 @@ public:
static cmExternalMakefileProjectGeneratorFactory* GetFactory();
void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*,
- bool optional) CM_OVERRIDE;
+ bool optional) override;
- void Generate() CM_OVERRIDE;
+ void Generate() override;
private:
// create .project file in the source tree
@@ -67,7 +67,7 @@ private:
const std::string& make,
const std::string& makeArguments,
const std::string& path, const char* prefix = "",
- const char* makeTarget = CM_NULLPTR);
+ const char* makeTarget = nullptr);
static void AppendScannerProfile(
cmXMLWriter& xml, const std::string& profileID, bool openActionEnabled,
const std::string& openActionFilePath, bool pParserEnabled,
diff --git a/Source/cmExtraKateGenerator.cxx b/Source/cmExtraKateGenerator.cxx
index 373043309..79cc6ef52 100644
--- a/Source/cmExtraKateGenerator.cxx
+++ b/Source/cmExtraKateGenerator.cxx
@@ -112,18 +112,16 @@ void cmExtraKateGenerator::WriteTargets(const cmLocalGenerator* lg,
// add all executable and library targets and some of the GLOBAL
// and UTILITY targets
- for (std::vector<cmLocalGenerator*>::const_iterator it =
- this->GlobalGenerator->GetLocalGenerators().begin();
- it != this->GlobalGenerator->GetLocalGenerators().end(); ++it) {
- const std::vector<cmGeneratorTarget*> targets =
- (*it)->GetGeneratorTargets();
- std::string currentDir = (*it)->GetCurrentBinaryDirectory();
- bool topLevel = (currentDir == (*it)->GetBinaryDirectory());
-
- for (std::vector<cmGeneratorTarget*>::const_iterator ti = targets.begin();
- ti != targets.end(); ++ti) {
- std::string targetName = (*ti)->GetName();
- switch ((*ti)->GetType()) {
+ for (cmLocalGenerator* localGen :
+ this->GlobalGenerator->GetLocalGenerators()) {
+ const std::vector<cmGeneratorTarget*>& targets =
+ localGen->GetGeneratorTargets();
+ std::string currentDir = localGen->GetCurrentBinaryDirectory();
+ bool topLevel = (currentDir == localGen->GetBinaryDirectory());
+
+ for (cmGeneratorTarget* target : targets) {
+ std::string const& targetName = target->GetName();
+ switch (target->GetType()) {
case cmStateEnums::GLOBAL_TARGET: {
bool insertTarget = false;
// Only add the global targets from CMAKE_BINARY_DIR,
@@ -134,10 +132,10 @@ void cmExtraKateGenerator::WriteTargets(const cmLocalGenerator* lg,
// this will not work within the IDE
if (targetName == "edit_cache") {
const char* editCommand =
- (*it)->GetMakefile()->GetDefinition("CMAKE_EDIT_COMMAND");
- if (editCommand == CM_NULLPTR) {
+ localGen->GetMakefile()->GetDefinition("CMAKE_EDIT_COMMAND");
+ if (editCommand == nullptr) {
insertTarget = false;
- } else if (strstr(editCommand, "ccmake") != CM_NULLPTR) {
+ } else if (strstr(editCommand, "ccmake") != nullptr) {
insertTarget = false;
}
}
@@ -183,12 +181,9 @@ void cmExtraKateGenerator::WriteTargets(const cmLocalGenerator* lg,
// insert rules for compiling, preprocessing and assembling individual
// files
std::vector<std::string> objectFileTargets;
- (*it)->GetIndividualFileTargets(objectFileTargets);
- for (std::vector<std::string>::const_iterator fit =
- objectFileTargets.begin();
- fit != objectFileTargets.end(); ++fit) {
- this->AppendTarget(fout, *fit, make, makeArgs, currentDir,
- homeOutputDir);
+ localGen->GetIndividualFileTargets(objectFileTargets);
+ for (std::string const& f : objectFileTargets) {
+ this->AppendTarget(fout, f, make, makeArgs, currentDir, homeOutputDir);
}
}
@@ -251,22 +246,18 @@ std::string cmExtraKateGenerator::GenerateFilesString(
const std::vector<cmLocalGenerator*>& lgs =
this->GlobalGenerator->GetLocalGenerators();
- for (std::vector<cmLocalGenerator*>::const_iterator it = lgs.begin();
- it != lgs.end(); it++) {
- cmMakefile* makefile = (*it)->GetMakefile();
+ for (cmLocalGenerator* lgen : lgs) {
+ cmMakefile* makefile = lgen->GetMakefile();
const std::vector<std::string>& listFiles = makefile->GetListFiles();
- for (std::vector<std::string>::const_iterator lt = listFiles.begin();
- lt != listFiles.end(); lt++) {
- tmp = *lt;
+ for (std::string const& listFile : listFiles) {
+ tmp = listFile;
{
files.insert(tmp);
}
}
const std::vector<cmSourceFile*>& sources = makefile->GetSourceFiles();
- for (std::vector<cmSourceFile*>::const_iterator sfIt = sources.begin();
- sfIt != sources.end(); sfIt++) {
- cmSourceFile* sf = *sfIt;
+ for (cmSourceFile* sf : sources) {
if (sf->GetPropertyAsBool("GENERATED")) {
continue;
}
@@ -278,11 +269,10 @@ std::string cmExtraKateGenerator::GenerateFilesString(
const char* sep = "";
tmp = "\"list\": [";
- for (std::set<std::string>::const_iterator it = files.begin();
- it != files.end(); ++it) {
+ for (std::string const& f : files) {
tmp += sep;
tmp += " \"";
- tmp += *it;
+ tmp += f;
tmp += "\"";
sep = ",";
}
diff --git a/Source/cmExtraKateGenerator.h b/Source/cmExtraKateGenerator.h
index 6b9c7af5c..9716fe750 100644
--- a/Source/cmExtraKateGenerator.h
+++ b/Source/cmExtraKateGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmExtraKateGenerator_h
#define cmExtraKateGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmExternalMakefileProjectGenerator.h"
@@ -22,7 +22,7 @@ public:
static cmExternalMakefileProjectGeneratorFactory* GetFactory();
- void Generate() CM_OVERRIDE;
+ void Generate() override;
private:
void CreateKateProjectFile(const cmLocalGenerator* lg) const;
diff --git a/Source/cmExtraSublimeTextGenerator.cxx b/Source/cmExtraSublimeTextGenerator.cxx
index 1fd1418de..73a9c8521 100644
--- a/Source/cmExtraSublimeTextGenerator.cxx
+++ b/Source/cmExtraSublimeTextGenerator.cxx
@@ -68,11 +68,9 @@ void cmExtraSublimeTextGenerator::Generate()
"CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS");
// for each sub project in the project create a sublime text 2 project
- for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
- it = this->GlobalGenerator->GetProjectMap().begin();
- it != this->GlobalGenerator->GetProjectMap().end(); ++it) {
+ for (auto const& it : this->GlobalGenerator->GetProjectMap()) {
// create a project file
- this->CreateProjectFile(it->second);
+ this->CreateProjectFile(it.second);
}
}
@@ -144,20 +142,19 @@ void cmExtraSublimeTextGenerator::CreateNewProjectFile(
fout << "\n\t{";
fout << "\n\t\t" << systemName << ":";
fout << "\n\t\t{";
- for (std::vector<std::string>::iterator i = tokens.begin();
- i != tokens.end(); ++i) {
- size_t const pos = i->find_first_of('=');
+ for (std::string const& t : tokens) {
+ size_t const pos = t.find_first_of('=');
if (pos != std::string::npos) {
- std::string varName = i->substr(0, pos);
- std::string varValue = i->substr(pos + 1);
+ std::string varName = t.substr(0, pos);
+ std::string varValue = t.substr(pos + 1);
fout << "\n\t\t\t\"" << varName << "\":\"" << varValue << "\"";
} else {
std::ostringstream e;
e << "Could not parse Env Vars specified in "
"\"CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS\""
- << ", corrupted string " << *i;
+ << ", corrupted string " << t;
mf->IssueMessage(cmake::FATAL_ERROR, e.str());
}
}
@@ -174,28 +171,26 @@ void cmExtraSublimeTextGenerator::AppendAllTargets(
std::string make = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
std::string compiler;
if (!lgs.empty()) {
- this->AppendTarget(fout, "all", lgs[0], CM_NULLPTR, make.c_str(), mf,
+ this->AppendTarget(fout, "all", lgs[0], nullptr, make.c_str(), mf,
compiler.c_str(), sourceFileFlags, true);
- this->AppendTarget(fout, "clean", lgs[0], CM_NULLPTR, make.c_str(), mf,
+ this->AppendTarget(fout, "clean", lgs[0], nullptr, make.c_str(), mf,
compiler.c_str(), sourceFileFlags, false);
}
// add all executable and library targets and some of the GLOBAL
// and UTILITY targets
- for (std::vector<cmLocalGenerator*>::const_iterator lg = lgs.begin();
- lg != lgs.end(); lg++) {
- cmMakefile* makefile = (*lg)->GetMakefile();
- std::vector<cmGeneratorTarget*> targets = (*lg)->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator ti = targets.begin();
- ti != targets.end(); ti++) {
- std::string targetName = (*ti)->GetName();
- switch ((*ti)->GetType()) {
+ for (cmLocalGenerator* lg : lgs) {
+ cmMakefile* makefile = lg->GetMakefile();
+ const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
+ std::string targetName = target->GetName();
+ switch (target->GetType()) {
case cmStateEnums::GLOBAL_TARGET: {
// Only add the global targets from CMAKE_BINARY_DIR,
// not from the subdirs
- if (strcmp((*lg)->GetCurrentBinaryDirectory(),
- (*lg)->GetBinaryDirectory()) == 0) {
- this->AppendTarget(fout, targetName, *lg, CM_NULLPTR, make.c_str(),
+ if (strcmp(lg->GetCurrentBinaryDirectory(),
+ lg->GetBinaryDirectory()) == 0) {
+ this->AppendTarget(fout, targetName, lg, nullptr, make.c_str(),
makefile, compiler.c_str(), sourceFileFlags,
false);
}
@@ -212,7 +207,7 @@ void cmExtraSublimeTextGenerator::AppendAllTargets(
break;
}
- this->AppendTarget(fout, targetName, *lg, CM_NULLPTR, make.c_str(),
+ this->AppendTarget(fout, targetName, lg, nullptr, make.c_str(),
makefile, compiler.c_str(), sourceFileFlags,
false);
break;
@@ -221,12 +216,12 @@ void cmExtraSublimeTextGenerator::AppendAllTargets(
case cmStateEnums::SHARED_LIBRARY:
case cmStateEnums::MODULE_LIBRARY:
case cmStateEnums::OBJECT_LIBRARY: {
- this->AppendTarget(fout, targetName, *lg, *ti, make.c_str(),
+ this->AppendTarget(fout, targetName, lg, target, make.c_str(),
makefile, compiler.c_str(), sourceFileFlags,
false);
std::string fastTarget = targetName;
fastTarget += "/fast";
- this->AppendTarget(fout, fastTarget, *lg, *ti, make.c_str(),
+ this->AppendTarget(fout, fastTarget, lg, target, make.c_str(),
makefile, compiler.c_str(), sourceFileFlags,
false);
} break;
@@ -244,15 +239,11 @@ void cmExtraSublimeTextGenerator::AppendTarget(
MapSourceFileFlags& sourceFileFlags, bool firstTarget)
{
- if (target != CM_NULLPTR) {
+ if (target != nullptr) {
std::vector<cmSourceFile*> sourceFiles;
target->GetSourceFiles(sourceFiles,
makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
- std::vector<cmSourceFile*>::const_iterator sourceFilesEnd =
- sourceFiles.end();
- for (std::vector<cmSourceFile*>::const_iterator iter = sourceFiles.begin();
- iter != sourceFilesEnd; ++iter) {
- cmSourceFile* sourceFile = *iter;
+ for (cmSourceFile* sourceFile : sourceFiles) {
MapSourceFileFlags::iterator sourceFileFlagsIter =
sourceFileFlags.find(sourceFile->GetFullPath());
if (sourceFileFlagsIter == sourceFileFlags.end()) {
@@ -263,8 +254,9 @@ void cmExtraSublimeTextGenerator::AppendTarget(
.first;
}
std::vector<std::string>& flags = sourceFileFlagsIter->second;
- std::string flagsString = this->ComputeFlagsForObject(*iter, lg, target);
- std::string definesString = this->ComputeDefines(*iter, lg, target);
+ std::string flagsString =
+ this->ComputeFlagsForObject(sourceFile, lg, target);
+ std::string definesString = this->ComputeDefines(sourceFile, lg, target);
flags.clear();
cmsys::RegularExpression flagRegex;
// Regular expression to extract compiler flags from a string
@@ -282,7 +274,7 @@ void cmExtraSublimeTextGenerator::AppendTarget(
if (flagRegex.end() < workString.size()) {
workString = workString.substr(flagRegex.end());
} else {
- workString = "";
+ workString.clear();
}
}
}
diff --git a/Source/cmExtraSublimeTextGenerator.h b/Source/cmExtraSublimeTextGenerator.h
index 9022d3754..7fb304e11 100644
--- a/Source/cmExtraSublimeTextGenerator.h
+++ b/Source/cmExtraSublimeTextGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmExtraSublimeTextGenerator_h
#define cmExtraSublimeTextGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmExternalMakefileProjectGenerator.h"
@@ -24,10 +24,10 @@ class cmExtraSublimeTextGenerator : public cmExternalMakefileProjectGenerator
{
public:
static cmExternalMakefileProjectGeneratorFactory* GetFactory();
- typedef std::map<std::string, std::vector<std::string> > MapSourceFileFlags;
+ typedef std::map<std::string, std::vector<std::string>> MapSourceFileFlags;
cmExtraSublimeTextGenerator();
- void Generate() CM_OVERRIDE;
+ void Generate() override;
private:
void CreateProjectFile(const std::vector<cmLocalGenerator*>& lgs);
diff --git a/Source/cmFLTKWrapUICommand.cxx b/Source/cmFLTKWrapUICommand.cxx
index ff78f52e3..03d1ad1f6 100644
--- a/Source/cmFLTKWrapUICommand.cxx
+++ b/Source/cmFLTKWrapUICommand.cxx
@@ -72,8 +72,8 @@ bool cmFLTKWrapUICommand::InitialPass(std::vector<std::string> const& args,
// Add command for generating the .h and .cxx files
std::string no_main_dependency;
- const char* no_comment = CM_NULLPTR;
- const char* no_working_dir = CM_NULLPTR;
+ const char* no_comment = nullptr;
+ const char* no_working_dir = nullptr;
this->Makefile->AddCustomCommandToOutput(
cxxres, depends, no_main_dependency, commandLines, no_comment,
no_working_dir);
diff --git a/Source/cmFLTKWrapUICommand.h b/Source/cmFLTKWrapUICommand.h
index d8045ab6a..044755e5b 100644
--- a/Source/cmFLTKWrapUICommand.h
+++ b/Source/cmFLTKWrapUICommand.h
@@ -3,7 +3,7 @@
#ifndef cmFLTKWrapUICommand_h
#define cmFLTKWrapUICommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -25,14 +25,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmFLTKWrapUICommand; }
+ cmCommand* Clone() override { return new cmFLTKWrapUICommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
/**
* This is called at the end after all the information
@@ -40,8 +40,8 @@ public:
* not implement this method. At this point, reading and
* writing to the cache can be done.
*/
- void FinalPass() CM_OVERRIDE;
- bool HasFinalPass() const CM_OVERRIDE { return true; }
+ void FinalPass() override;
+ bool HasFinalPass() const override { return true; }
private:
/**
diff --git a/Source/cmFileCommand.cxx b/Source/cmFileCommand.cxx
index 5777fb204..fdd5f0c81 100644
--- a/Source/cmFileCommand.cxx
+++ b/Source/cmFileCommand.cxx
@@ -10,6 +10,7 @@
#include "cmsys/String.hxx"
#include <algorithm>
#include <assert.h>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
@@ -30,7 +31,6 @@
#include "cmPolicies.h"
#include "cmSystemTools.h"
#include "cmTimestamp.h"
-#include "cm_auto_ptr.hxx"
#include "cm_sys_stat.h"
#include "cmake.h"
@@ -55,14 +55,14 @@ class cmSystemToolsFileTime;
static mode_t mode_owner_read = S_IREAD;
static mode_t mode_owner_write = S_IWRITE;
static mode_t mode_owner_execute = S_IEXEC;
-static mode_t mode_group_read = 0;
-static mode_t mode_group_write = 0;
-static mode_t mode_group_execute = 0;
-static mode_t mode_world_read = 0;
-static mode_t mode_world_write = 0;
-static mode_t mode_world_execute = 0;
-static mode_t mode_setuid = 0;
-static mode_t mode_setgid = 0;
+static mode_t mode_group_read = 040;
+static mode_t mode_group_write = 020;
+static mode_t mode_group_execute = 010;
+static mode_t mode_world_read = 04;
+static mode_t mode_world_write = 02;
+static mode_t mode_world_execute = 01;
+static mode_t mode_setuid = 04000;
+static mode_t mode_setgid = 02000;
#else
static mode_t mode_owner_read = S_IRUSR;
static mode_t mode_owner_write = S_IWUSR;
@@ -269,17 +269,17 @@ bool cmFileCommand::HandleReadCommand(std::vector<std::string> const& args)
cmCommandArgumentGroup group;
cmCAString readArg(&argHelper, "READ");
- cmCAString fileNameArg(&argHelper, CM_NULLPTR);
- cmCAString resultArg(&argHelper, CM_NULLPTR);
+ cmCAString fileNameArg(&argHelper, nullptr);
+ cmCAString resultArg(&argHelper, nullptr);
cmCAString offsetArg(&argHelper, "OFFSET", &group);
cmCAString limitArg(&argHelper, "LIMIT", &group);
cmCAEnabler hexOutputArg(&argHelper, "HEX", &group);
- readArg.Follows(CM_NULLPTR);
+ readArg.Follows(nullptr);
fileNameArg.Follows(&readArg);
resultArg.Follows(&fileNameArg);
group.Follows(&resultArg);
- argHelper.Parse(&args, CM_NULLPTR);
+ argHelper.Parse(&args, nullptr);
std::string fileName = fileNameArg.GetString();
if (!cmsys::SystemTools::FileIsFullPath(fileName.c_str())) {
@@ -368,8 +368,8 @@ bool cmFileCommand::HandleHashCommand(std::vector<std::string> const& args)
return false;
}
- CM_AUTO_PTR<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
- if (hash.get()) {
+ std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
+ if (hash) {
std::string out = hash->HashFile(args[1]);
if (!out.empty()) {
this->Makefile->AddDefinition(args[2], out.c_str());
@@ -656,7 +656,7 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args)
c = current_str[current_str.size() - 1 - j];
fin.putback(static_cast<char>(c));
}
- current_str = "";
+ current_str.clear();
}
}
@@ -667,14 +667,14 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args)
if (s.length() >= minlen && (!have_regex || regex.find(s.c_str()))) {
output_size += static_cast<int>(s.size()) + 1;
if (limit_output >= 0 && output_size >= limit_output) {
- s = "";
+ s.clear();
break;
}
strings.push_back(s);
}
// Reset the string to empty.
- s = "";
+ s.clear();
} else if (current_str.empty()) {
// A non-string character has been found. Check if the current
// string matches the requirements. We require that the length
@@ -683,14 +683,14 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args)
(!have_regex || regex.find(s.c_str()))) {
output_size += static_cast<int>(s.size()) + 1;
if (limit_output >= 0 && output_size >= limit_output) {
- s = "";
+ s.clear();
break;
}
strings.push_back(s);
}
// Reset the string to empty.
- s = "";
+ s.clear();
} else {
s += current_str;
}
@@ -700,12 +700,12 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args)
if (s.length() >= minlen && (!have_regex || regex.find(s.c_str()))) {
output_size += static_cast<int>(s.size()) + 1;
if (limit_output >= 0 && output_size >= limit_output) {
- s = "";
+ s.clear();
break;
}
strings.push_back(s);
}
- s = "";
+ s.clear();
}
}
@@ -723,20 +723,18 @@ bool cmFileCommand::HandleStringsCommand(std::vector<std::string> const& args)
// Encode the result in a CMake list.
const char* sep = "";
std::string output;
- for (std::vector<std::string>::const_iterator si = strings.begin();
- si != strings.end(); ++si) {
+ for (std::string const& sr : strings) {
// Separate the strings in the output to make it a list.
output += sep;
sep = ";";
// Store the string in the output, but escape semicolons to
// make sure it is a list.
- std::string const& sr = *si;
- for (unsigned int i = 0; i < sr.size(); ++i) {
- if (sr[i] == ';') {
+ for (char i : sr) {
+ if (i == ';') {
output += '\\';
}
- output += sr[i];
+ output += i;
}
}
@@ -841,17 +839,16 @@ bool cmFileCommand::HandleGlobCommand(std::vector<std::string> const& args,
if (!globMessages.empty()) {
bool shouldExit = false;
- for (cmsys::Glob::GlobMessagesIterator it = globMessages.begin();
- it != globMessages.end(); ++it) {
- if (it->type == cmsys::Glob::cyclicRecursion) {
+ for (cmsys::Glob::Message const& globMessage : globMessages) {
+ if (globMessage.type == cmsys::Glob::cyclicRecursion) {
this->Makefile->IssueMessage(
cmake::AUTHOR_WARNING,
"Cyclic recursion detected while globbing for '" + *i + "':\n" +
- it->content);
+ globMessage.content);
} else {
this->Makefile->IssueMessage(
cmake::FATAL_ERROR, "Error has occurred while globbing for '" +
- *i + "' - " + it->content);
+ *i + "' - " + globMessage.content);
shouldExit = true;
}
}
@@ -940,9 +937,9 @@ bool cmFileCommand::HandleDifferentCommand(
*/
// Evaluate arguments.
- const char* file_lhs = CM_NULLPTR;
- const char* file_rhs = CM_NULLPTR;
- const char* var = CM_NULLPTR;
+ const char* file_lhs = nullptr;
+ const char* file_rhs = nullptr;
+ const char* var = nullptr;
enum Doing
{
DoingNone,
@@ -997,7 +994,7 @@ struct cmFileCopier
, MatchlessFiles(true)
, FilePermissions(0)
, DirPermissions(0)
- , CurrentMatchRule(CM_NULLPTR)
+ , CurrentMatchRule(nullptr)
, UseGivenPermissionsFile(false)
, UseGivenPermissionsDir(false)
, UseSourcePermissions(true)
@@ -1060,12 +1057,11 @@ protected:
// Collect properties from all matching rules.
bool matched = false;
MatchProperties result;
- for (std::vector<MatchRule>::iterator mr = this->MatchRules.begin();
- mr != this->MatchRules.end(); ++mr) {
- if (mr->Regex.find(file_to_match)) {
+ for (MatchRule& mr : this->MatchRules) {
+ if (mr.Regex.find(file_to_match)) {
matched = true;
- result.Exclude |= mr->Properties.Exclude;
- result.Permissions |= mr->Properties.Permissions;
+ result.Exclude |= mr.Properties.Exclude;
+ result.Permissions |= mr.Properties.Permissions;
}
}
if (!matched && !this->MatchlessFiles) {
@@ -1076,11 +1072,26 @@ protected:
bool SetPermissions(const char* toFile, mode_t permissions)
{
- if (permissions && !cmSystemTools::SetPermissions(toFile, permissions)) {
- std::ostringstream e;
- e << this->Name << " cannot set permissions on \"" << toFile << "\"";
- this->FileCommand->SetError(e.str());
- return false;
+ if (permissions) {
+#ifdef WIN32
+ if (Makefile->IsOn("CMAKE_CROSSCOMPILING")) {
+ std::string mode_t_adt_filename =
+ std::string(toFile) + ":cmake_mode_t";
+
+ cmsys::ofstream permissionStream(mode_t_adt_filename.c_str());
+
+ if (permissionStream) {
+ permissionStream << std::oct << permissions << std::endl;
+ }
+ }
+#endif
+
+ if (!cmSystemTools::SetPermissions(toFile, permissions)) {
+ std::ostringstream e;
+ e << this->Name << " cannot set permissions on \"" << toFile << "\"";
+ this->FileCommand->SetError(e.str());
+ return false;
+ }
}
return true;
}
@@ -1406,23 +1417,22 @@ bool cmFileCopier::Run(std::vector<std::string> const& args)
return false;
}
- for (std::vector<std::string>::const_iterator i = this->Files.begin();
- i != this->Files.end(); ++i) {
+ for (std::string const& f : this->Files) {
std::string file;
- if (!i->empty() && !cmSystemTools::FileIsFullPath(*i)) {
+ if (!f.empty() && !cmSystemTools::FileIsFullPath(f)) {
if (!this->FilesFromDir.empty()) {
file = this->FilesFromDir;
} else {
file = this->Makefile->GetCurrentSourceDirectory();
}
file += "/";
- file += *i;
+ file += f;
} else if (!this->FilesFromDir.empty()) {
this->FileCommand->SetError("option FILES_FROM_DIR requires all files "
"to be specified as relative paths.");
return false;
} else {
- file = *i;
+ file = f;
}
// Split the input file into its directory and name components.
@@ -1435,7 +1445,7 @@ bool cmFileCopier::Run(std::vector<std::string> const& args)
// Compute the full path to the destination file.
std::string toFile = this->Destination;
if (!this->FilesFromDir.empty()) {
- std::string dir = cmSystemTools::GetFilenamePath(*i);
+ std::string dir = cmSystemTools::GetFilenamePath(f);
if (!dir.empty()) {
toFile += "/";
toFile += dir;
@@ -1696,7 +1706,7 @@ struct cmFileInstaller : public cmFileCopier
this->Manifest =
this->Makefile->GetSafeDefinition("CMAKE_INSTALL_MANIFEST_FILES");
}
- ~cmFileInstaller() CM_OVERRIDE
+ ~cmFileInstaller() override
{
// Save the updated install manifest.
this->Makefile->AddDefinition("CMAKE_INSTALL_MANIFEST_FILES",
@@ -1721,12 +1731,12 @@ protected:
this->Manifest += file.substr(this->DestDirLength);
}
- std::string const& ToName(std::string const& fromName) CM_OVERRIDE
+ std::string const& ToName(std::string const& fromName) override
{
return this->Rename.empty() ? fromName : this->Rename;
}
- void ReportCopy(const char* toFile, Type type, bool copy) CM_OVERRIDE
+ void ReportCopy(const char* toFile, Type type, bool copy) override
{
if (!this->MessageNever && (copy || !this->MessageLazy)) {
std::string message = (copy ? "Installing: " : "Up-to-date: ");
@@ -1738,11 +1748,11 @@ protected:
this->ManifestAppend(toFile);
}
}
- bool ReportMissing(const char* fromFile) CM_OVERRIDE
+ bool ReportMissing(const char* fromFile) override
{
return (this->Optional || this->cmFileCopier::ReportMissing(fromFile));
}
- bool Install(const char* fromFile, const char* toFile) CM_OVERRIDE
+ bool Install(const char* fromFile, const char* toFile) override
{
// Support installing from empty source to make a directory.
if (this->InstallType == cmInstallType_DIRECTORY && !*fromFile) {
@@ -1751,16 +1761,16 @@ protected:
return this->cmFileCopier::Install(fromFile, toFile);
}
- bool Parse(std::vector<std::string> const& args) CM_OVERRIDE;
+ bool Parse(std::vector<std::string> const& args) override;
enum
{
DoingType = DoingLast1,
DoingRename,
DoingLast2
};
- bool CheckKeyword(std::string const& arg) CM_OVERRIDE;
- bool CheckValue(std::string const& arg) CM_OVERRIDE;
- void DefaultFilePermissions() CM_OVERRIDE
+ bool CheckKeyword(std::string const& arg) override;
+ bool CheckValue(std::string const& arg) override;
+ void DefaultFilePermissions() override
{
this->cmFileCopier::DefaultFilePermissions();
// Add execute permissions based on the target type.
@@ -2028,9 +2038,9 @@ bool cmFileCommand::HandleRPathChangeCommand(
std::vector<std::string> const& args)
{
// Evaluate arguments.
- const char* file = CM_NULLPTR;
- const char* oldRPath = CM_NULLPTR;
- const char* newRPath = CM_NULLPTR;
+ const char* file = nullptr;
+ const char* oldRPath = nullptr;
+ const char* newRPath = nullptr;
enum Doing
{
DoingNone,
@@ -2118,7 +2128,7 @@ bool cmFileCommand::HandleRPathRemoveCommand(
std::vector<std::string> const& args)
{
// Evaluate arguments.
- const char* file = CM_NULLPTR;
+ const char* file = nullptr;
enum Doing
{
DoingNone,
@@ -2182,8 +2192,8 @@ bool cmFileCommand::HandleRPathCheckCommand(
std::vector<std::string> const& args)
{
// Evaluate arguments.
- const char* file = CM_NULLPTR;
- const char* rpath = CM_NULLPTR;
+ const char* file = nullptr;
+ const char* rpath = nullptr;
enum Doing
{
DoingNone,
@@ -2241,16 +2251,16 @@ bool cmFileCommand::HandleReadElfCommand(std::vector<std::string> const& args)
cmCommandArgumentGroup group;
cmCAString readArg(&argHelper, "READ_ELF");
- cmCAString fileNameArg(&argHelper, CM_NULLPTR);
+ cmCAString fileNameArg(&argHelper, nullptr);
cmCAString rpathArg(&argHelper, "RPATH", &group);
cmCAString runpathArg(&argHelper, "RUNPATH", &group);
cmCAString errorArg(&argHelper, "CAPTURE_ERROR", &group);
- readArg.Follows(CM_NULLPTR);
+ readArg.Follows(nullptr);
fileNameArg.Follows(&readArg);
group.Follows(&fileNameArg);
- argHelper.Parse(&args, CM_NULLPTR);
+ argHelper.Parse(&args, nullptr);
if (!cmSystemTools::FileExists(fileNameArg.GetString(), true)) {
std::ostringstream e;
@@ -2284,10 +2294,9 @@ bool cmFileCommand::HandleReadElfCommand(std::vector<std::string> const& args)
if (errorArg.GetString().empty()) {
this->SetError(error);
return false;
- } else {
- this->Makefile->AddDefinition(errorArg.GetString(), error.c_str());
- return true;
}
+ this->Makefile->AddDefinition(errorArg.GetString(), error.c_str());
+ return true;
#endif
}
@@ -2439,7 +2448,7 @@ namespace {
size_t cmWriteToFileCallback(void* ptr, size_t size, size_t nmemb, void* data)
{
- int realsize = (int)(size * nmemb);
+ int realsize = static_cast<int>(size * nmemb);
cmsys::ofstream* fout = static_cast<cmsys::ofstream*>(data);
const char* chPtr = static_cast<char*>(ptr);
fout->write(chPtr, realsize);
@@ -2449,7 +2458,7 @@ size_t cmWriteToFileCallback(void* ptr, size_t size, size_t nmemb, void* data)
size_t cmWriteToMemoryCallback(void* ptr, size_t size, size_t nmemb,
void* data)
{
- int realsize = (int)(size * nmemb);
+ int realsize = static_cast<int>(size * nmemb);
cmFileCommandVectorOfChar* vec =
static_cast<cmFileCommandVectorOfChar*>(data);
const char* chPtr = static_cast<char*>(ptr);
@@ -2581,7 +2590,7 @@ public:
}
}
- void release() { this->Easy = CM_NULLPTR; }
+ void release() { this->Easy = nullptr; }
private:
::CURL* Easy;
@@ -2619,7 +2628,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
const char* cainfo = this->Makefile->GetDefinition("CMAKE_TLS_CAINFO");
std::string expectedHash;
std::string hashMatchMSG;
- CM_AUTO_PTR<cmCryptoHash> hash;
+ std::unique_ptr<cmCryptoHash> hash;
bool showProgress = false;
std::string userpwd;
@@ -2678,8 +2687,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
this->SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
return false;
}
- hash =
- CM_AUTO_PTR<cmCryptoHash>(new cmCryptoHash(cmCryptoHash::AlgoMD5));
+ hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5);
hashMatchMSG = "MD5 sum";
expectedHash = cmSystemTools::LowerCase(*i);
} else if (*i == "SHOW_PROGRESS") {
@@ -2700,7 +2708,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
}
std::string algo = i->substr(0, pos);
expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
- hash = CM_AUTO_PTR<cmCryptoHash>(cmCryptoHash::New(algo.c_str()));
+ hash = std::unique_ptr<cmCryptoHash>(cmCryptoHash::New(algo.c_str()));
if (!hash.get()) {
std::string err = "DOWNLOAD EXPECTED_HASH given unknown ALGO: ";
err += algo;
@@ -2743,7 +2751,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
msg += "\"";
if (!statusVar.empty()) {
std::ostringstream result;
- result << (int)0 << ";\"" << msg;
+ result << 0 << ";\"" << msg;
this->Makefile->AddDefinition(statusVar, result.str().c_str());
}
return true;
@@ -2816,10 +2824,10 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
cmFileCommandVectorOfChar chunkDebug;
- res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&fout);
+ res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &fout);
check_curl_result(res, "DOWNLOAD cannot set write data: ");
- res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void*)&chunkDebug);
+ res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
check_curl_result(res, "DOWNLOAD cannot set debug data: ");
res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
@@ -2866,10 +2874,9 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
check_curl_result(res, "DOWNLOAD cannot set user password: ");
}
- struct curl_slist* headers = CM_NULLPTR;
- for (std::vector<std::string>::const_iterator h = curl_headers.begin();
- h != curl_headers.end(); ++h) {
- headers = ::curl_slist_append(headers, h->c_str());
+ struct curl_slist* headers = nullptr;
+ for (std::string const& h : curl_headers) {
+ headers = ::curl_slist_append(headers, h.c_str());
}
::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
@@ -2883,7 +2890,8 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
if (!statusVar.empty()) {
std::ostringstream result;
- result << (int)res << ";\"" << ::curl_easy_strerror(res) << "\"";
+ result << static_cast<int>(res) << ";\"" << ::curl_easy_strerror(res)
+ << "\"";
this->Makefile->AddDefinition(statusVar, result.str().c_str());
}
@@ -2896,7 +2904,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
// Verify MD5 sum if requested:
//
- if (hash.get()) {
+ if (hash) {
std::string actualHash = hash->HashFile(file);
if (actualHash.empty()) {
this->SetError("DOWNLOAD cannot compute hash on downloaded file");
@@ -2909,7 +2917,7 @@ bool cmFileCommand::HandleDownloadCommand(std::vector<std::string> const& args)
<< " for file: [" << file << "]" << std::endl
<< " expected hash: [" << expectedHash << "]" << std::endl
<< " actual hash: [" << actualHash << "]" << std::endl
- << " status: [" << (int)res << ";\""
+ << " status: [" << static_cast<int>(res) << ";\""
<< ::curl_easy_strerror(res) << "\"]" << std::endl;
if (!statusVar.empty() && res == 0) {
@@ -3065,10 +3073,10 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
cmFileCommandVectorOfChar chunkResponse;
cmFileCommandVectorOfChar chunkDebug;
- res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunkResponse);
+ res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunkResponse);
check_curl_result(res, "UPLOAD cannot set write data: ");
- res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void*)&chunkDebug);
+ res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
check_curl_result(res, "UPLOAD cannot set debug data: ");
res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
@@ -3124,10 +3132,9 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
check_curl_result(res, "UPLOAD cannot set user password: ");
}
- struct curl_slist* headers = CM_NULLPTR;
- for (std::vector<std::string>::const_iterator h = curl_headers.begin();
- h != curl_headers.end(); ++h) {
- headers = ::curl_slist_append(headers, h->c_str());
+ struct curl_slist* headers = nullptr;
+ for (std::string const& h : curl_headers) {
+ headers = ::curl_slist_append(headers, h.c_str());
}
::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
@@ -3141,14 +3148,15 @@ bool cmFileCommand::HandleUploadCommand(std::vector<std::string> const& args)
if (!statusVar.empty()) {
std::ostringstream result;
- result << (int)res << ";\"" << ::curl_easy_strerror(res) << "\"";
+ result << static_cast<int>(res) << ";\"" << ::curl_easy_strerror(res)
+ << "\"";
this->Makefile->AddDefinition(statusVar, result.str().c_str());
}
::curl_global_cleanup();
fclose(fin);
- fin = CM_NULLPTR;
+ fin = nullptr;
if (!logVar.empty()) {
std::string log;
@@ -3185,15 +3193,15 @@ void cmFileCommand::AddEvaluationFile(const std::string& inputName,
cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
cmGeneratorExpression outputGe(lfbt);
- CM_AUTO_PTR<cmCompiledGeneratorExpression> outputCge =
+ std::unique_ptr<cmCompiledGeneratorExpression> outputCge =
outputGe.Parse(outputExpr);
cmGeneratorExpression conditionGe(lfbt);
- CM_AUTO_PTR<cmCompiledGeneratorExpression> conditionCge =
+ std::unique_ptr<cmCompiledGeneratorExpression> conditionCge =
conditionGe.Parse(condition);
- this->Makefile->AddEvaluationFile(inputName, outputCge, conditionCge,
- inputIsContent);
+ this->Makefile->AddEvaluationFile(inputName, std::move(outputCge),
+ std::move(conditionCge), inputIsContent);
}
bool cmFileCommand::HandleGenerateCommand(std::vector<std::string> const& args)
diff --git a/Source/cmFileCommand.h b/Source/cmFileCommand.h
index d09ef42f1..17269f3f9 100644
--- a/Source/cmFileCommand.h
+++ b/Source/cmFileCommand.h
@@ -3,7 +3,7 @@
#ifndef cmFileCommand_h
#define cmFileCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -22,14 +22,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmFileCommand; }
+ cmCommand* Clone() override { return new cmFileCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
protected:
bool HandleRename(std::vector<std::string> const& args);
diff --git a/Source/cmFileLock.cxx b/Source/cmFileLock.cxx
index 786d6c63f..f309241a6 100644
--- a/Source/cmFileLock.cxx
+++ b/Source/cmFileLock.cxx
@@ -42,7 +42,7 @@ cmFileLockResult cmFileLock::Lock(const std::string& filename,
}
if (!result.IsOk()) {
- this->Filename = "";
+ this->Filename.clear();
}
return result;
diff --git a/Source/cmFileLock.h b/Source/cmFileLock.h
index ccef50816..c9ab0dbcb 100644
--- a/Source/cmFileLock.h
+++ b/Source/cmFileLock.h
@@ -3,7 +3,7 @@
#ifndef cmFileLock_h
#define cmFileLock_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
diff --git a/Source/cmFileLockPool.cxx b/Source/cmFileLockPool.cxx
index 7b1564c34..5dc9243a1 100644
--- a/Source/cmFileLockPool.cxx
+++ b/Source/cmFileLockPool.cxx
@@ -75,16 +75,15 @@ cmFileLockResult cmFileLockPool::LockProcessScope(const std::string& filename,
cmFileLockResult cmFileLockPool::Release(const std::string& filename)
{
- for (It i = this->FunctionScopes.begin(); i != this->FunctionScopes.end();
- ++i) {
- const cmFileLockResult result = (*i)->Release(filename);
+ for (auto& funcScope : this->FunctionScopes) {
+ const cmFileLockResult result = funcScope->Release(filename);
if (!result.IsOk()) {
return result;
}
}
- for (It i = this->FileScopes.begin(); i != this->FileScopes.end(); ++i) {
- const cmFileLockResult result = (*i)->Release(filename);
+ for (auto& fileScope : this->FileScopes) {
+ const cmFileLockResult result = fileScope->Release(filename);
if (!result.IsOk()) {
return result;
}
@@ -95,16 +94,15 @@ cmFileLockResult cmFileLockPool::Release(const std::string& filename)
bool cmFileLockPool::IsAlreadyLocked(const std::string& filename) const
{
- for (CIt i = this->FunctionScopes.begin(); i != this->FunctionScopes.end();
- ++i) {
- const bool result = (*i)->IsAlreadyLocked(filename);
+ for (auto const& funcScope : this->FunctionScopes) {
+ const bool result = funcScope->IsAlreadyLocked(filename);
if (result) {
return true;
}
}
- for (CIt i = this->FileScopes.begin(); i != this->FileScopes.end(); ++i) {
- const bool result = (*i)->IsAlreadyLocked(filename);
+ for (auto const& fileScope : this->FileScopes) {
+ const bool result = fileScope->IsAlreadyLocked(filename);
if (result) {
return true;
}
@@ -138,9 +136,9 @@ cmFileLockResult cmFileLockPool::ScopePool::Lock(const std::string& filename,
cmFileLockResult cmFileLockPool::ScopePool::Release(
const std::string& filename)
{
- for (It i = this->Locks.begin(); i != this->Locks.end(); ++i) {
- if ((*i)->IsLocked(filename)) {
- return (*i)->Release();
+ for (auto& lock : this->Locks) {
+ if (lock->IsLocked(filename)) {
+ return lock->Release();
}
}
return cmFileLockResult::MakeOk();
@@ -149,8 +147,8 @@ cmFileLockResult cmFileLockPool::ScopePool::Release(
bool cmFileLockPool::ScopePool::IsAlreadyLocked(
const std::string& filename) const
{
- for (CIt i = this->Locks.begin(); i != this->Locks.end(); ++i) {
- if ((*i)->IsLocked(filename)) {
+ for (auto const& lock : this->Locks) {
+ if (lock->IsLocked(filename)) {
return true;
}
}
diff --git a/Source/cmFileLockPool.h b/Source/cmFileLockPool.h
index c96a8c2f8..af982707e 100644
--- a/Source/cmFileLockPool.h
+++ b/Source/cmFileLockPool.h
@@ -3,7 +3,7 @@
#ifndef cmFileLockPool_h
#define cmFileLockPool_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
diff --git a/Source/cmFileLockResult.cxx b/Source/cmFileLockResult.cxx
index a040705e8..9ca5d8a06 100644
--- a/Source/cmFileLockResult.cxx
+++ b/Source/cmFileLockResult.cxx
@@ -5,6 +5,7 @@
#include <errno.h>
#include <string.h>
+#define WINMSG_BUF_LEN (1024)
cmFileLockResult cmFileLockResult::MakeOk()
{
return cmFileLockResult(OK, 0);
@@ -53,18 +54,12 @@ std::string cmFileLockResult::GetOutputMessage() const
case SYSTEM:
#if defined(_WIN32)
{
- char* errorText = NULL;
-
- // http://stackoverflow.com/a/455533/2288008
- DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS;
- ::FormatMessageA(flags, NULL, this->ErrorValue,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (LPSTR)&errorText, 0, NULL);
-
- if (errorText != NULL) {
- const std::string message = errorText;
- ::LocalFree(errorText);
+ char winmsg[WINMSG_BUF_LEN];
+ DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
+ if (FormatMessageA(flags, NULL, this->ErrorValue,
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPSTR)winmsg, WINMSG_BUF_LEN, NULL)) {
+ const std::string message = winmsg;
return message;
} else {
return "Internal error (FormatMessageA failed)";
diff --git a/Source/cmFileMonitor.cxx b/Source/cmFileMonitor.cxx
index 80275357c..04a3c0ef7 100644
--- a/Source/cmFileMonitor.cxx
+++ b/Source/cmFileMonitor.cxx
@@ -49,8 +49,8 @@ public:
int status) const final
{
if (pathSegment.empty()) {
- for (const auto& i : this->Children) {
- i.second->Trigger(std::string(), events, status);
+ for (auto const& child : this->Children) {
+ child.second->Trigger(std::string(), events, status);
}
} else {
const auto i = this->Children.find(pathSegment);
@@ -62,24 +62,24 @@ public:
void StartWatching() override
{
- for (const auto& i : this->Children) {
- i.second->StartWatching();
+ for (auto const& child : this->Children) {
+ child.second->StartWatching();
}
}
void StopWatching() override
{
- for (const auto& i : this->Children) {
- i.second->StopWatching();
+ for (auto const& child : this->Children) {
+ child.second->StopWatching();
}
}
std::vector<std::string> WatchedFiles() const final
{
std::vector<std::string> result;
- for (const auto& i : this->Children) {
- for (const auto& j : i.second->WatchedFiles()) {
- result.push_back(j);
+ for (auto const& child : this->Children) {
+ for (std::string const& f : child.second->WatchedFiles()) {
+ result.push_back(f);
}
}
return result;
@@ -88,9 +88,9 @@ public:
std::vector<std::string> WatchedDirectories() const override
{
std::vector<std::string> result;
- for (const auto& i : this->Children) {
- for (const auto& j : i.second->WatchedDirectories()) {
- result.push_back(j);
+ for (auto const& child : this->Children) {
+ for (std::string const& dir : child.second->WatchedDirectories()) {
+ result.push_back(dir);
}
}
return result;
@@ -171,7 +171,9 @@ public:
{
if (this->Handle) {
uv_fs_event_stop(this->Handle);
- uv_close(reinterpret_cast<uv_handle_t*>(this->Handle), &on_fs_close);
+ if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(this->Handle))) {
+ uv_close(reinterpret_cast<uv_handle_t*>(this->Handle), &on_fs_close);
+ }
this->Handle = nullptr;
}
cmVirtualDirectoryWatcher::StopWatching();
@@ -182,8 +184,9 @@ public:
std::vector<std::string> WatchedDirectories() const override
{
std::vector<std::string> result = { Path() };
- for (const auto& j : cmVirtualDirectoryWatcher::WatchedDirectories()) {
- result.push_back(j);
+ for (std::string const& dir :
+ cmVirtualDirectoryWatcher::WatchedDirectories()) {
+ result.push_back(dir);
}
return result;
}
@@ -265,7 +268,7 @@ public:
static_cast<void>(ps);
const std::string path = this->Path();
- for (const auto& cb : this->CbList) {
+ for (cmFileMonitor::Callback const& cb : this->CbList) {
cb(path, events, status);
}
}
@@ -309,7 +312,7 @@ cmFileMonitor::~cmFileMonitor()
void cmFileMonitor::MonitorPaths(const std::vector<std::string>& paths,
Callback const& cb)
{
- for (const auto& p : paths) {
+ for (std::string const& p : paths) {
std::vector<std::string> pathSegments;
cmsys::SystemTools::SplitPath(p, pathSegments, true);
diff --git a/Source/cmFileMonitor.h b/Source/cmFileMonitor.h
index d7ec92a17..632e7514f 100644
--- a/Source/cmFileMonitor.h
+++ b/Source/cmFileMonitor.h
@@ -2,7 +2,7 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#pragma once
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <functional>
#include <string>
diff --git a/Source/cmFilePathChecksum.cxx b/Source/cmFilePathChecksum.cxx
index 62f52e590..f9afeefcd 100644
--- a/Source/cmFilePathChecksum.cxx
+++ b/Source/cmFilePathChecksum.cxx
@@ -13,10 +13,10 @@ cmFilePathChecksum::cmFilePathChecksum()
{
}
-cmFilePathChecksum::cmFilePathChecksum(const std::string& currentSrcDir,
- const std::string& currentBinDir,
- const std::string& projectSrcDir,
- const std::string& projectBinDir)
+cmFilePathChecksum::cmFilePathChecksum(std::string const& currentSrcDir,
+ std::string const& currentBinDir,
+ std::string const& projectSrcDir,
+ std::string const& projectBinDir)
{
setupParentDirs(currentSrcDir, currentBinDir, projectSrcDir, projectBinDir);
}
@@ -29,36 +29,35 @@ cmFilePathChecksum::cmFilePathChecksum(cmMakefile* makefile)
makefile->GetHomeOutputDirectory());
}
-void cmFilePathChecksum::setupParentDirs(const std::string& currentSrcDir,
- const std::string& currentBinDir,
- const std::string& projectSrcDir,
- const std::string& projectBinDir)
+void cmFilePathChecksum::setupParentDirs(std::string const& currentSrcDir,
+ std::string const& currentBinDir,
+ std::string const& projectSrcDir,
+ std::string const& projectBinDir)
{
- parentDirs[0].first = cmsys::SystemTools::GetRealPath(currentSrcDir);
- parentDirs[1].first = cmsys::SystemTools::GetRealPath(currentBinDir);
- parentDirs[2].first = cmsys::SystemTools::GetRealPath(projectSrcDir);
- parentDirs[3].first = cmsys::SystemTools::GetRealPath(projectBinDir);
+ this->parentDirs[0].first = cmsys::SystemTools::GetRealPath(currentSrcDir);
+ this->parentDirs[1].first = cmsys::SystemTools::GetRealPath(currentBinDir);
+ this->parentDirs[2].first = cmsys::SystemTools::GetRealPath(projectSrcDir);
+ this->parentDirs[3].first = cmsys::SystemTools::GetRealPath(projectBinDir);
- parentDirs[0].second = "CurrentSource";
- parentDirs[1].second = "CurrentBinary";
- parentDirs[2].second = "ProjectSource";
- parentDirs[3].second = "ProjectBinary";
+ this->parentDirs[0].second = "CurrentSource";
+ this->parentDirs[1].second = "CurrentBinary";
+ this->parentDirs[2].second = "ProjectSource";
+ this->parentDirs[3].second = "ProjectBinary";
}
-std::string cmFilePathChecksum::get(const std::string& filePath) const
+std::string cmFilePathChecksum::get(std::string const& filePath) const
{
std::string relPath;
std::string relSeed;
{
- const std::string fileReal = cmsys::SystemTools::GetRealPath(filePath);
+ std::string const fileReal = cmsys::SystemTools::GetRealPath(filePath);
std::string parentDir;
// Find closest project parent directory
- for (size_t ii = 0; ii != numParentDirs; ++ii) {
- const std::string& pDir = parentDirs[ii].first;
- if (!pDir.empty() &&
- cmsys::SystemTools::IsSubDirectory(fileReal, pDir)) {
- relSeed = parentDirs[ii].second;
- parentDir = pDir;
+ for (auto const& pDir : this->parentDirs) {
+ if (!pDir.first.empty() &&
+ cmsys::SystemTools::IsSubDirectory(fileReal, pDir.first)) {
+ parentDir = pDir.first;
+ relSeed = pDir.second;
break;
}
}
@@ -77,11 +76,11 @@ std::string cmFilePathChecksum::get(const std::string& filePath) const
cmCryptoHash(cmCryptoHash::AlgoSHA256).ByteHashString(relSeed + relPath);
// Convert binary checksum to string
- return cmBase32Encoder().encodeString(&hashBytes[0], hashBytes.size(),
+ return cmBase32Encoder().encodeString(&hashBytes.front(), hashBytes.size(),
false);
}
-std::string cmFilePathChecksum::getPart(const std::string& filePath,
+std::string cmFilePathChecksum::getPart(std::string const& filePath,
size_t length) const
{
return get(filePath).substr(0, length);
diff --git a/Source/cmFilePathChecksum.h b/Source/cmFilePathChecksum.h
index 9d570eb4d..48b5da0f0 100644
--- a/Source/cmFilePathChecksum.h
+++ b/Source/cmFilePathChecksum.h
@@ -5,6 +5,7 @@
#include "cmConfigure.h" // IWYU pragma: keep
+#include <array>
#include <stddef.h>
#include <string>
#include <utility>
@@ -29,37 +30,35 @@ public:
cmFilePathChecksum();
/// @brief Initilizes the parent directories manually
- cmFilePathChecksum(const std::string& currentSrcDir,
- const std::string& currentBinDir,
- const std::string& projectSrcDir,
- const std::string& projectBinDir);
+ cmFilePathChecksum(std::string const& currentSrcDir,
+ std::string const& currentBinDir,
+ std::string const& projectSrcDir,
+ std::string const& projectBinDir);
/// @brief Initilizes the parent directories from a makefile
cmFilePathChecksum(cmMakefile* makefile);
/// @brief Allows parent directories setup after construction
///
- void setupParentDirs(const std::string& currentSrcDir,
- const std::string& currentBinDir,
- const std::string& projectSrcDir,
- const std::string& projectBinDir);
+ void setupParentDirs(std::string const& currentSrcDir,
+ std::string const& currentBinDir,
+ std::string const& projectSrcDir,
+ std::string const& projectBinDir);
/* @brief Calculates the path checksum for the parent directory of a file
*
*/
- std::string get(const std::string& filePath) const;
+ std::string get(std::string const& filePath) const;
/* @brief Same as get() but returns only the first length characters
*
*/
- std::string getPart(const std::string& filePath,
+ std::string getPart(std::string const& filePath,
size_t length = partLengthDefault) const;
private:
- /// Size of the parent directory list
- static const size_t numParentDirs = 4;
/// List of (directory name, seed name) pairs
- std::pair<std::string, std::string> parentDirs[numParentDirs];
+ std::array<std::pair<std::string, std::string>, 4> parentDirs;
};
#endif
diff --git a/Source/cmFileTimeComparison.cxx b/Source/cmFileTimeComparison.cxx
index f591a8dc7..622c15e2c 100644
--- a/Source/cmFileTimeComparison.cxx
+++ b/Source/cmFileTimeComparison.cxx
@@ -4,10 +4,9 @@
#include <string>
#include <time.h>
+#include <unordered_map>
#include <utility>
-#include "cm_unordered_map.hxx"
-
// Use a platform-specific API to get file times efficiently.
#if !defined(_WIN32) || defined(__CYGWIN__)
#include "cm_sys_stat.h"
@@ -27,7 +26,7 @@ public:
bool FileTimesDiffer(const char* f1, const char* f2);
private:
- typedef CM_UNORDERED_MAP<std::string, cmFileTimeComparison_Type>
+ typedef std::unordered_map<std::string, cmFileTimeComparison_Type>
FileStatsMap;
FileStatsMap Files;
@@ -117,18 +116,22 @@ int cmFileTimeComparisonInternal::Compare(cmFileTimeComparison_Type* s1,
// Compare using nanosecond resolution.
if (s1->st_mtimespec.tv_sec < s2->st_mtimespec.tv_sec) {
return -1;
- } else if (s1->st_mtimespec.tv_sec > s2->st_mtimespec.tv_sec) {
+ }
+ if (s1->st_mtimespec.tv_sec > s2->st_mtimespec.tv_sec) {
return 1;
- } else if (s1->st_mtimespec.tv_nsec < s2->st_mtimespec.tv_nsec) {
+ }
+ if (s1->st_mtimespec.tv_nsec < s2->st_mtimespec.tv_nsec) {
return -1;
- } else if (s1->st_mtimespec.tv_nsec > s2->st_mtimespec.tv_nsec) {
+ }
+ if (s1->st_mtimespec.tv_nsec > s2->st_mtimespec.tv_nsec) {
return 1;
}
#else
// Compare using 1 second resolution.
if (s1->st_mtime < s2->st_mtime) {
return -1;
- } else if (s1->st_mtime > s2->st_mtime) {
+ }
+ if (s1->st_mtime > s2->st_mtime) {
return 1;
}
#endif
@@ -163,20 +166,20 @@ bool cmFileTimeComparisonInternal::TimesDiffer(cmFileTimeComparison_Type* s1,
long long t2 = s2->st_mtimespec.tv_sec * bil + s2->st_mtimespec.tv_nsec;
if (t1 < t2) {
return (t2 - t1) >= bil;
- } else if (t2 < t1) {
+ }
+ if (t2 < t1) {
return (t1 - t2) >= bil;
- } else {
- return false;
}
+ return false;
#else
// Times are integers in units of 1s.
if (s1->st_mtime < s2->st_mtime) {
return (s2->st_mtime - s1->st_mtime) >= 1;
- } else if (s1->st_mtime > s2->st_mtime) {
+ }
+ if (s1->st_mtime > s2->st_mtime) {
return (s1->st_mtime - s2->st_mtime) >= 1;
- } else {
- return false;
}
+ return false;
#endif
#else
// Times are integers in units of 100ns.
diff --git a/Source/cmFindBase.cxx b/Source/cmFindBase.cxx
index 10c6fe46f..417cdd25c 100644
--- a/Source/cmFindBase.cxx
+++ b/Source/cmFindBase.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmFindBase.h"
-#include "cmConfigure.h"
#include <deque>
#include <iostream>
#include <iterator>
@@ -281,10 +280,8 @@ void cmFindBase::FillUserHintsPath()
{
cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
- for (std::vector<std::string>::const_iterator p =
- this->UserHintsArgs.begin();
- p != this->UserHintsArgs.end(); ++p) {
- paths.AddUserPath(*p);
+ for (std::string const& p : this->UserHintsArgs) {
+ paths.AddUserPath(p);
}
paths.AddSuffixes(this->SearchPathSuffixes);
}
@@ -293,10 +290,8 @@ void cmFindBase::FillUserGuessPath()
{
cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
- for (std::vector<std::string>::const_iterator p =
- this->UserGuessArgs.begin();
- p != this->UserGuessArgs.end(); ++p) {
- paths.AddUserPath(*p);
+ for (std::string const& p : this->UserGuessArgs) {
+ paths.AddUserPath(p);
}
paths.AddSuffixes(this->SearchPathSuffixes);
}
@@ -335,7 +330,7 @@ bool cmFindBase::CheckForVariableInCache()
cmState* state = this->Makefile->GetState();
const char* cacheEntry = state->GetCacheEntryValue(this->VariableName);
bool found = !cmSystemTools::IsNOTFOUND(cacheValue);
- bool cached = cacheEntry != CM_NULLPTR;
+ bool cached = cacheEntry != nullptr;
if (found) {
// If the user specifies the entry on the command line without a
// type we should add the type and docstring but keep the
diff --git a/Source/cmFindCommon.cxx b/Source/cmFindCommon.cxx
index 4ef0f3ec1..814296201 100644
--- a/Source/cmFindCommon.cxx
+++ b/Source/cmFindCommon.cxx
@@ -155,10 +155,9 @@ void cmFindCommon::SelectDefaultMacMode()
void cmFindCommon::RerootPaths(std::vector<std::string>& paths)
{
#if 0
- for(std::vector<std::string>::const_iterator i = paths.begin();
- i != paths.end(); ++i)
+ for(std::string const& p : paths)
{
- fprintf(stderr, "[%s]\n", i->c_str());
+ fprintf(stderr, "[%s]\n", p.c_str());
}
#endif
// Short-circuit if there is nothing to do.
@@ -194,9 +193,8 @@ void cmFindCommon::RerootPaths(std::vector<std::string>& paths)
if (sysroot) {
roots.push_back(sysroot);
}
- for (std::vector<std::string>::iterator ri = roots.begin();
- ri != roots.end(); ++ri) {
- cmSystemTools::ConvertToUnixSlashes(*ri);
+ for (std::string& r : roots) {
+ cmSystemTools::ConvertToUnixSlashes(r);
}
const char* stagePrefix =
@@ -206,24 +204,22 @@ void cmFindCommon::RerootPaths(std::vector<std::string>& paths)
std::vector<std::string> unrootedPaths = paths;
paths.clear();
- for (std::vector<std::string>::const_iterator ri = roots.begin();
- ri != roots.end(); ++ri) {
- for (std::vector<std::string>::const_iterator ui = unrootedPaths.begin();
- ui != unrootedPaths.end(); ++ui) {
+ for (std::string const& r : roots) {
+ for (std::string const& up : unrootedPaths) {
// Place the unrooted path under the current root if it is not
// already inside. Skip the unrooted path if it is relative to
// a user home directory or is empty.
std::string rootedDir;
- if (cmSystemTools::IsSubDirectory(*ui, *ri) ||
- (stagePrefix && cmSystemTools::IsSubDirectory(*ui, stagePrefix))) {
- rootedDir = *ui;
- } else if (!ui->empty() && (*ui)[0] != '~') {
+ if (cmSystemTools::IsSubDirectory(up, r) ||
+ (stagePrefix && cmSystemTools::IsSubDirectory(up, stagePrefix))) {
+ rootedDir = up;
+ } else if (!up.empty() && up[0] != '~') {
// Start with the new root.
- rootedDir = *ri;
+ rootedDir = r;
rootedDir += "/";
// Append the original path with its old root removed.
- rootedDir += cmSystemTools::SplitPathRootComponent(*ui);
+ rootedDir += cmSystemTools::SplitPathRootComponent(up);
}
// Store the new path.
@@ -242,22 +238,21 @@ void cmFindCommon::GetIgnoredPaths(std::vector<std::string>& ignore)
{
// null-terminated list of paths.
static const char* paths[] = { "CMAKE_SYSTEM_IGNORE_PATH",
- "CMAKE_IGNORE_PATH", CM_NULLPTR };
+ "CMAKE_IGNORE_PATH", nullptr };
// Construct the list of path roots with no trailing slashes.
for (const char** pathName = paths; *pathName; ++pathName) {
// Get the list of paths to ignore from the variable.
const char* ignorePath = this->Makefile->GetDefinition(*pathName);
- if ((ignorePath == CM_NULLPTR) || (strlen(ignorePath) == 0)) {
+ if ((ignorePath == nullptr) || (strlen(ignorePath) == 0)) {
continue;
}
cmSystemTools::ExpandListArgument(ignorePath, ignore);
}
- for (std::vector<std::string>::iterator i = ignore.begin();
- i != ignore.end(); ++i) {
- cmSystemTools::ConvertToUnixSlashes(*i);
+ for (std::string& i : ignore) {
+ cmSystemTools::ConvertToUnixSlashes(i);
}
}
@@ -337,9 +332,8 @@ void cmFindCommon::ComputeFinalPaths()
// Combine the seperate path types, filtering out ignores
this->SearchPaths.clear();
std::vector<PathLabel>& allLabels = this->PathGroupLabelMap[PathGroup::All];
- for (std::vector<PathLabel>::const_iterator l = allLabels.begin();
- l != allLabels.end(); ++l) {
- this->LabeledPaths[*l].ExtractWithout(ignored, this->SearchPaths);
+ for (PathLabel const& l : allLabels) {
+ this->LabeledPaths[l].ExtractWithout(ignored, this->SearchPaths);
}
// Expand list of paths inside all search roots.
diff --git a/Source/cmFindCommon.h b/Source/cmFindCommon.h
index 72dcd355d..b237f1bd1 100644
--- a/Source/cmFindCommon.h
+++ b/Source/cmFindCommon.h
@@ -3,7 +3,7 @@
#ifndef cmFindCommon_h
#define cmFindCommon_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <map>
#include <set>
@@ -25,7 +25,7 @@ class cmFindCommon : public cmCommand
{
public:
cmFindCommon();
- ~cmFindCommon() CM_OVERRIDE;
+ ~cmFindCommon() override;
protected:
friend class cmSearchPath;
@@ -112,7 +112,7 @@ protected:
std::vector<std::string> SearchPathSuffixes;
- std::map<PathGroup, std::vector<PathLabel> > PathGroupLabelMap;
+ std::map<PathGroup, std::vector<PathLabel>> PathGroupLabelMap;
std::vector<PathGroup> PathGroupOrder;
std::map<std::string, PathLabel> PathLabelStringMap;
std::map<PathLabel, cmSearchPath> LabeledPaths;
diff --git a/Source/cmFindFileCommand.h b/Source/cmFindFileCommand.h
index bf57fecd3..430944942 100644
--- a/Source/cmFindFileCommand.h
+++ b/Source/cmFindFileCommand.h
@@ -3,7 +3,7 @@
#ifndef cmFindFileCommand_h
#define cmFindFileCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmFindPathCommand.h"
@@ -24,7 +24,7 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmFindFileCommand; }
+ cmCommand* Clone() override { return new cmFindFileCommand; }
};
#endif
diff --git a/Source/cmFindLibraryCommand.cxx b/Source/cmFindLibraryCommand.cxx
index a6b1a2155..758da2ce0 100644
--- a/Source/cmFindLibraryCommand.cxx
+++ b/Source/cmFindLibraryCommand.cxx
@@ -68,8 +68,8 @@ bool cmFindLibraryCommand::InitialPass(std::vector<std::string> const& argsIn,
this->AddArchitecturePaths("x32");
}
- std::string library = this->FindLibrary();
- if (library != "") {
+ std::string const library = this->FindLibrary();
+ if (!library.empty()) {
// Save the value in the cache
this->Makefile->AddCacheDefinition(this->VariableName, library.c_str(),
this->VariableDocumentation.c_str(),
@@ -87,9 +87,8 @@ void cmFindLibraryCommand::AddArchitecturePaths(const char* suffix)
{
std::vector<std::string> original;
original.swap(this->SearchPaths);
- for (std::vector<std::string>::const_iterator i = original.begin();
- i != original.end(); ++i) {
- this->AddArchitecturePath(*i, 0, suffix);
+ for (std::string const& o : original) {
+ this->AddArchitecturePath(o, 0, suffix);
}
}
@@ -254,15 +253,14 @@ cmFindLibraryHelper::cmFindLibraryHelper(cmMakefile* mf)
void cmFindLibraryHelper::RegexFromLiteral(std::string& out,
std::string const& in)
{
- for (std::string::const_iterator ci = in.begin(); ci != in.end(); ++ci) {
- char ch = *ci;
+ for (char ch : in) {
if (ch == '[' || ch == ']' || ch == '(' || ch == ')' || ch == '\\' ||
ch == '.' || ch == '*' || ch == '+' || ch == '?' || ch == '-' ||
ch == '^' || ch == '$') {
out += "\\";
}
#if defined(_WIN32) || defined(__APPLE__)
- out += tolower(ch);
+ out += static_cast<char>(tolower(ch));
#else
out += ch;
#endif
@@ -276,23 +274,20 @@ void cmFindLibraryHelper::RegexFromList(std::string& out,
// else and the result can be checked after matching.
out += "(";
const char* sep = "";
- for (std::vector<std::string>::const_iterator si = in.begin();
- si != in.end(); ++si) {
+ for (std::string const& s : in) {
// Separate from previous item.
out += sep;
sep = "|";
// Append this item.
- this->RegexFromLiteral(out, *si);
+ this->RegexFromLiteral(out, s);
}
out += ")";
}
bool cmFindLibraryHelper::HasValidSuffix(std::string const& name)
{
- for (std::vector<std::string>::const_iterator si = this->Suffixes.begin();
- si != this->Suffixes.end(); ++si) {
- std::string suffix = *si;
+ for (std::string suffix : this->Suffixes) {
if (name.length() <= suffix.length()) {
continue;
}
@@ -339,9 +334,8 @@ void cmFindLibraryHelper::SetName(std::string const& name)
bool cmFindLibraryHelper::CheckDirectory(std::string const& path)
{
- for (std::vector<Name>::iterator i = this->Names.begin();
- i != this->Names.end(); ++i) {
- if (this->CheckDirectoryForName(path, *i)) {
+ for (Name& i : this->Names) {
+ if (this->CheckDirectoryForName(path, i)) {
return true;
}
}
@@ -376,9 +370,7 @@ bool cmFindLibraryHelper::CheckDirectoryForName(std::string const& path,
std::string dir = path;
cmSystemTools::ConvertToUnixSlashes(dir);
std::set<std::string> const& files = this->GG->GetDirectoryContent(dir);
- for (std::set<std::string>::const_iterator fi = files.begin();
- fi != files.end(); ++fi) {
- std::string const& origName = *fi;
+ for (std::string const& origName : files) {
#if defined(_WIN32) || defined(__APPLE__)
std::string testName = cmSystemTools::LowerCase(origName);
#else
@@ -430,14 +422,12 @@ std::string cmFindLibraryCommand::FindNormalLibraryNamesPerDir()
{
// Search for all names in each directory.
cmFindLibraryHelper helper(this->Makefile);
- for (std::vector<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
- helper.AddName(*ni);
+ for (std::string const& n : this->Names) {
+ helper.AddName(n);
}
// Search every directory.
- for (std::vector<std::string>::const_iterator p = this->SearchPaths.begin();
- p != this->SearchPaths.end(); ++p) {
- if (helper.CheckDirectory(*p)) {
+ for (std::string const& sp : this->SearchPaths) {
+ if (helper.CheckDirectory(sp)) {
return helper.BestPath;
}
}
@@ -449,16 +439,13 @@ std::string cmFindLibraryCommand::FindNormalLibraryDirsPerName()
{
// Search the entire path for each name.
cmFindLibraryHelper helper(this->Makefile);
- for (std::vector<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
+ for (std::string const& n : this->Names) {
// Switch to searching for this name.
- helper.SetName(*ni);
+ helper.SetName(n);
// Search every directory.
- for (std::vector<std::string>::const_iterator p =
- this->SearchPaths.begin();
- p != this->SearchPaths.end(); ++p) {
- if (helper.CheckDirectory(*p)) {
+ for (std::string const& sp : this->SearchPaths) {
+ if (helper.CheckDirectory(sp)) {
return helper.BestPath;
}
}
@@ -479,12 +466,10 @@ std::string cmFindLibraryCommand::FindFrameworkLibraryNamesPerDir()
{
std::string fwPath;
// Search for all names in each search path.
- for (std::vector<std::string>::const_iterator di = this->SearchPaths.begin();
- di != this->SearchPaths.end(); ++di) {
- for (std::vector<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
- fwPath = *di;
- fwPath += *ni;
+ for (std::string const& d : this->SearchPaths) {
+ for (std::string const& n : this->Names) {
+ fwPath = d;
+ fwPath += n;
fwPath += ".framework";
if (cmSystemTools::FileIsDirectory(fwPath)) {
return cmSystemTools::CollapseFullPath(fwPath);
@@ -500,13 +485,10 @@ std::string cmFindLibraryCommand::FindFrameworkLibraryDirsPerName()
{
std::string fwPath;
// Search for each name in all search paths.
- for (std::vector<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
- for (std::vector<std::string>::const_iterator di =
- this->SearchPaths.begin();
- di != this->SearchPaths.end(); ++di) {
- fwPath = *di;
- fwPath += *ni;
+ for (std::string const& n : this->Names) {
+ for (std::string const& d : this->SearchPaths) {
+ fwPath = d;
+ fwPath += n;
fwPath += ".framework";
if (cmSystemTools::FileIsDirectory(fwPath)) {
return cmSystemTools::CollapseFullPath(fwPath);
diff --git a/Source/cmFindLibraryCommand.h b/Source/cmFindLibraryCommand.h
index 9d38eab33..fb8a7002d 100644
--- a/Source/cmFindLibraryCommand.h
+++ b/Source/cmFindLibraryCommand.h
@@ -3,7 +3,7 @@
#ifndef cmFindLibraryCommand_h
#define cmFindLibraryCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -27,14 +27,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmFindLibraryCommand; }
+ cmCommand* Clone() override { return new cmFindLibraryCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
protected:
void AddArchitecturePaths(const char* suffix);
diff --git a/Source/cmFindPackageCommand.cxx b/Source/cmFindPackageCommand.cxx
index 7797700d6..5a7265581 100644
--- a/Source/cmFindPackageCommand.cxx
+++ b/Source/cmFindPackageCommand.cxx
@@ -13,6 +13,7 @@
#include <deque>
#include <functional>
#include <iterator>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
#include <string.h>
@@ -24,7 +25,6 @@
#include "cmState.h"
#include "cmStateTypes.h"
#include "cmVersion.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
#if defined(__HAIKU__)
@@ -367,14 +367,12 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args,
if (!this->UseFindModules && !this->UseConfigFiles) {
std::ostringstream e;
e << "given options exclusive to Module mode:\n";
- for (std::set<unsigned int>::const_iterator si = moduleArgs.begin();
- si != moduleArgs.end(); ++si) {
- e << " " << args[*si] << "\n";
+ for (unsigned int si : moduleArgs) {
+ e << " " << args[si] << "\n";
}
e << "and options exclusive to Config mode:\n";
- for (std::set<unsigned int>::const_iterator si = configArgs.begin();
- si != configArgs.end(); ++si) {
- e << " " << args[*si] << "\n";
+ for (unsigned int si : configArgs) {
+ e << " " << args[si] << "\n";
}
e << "The options are incompatible.";
this->SetError(e.str());
@@ -518,13 +516,12 @@ bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args,
// Add the default configs.
if (this->Configs.empty()) {
- for (std::vector<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
- std::string config = *ni;
+ for (std::string const& n : this->Names) {
+ std::string config = n;
config += "Config.cmake";
this->Configs.push_back(config);
- config = cmSystemTools::LowerCase(*ni);
+ config = cmSystemTools::LowerCase(n);
config += "-config.cmake";
this->Configs.push_back(config);
}
@@ -611,14 +608,12 @@ void cmFindPackageCommand::AddFindDefinition(const std::string& var,
void cmFindPackageCommand::RestoreFindDefinitions()
{
- for (std::map<std::string, OriginalDef>::iterator i =
- this->OriginalDefs.begin();
- i != this->OriginalDefs.end(); ++i) {
- OriginalDef const& od = i->second;
+ for (auto const& i : this->OriginalDefs) {
+ OriginalDef const& od = i.second;
if (od.exists) {
- this->Makefile->AddDefinition(i->first, od.value.c_str());
+ this->Makefile->AddDefinition(i.first, od.value.c_str());
} else {
- this->Makefile->RemoveDefinition(i->first);
+ this->Makefile->RemoveDefinition(i.first);
}
}
}
@@ -874,13 +869,11 @@ bool cmFindPackageCommand::HandlePackageMode()
std::string consideredVersions;
const char* sep = "";
- for (std::vector<ConfigFileInfo>::const_iterator i =
- this->ConsideredConfigs.begin();
- i != this->ConsideredConfigs.end(); ++i) {
+ for (ConfigFileInfo const& i : this->ConsideredConfigs) {
consideredConfigFiles += sep;
consideredVersions += sep;
- consideredConfigFiles += i->filename;
- consideredVersions += i->version;
+ consideredConfigFiles += i.filename;
+ consideredVersions += i.version;
sep = ";";
}
@@ -946,9 +939,8 @@ bool cmFindPackageCommand::FindConfig()
bool cmFindPackageCommand::FindPrefixedConfig()
{
std::vector<std::string> const& prefixes = this->SearchPaths;
- for (std::vector<std::string>::const_iterator pi = prefixes.begin();
- pi != prefixes.end(); ++pi) {
- if (this->SearchPrefix(*pi)) {
+ for (std::string const& p : prefixes) {
+ if (this->SearchPrefix(p)) {
return true;
}
}
@@ -958,9 +950,8 @@ bool cmFindPackageCommand::FindPrefixedConfig()
bool cmFindPackageCommand::FindFrameworkConfig()
{
std::vector<std::string> const& prefixes = this->SearchPaths;
- for (std::vector<std::string>::const_iterator i = prefixes.begin();
- i != prefixes.end(); ++i) {
- if (this->SearchFrameworkPrefix(*i)) {
+ for (std::string const& p : prefixes) {
+ if (this->SearchFrameworkPrefix(p)) {
return true;
}
}
@@ -970,9 +961,8 @@ bool cmFindPackageCommand::FindFrameworkConfig()
bool cmFindPackageCommand::FindAppBundleConfig()
{
std::vector<std::string> const& prefixes = this->SearchPaths;
- for (std::vector<std::string>::const_iterator i = prefixes.begin();
- i != prefixes.end(); ++i) {
- if (this->SearchAppBundlePrefix(*i)) {
+ for (std::string const& p : prefixes) {
+ if (this->SearchAppBundlePrefix(p)) {
return true;
}
}
@@ -1171,14 +1161,12 @@ void cmFindPackageCommand::FillPrefixesSystemEnvironment()
// working directory.
std::vector<std::string> tmp;
cmSystemTools::GetPath(tmp);
- for (std::vector<std::string>::iterator i = tmp.begin(); i != tmp.end();
- ++i) {
+ for (std::string const& i : tmp) {
// If the path is a PREFIX/bin case then add its parent instead.
- if ((cmHasLiteralSuffix(*i, "/bin")) ||
- (cmHasLiteralSuffix(*i, "/sbin"))) {
- paths.AddPath(cmSystemTools::GetFilenamePath(*i));
+ if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
+ paths.AddPath(cmSystemTools::GetFilenamePath(i));
} else {
- paths.AddPath(*i);
+ paths.AddPath(i);
}
}
}
@@ -1296,9 +1284,8 @@ void cmFindPackageCommand::LoadPackageRegistryWin(bool user, unsigned int view,
if (user && !bad.empty() &&
RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
&hKey) == ERROR_SUCCESS) {
- for (std::set<std::wstring>::const_iterator vi = bad.begin();
- vi != bad.end(); ++vi) {
- RegDeleteValueW(hKey, vi->c_str());
+ for (std::wstring const& v : bad) {
+ RegDeleteValueW(hKey, v.c_str());
}
RegCloseKey(hKey);
}
@@ -1319,7 +1306,7 @@ public:
cmSystemTools::RemoveFile(this->File);
}
}
- void Release() { this->File = CM_NULLPTR; }
+ void Release() { this->File = nullptr; }
};
void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
@@ -1395,10 +1382,8 @@ void cmFindPackageCommand::FillPrefixesUserGuess()
{
cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
- for (std::vector<std::string>::const_iterator p =
- this->UserGuessArgs.begin();
- p != this->UserGuessArgs.end(); ++p) {
- paths.AddUserPath(*p);
+ for (std::string const& p : this->UserGuessArgs) {
+ paths.AddUserPath(p);
}
}
@@ -1406,10 +1391,8 @@ void cmFindPackageCommand::FillPrefixesUserHints()
{
cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
- for (std::vector<std::string>::const_iterator p =
- this->UserHintsArgs.begin();
- p != this->UserHintsArgs.end(); ++p) {
- paths.AddUserPath(*p);
+ for (std::string const& p : this->UserHintsArgs) {
+ paths.AddUserPath(p);
}
}
@@ -1418,12 +1401,10 @@ bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
assert(!dir.empty() && dir[dir.size() - 1] == '/');
// Check each path suffix on this directory.
- for (std::vector<std::string>::const_iterator si =
- this->SearchPathSuffixes.begin();
- si != this->SearchPathSuffixes.end(); ++si) {
+ for (std::string const& s : this->SearchPathSuffixes) {
std::string d = dir;
- if (!si->empty()) {
- d += *si;
+ if (!s.empty()) {
+ d += s;
d += "/";
}
if (this->CheckDirectory(d)) {
@@ -1454,11 +1435,10 @@ bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
return false;
}
- for (std::vector<std::string>::const_iterator ci = this->Configs.begin();
- ci != this->Configs.end(); ++ci) {
+ for (std::string const& c : this->Configs) {
file = dir;
file += "/";
- file += *ci;
+ file += c;
if (this->DebugMode) {
fprintf(stderr, "Checking file [%s]\n", file.c_str());
}
@@ -1631,10 +1611,10 @@ protected:
private:
bool Search(cmFileList&);
virtual bool Search(std::string const& parent, cmFileList&) = 0;
- virtual CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const = 0;
+ virtual std::unique_ptr<cmFileListGeneratorBase> Clone() const = 0;
friend class cmFileList;
cmFileListGeneratorBase* SetNext(cmFileListGeneratorBase const& next);
- CM_AUTO_PTR<cmFileListGeneratorBase> Next;
+ std::unique_ptr<cmFileListGeneratorBase> Next;
};
class cmFileList
@@ -1642,7 +1622,7 @@ class cmFileList
public:
cmFileList()
: First()
- , Last(CM_NULLPTR)
+ , Last(nullptr)
{
}
virtual ~cmFileList() {}
@@ -1658,7 +1638,7 @@ public:
}
bool Search()
{
- if (this->First.get()) {
+ if (this->First) {
return this->First->Search(*this);
}
return false;
@@ -1667,7 +1647,7 @@ public:
private:
virtual bool Visit(std::string const& fullPath) = 0;
friend class cmFileListGeneratorBase;
- CM_AUTO_PTR<cmFileListGeneratorBase> First;
+ std::unique_ptr<cmFileListGeneratorBase> First;
cmFileListGeneratorBase* Last;
};
@@ -1682,7 +1662,7 @@ public:
}
private:
- bool Visit(std::string const& fullPath) CM_OVERRIDE
+ bool Visit(std::string const& fullPath) override
{
if (this->UseSuffixes) {
return this->FPC->SearchDirectory(fullPath);
@@ -1708,7 +1688,7 @@ cmFileListGeneratorBase* cmFileListGeneratorBase::SetNext(
bool cmFileListGeneratorBase::Consider(std::string const& fullPath,
cmFileList& listing)
{
- if (this->Next.get()) {
+ if (this->Next) {
return this->Next->Search(fullPath + "/", listing);
}
return listing.Visit(fullPath + "/");
@@ -1730,14 +1710,14 @@ public:
private:
std::string String;
- bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE
+ bool Search(std::string const& parent, cmFileList& lister) override
{
std::string fullPath = parent + this->String;
return this->Consider(fullPath, lister);
}
- CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE
+ std::unique_ptr<cmFileListGeneratorBase> Clone() const override
{
- CM_AUTO_PTR<cmFileListGeneratorBase> g(
+ std::unique_ptr<cmFileListGeneratorBase> g(
new cmFileListGeneratorFixed(*this));
return g;
}
@@ -1759,19 +1739,18 @@ public:
private:
std::vector<std::string> const& Vector;
- bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE
+ bool Search(std::string const& parent, cmFileList& lister) override
{
- for (std::vector<std::string>::const_iterator i = this->Vector.begin();
- i != this->Vector.end(); ++i) {
- if (this->Consider(parent + *i, lister)) {
+ for (std::string const& i : this->Vector) {
+ if (this->Consider(parent + i, lister)) {
return true;
}
}
return false;
}
- CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE
+ std::unique_ptr<cmFileListGeneratorBase> Clone() const override
{
- CM_AUTO_PTR<cmFileListGeneratorBase> g(
+ std::unique_ptr<cmFileListGeneratorBase> g(
new cmFileListGeneratorEnumerate(*this));
return g;
}
@@ -1809,7 +1788,7 @@ protected:
private:
std::vector<std::string> const& Names;
- bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE
+ bool Search(std::string const& parent, cmFileList& lister) override
{
// Construct a list of matches.
std::vector<std::string> matches;
@@ -1820,9 +1799,8 @@ private:
if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
continue;
}
- for (std::vector<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
- if (cmsysString_strncasecmp(fname, ni->c_str(), ni->length()) == 0) {
+ for (std::string const& n : this->Names) {
+ if (cmsysString_strncasecmp(fname, n.c_str(), n.length()) == 0) {
matches.push_back(fname);
}
}
@@ -1835,17 +1813,16 @@ private:
SortDirection);
}
- for (std::vector<std::string>::const_iterator i = matches.begin();
- i != matches.end(); ++i) {
- if (this->Consider(parent + *i, lister)) {
+ for (std::string const& i : matches) {
+ if (this->Consider(parent + i, lister)) {
return true;
}
}
return false;
}
- CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE
+ std::unique_ptr<cmFileListGeneratorBase> Clone() const override
{
- CM_AUTO_PTR<cmFileListGeneratorBase> g(
+ std::unique_ptr<cmFileListGeneratorBase> g(
new cmFileListGeneratorProject(*this));
return g;
}
@@ -1871,7 +1848,7 @@ public:
private:
std::vector<std::string> const& Names;
std::string Extension;
- bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE
+ bool Search(std::string const& parent, cmFileList& lister) override
{
// Construct a list of matches.
std::vector<std::string> matches;
@@ -1882,9 +1859,7 @@ private:
if (strcmp(fname, ".") == 0 || strcmp(fname, "..") == 0) {
continue;
}
- for (std::vector<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
- std::string name = *ni;
+ for (std::string name : this->Names) {
name += this->Extension;
if (cmsysString_strcasecmp(fname, name.c_str()) == 0) {
matches.push_back(fname);
@@ -1892,17 +1867,16 @@ private:
}
}
- for (std::vector<std::string>::const_iterator i = matches.begin();
- i != matches.end(); ++i) {
- if (this->Consider(parent + *i, lister)) {
+ for (std::string const& i : matches) {
+ if (this->Consider(parent + i, lister)) {
return true;
}
}
return false;
}
- CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE
+ std::unique_ptr<cmFileListGeneratorBase> Clone() const override
{
- CM_AUTO_PTR<cmFileListGeneratorBase> g(
+ std::unique_ptr<cmFileListGeneratorBase> g(
new cmFileListGeneratorMacProject(*this));
return g;
}
@@ -1925,7 +1899,7 @@ public:
private:
std::string String;
- bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE
+ bool Search(std::string const& parent, cmFileList& lister) override
{
// Look for matching files.
std::vector<std::string> matches;
@@ -1944,9 +1918,9 @@ private:
}
return false;
}
- CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE
+ std::unique_ptr<cmFileListGeneratorBase> Clone() const override
{
- CM_AUTO_PTR<cmFileListGeneratorBase> g(
+ std::unique_ptr<cmFileListGeneratorBase> g(
new cmFileListGeneratorCaseInsensitive(*this));
return g;
}
@@ -1968,7 +1942,7 @@ public:
private:
std::string Pattern;
- bool Search(std::string const& parent, cmFileList& lister) CM_OVERRIDE
+ bool Search(std::string const& parent, cmFileList& lister) override
{
// Glob the set of matching files.
std::string expr = parent;
@@ -1980,20 +1954,18 @@ private:
std::vector<std::string> const& files = g.GetFiles();
// Look for directories among the matches.
- for (std::vector<std::string>::const_iterator fi = files.begin();
- fi != files.end(); ++fi) {
- if (cmSystemTools::FileIsDirectory(*fi)) {
- if (this->Consider(*fi, lister)) {
+ for (std::string const& f : files) {
+ if (cmSystemTools::FileIsDirectory(f)) {
+ if (this->Consider(f, lister)) {
return true;
}
}
}
return false;
}
- CM_AUTO_PTR<cmFileListGeneratorBase> Clone() const CM_OVERRIDE
+ std::unique_ptr<cmFileListGeneratorBase> Clone() const override
{
- CM_AUTO_PTR<cmFileListGeneratorBase> g(new cmFileListGeneratorGlob(*this));
- return g;
+ return cm::make_unique<cmFileListGeneratorGlob>(*this);
}
};
diff --git a/Source/cmFindPackageCommand.h b/Source/cmFindPackageCommand.h
index 99b0059ba..150a51d14 100644
--- a/Source/cmFindPackageCommand.h
+++ b/Source/cmFindPackageCommand.h
@@ -3,7 +3,7 @@
#ifndef cmFindPackageCommand_h
#define cmFindPackageCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cm_kwiml.h"
#include <map>
@@ -51,14 +51,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmFindPackageCommand; }
+ cmCommand* Clone() override { return new cmFindPackageCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
class PathLabel : public cmFindCommon::PathLabel
diff --git a/Source/cmFindPathCommand.cxx b/Source/cmFindPathCommand.cxx
index d3541ca94..ea2641001 100644
--- a/Source/cmFindPathCommand.cxx
+++ b/Source/cmFindPathCommand.cxx
@@ -85,7 +85,7 @@ std::string cmFindPathCommand::FindHeaderInFramework(std::string const& file,
// if the framework has a path in it then just use the filename
if (frameWorkName.find('/') != std::string::npos) {
fileName = file;
- frameWorkName = "";
+ frameWorkName.clear();
}
if (!frameWorkName.empty()) {
std::string fpath = dir;
@@ -124,18 +124,15 @@ std::string cmFindPathCommand::FindHeaderInFramework(std::string const& file,
std::string cmFindPathCommand::FindNormalHeader()
{
std::string tryPath;
- for (std::vector<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
- for (std::vector<std::string>::const_iterator p =
- this->SearchPaths.begin();
- p != this->SearchPaths.end(); ++p) {
- tryPath = *p;
- tryPath += *ni;
+ for (std::string const& n : this->Names) {
+ for (std::string const& sp : this->SearchPaths) {
+ tryPath = sp;
+ tryPath += n;
if (cmSystemTools::FileExists(tryPath.c_str())) {
if (this->IncludeFileInPath) {
return tryPath;
}
- return *p;
+ return sp;
}
}
}
@@ -144,12 +141,9 @@ std::string cmFindPathCommand::FindNormalHeader()
std::string cmFindPathCommand::FindFrameworkHeader()
{
- for (std::vector<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
- for (std::vector<std::string>::const_iterator p =
- this->SearchPaths.begin();
- p != this->SearchPaths.end(); ++p) {
- std::string fwPath = this->FindHeaderInFramework(*ni, *p);
+ for (std::string const& n : this->Names) {
+ for (std::string const& sp : this->SearchPaths) {
+ std::string fwPath = this->FindHeaderInFramework(n, sp);
if (!fwPath.empty()) {
return fwPath;
}
diff --git a/Source/cmFindPathCommand.h b/Source/cmFindPathCommand.h
index 3761145b2..cb0db4c46 100644
--- a/Source/cmFindPathCommand.h
+++ b/Source/cmFindPathCommand.h
@@ -3,7 +3,7 @@
#ifndef cmFindPathCommand_h
#define cmFindPathCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -27,14 +27,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmFindPathCommand; }
+ cmCommand* Clone() override { return new cmFindPathCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
bool IncludeFileInPath;
diff --git a/Source/cmFindProgramCommand.cxx b/Source/cmFindProgramCommand.cxx
index 9327c1805..2059b3d65 100644
--- a/Source/cmFindProgramCommand.cxx
+++ b/Source/cmFindProgramCommand.cxx
@@ -45,9 +45,8 @@ struct cmFindProgramHelper
}
bool CheckDirectory(std::string const& path)
{
- for (std::vector<std::string>::iterator i = this->Names.begin();
- i != this->Names.end(); ++i) {
- if (this->CheckDirectoryForName(path, *i)) {
+ for (std::string const& n : this->Names) {
+ if (this->CheckDirectoryForName(path, n)) {
return true;
}
}
@@ -55,14 +54,13 @@ struct cmFindProgramHelper
}
bool CheckDirectoryForName(std::string const& path, std::string const& name)
{
- for (std::vector<std::string>::iterator ext = this->Extensions.begin();
- ext != this->Extensions.end(); ++ext) {
+ for (std::string const& ext : this->Extensions) {
this->TestPath = path;
this->TestPath += name;
- if (!ext->empty() && cmSystemTools::StringEndsWith(name, ext->c_str())) {
+ if (!ext.empty() && cmSystemTools::StringEndsWith(name, ext.c_str())) {
continue;
}
- this->TestPath += *ext;
+ this->TestPath += ext;
if (cmSystemTools::FileExists(this->TestPath, true)) {
this->BestPath = cmSystemTools::CollapseFullPath(this->TestPath);
return true;
@@ -99,8 +97,8 @@ bool cmFindProgramCommand::InitialPass(std::vector<std::string> const& argsIn,
return true;
}
- std::string result = FindProgram();
- if (result != "") {
+ std::string const result = FindProgram();
+ if (!result.empty()) {
// Save the value in the cache
this->Makefile->AddCacheDefinition(this->VariableName, result.c_str(),
this->VariableDocumentation.c_str(),
@@ -143,9 +141,8 @@ std::string cmFindProgramCommand::FindNormalProgramNamesPerDir()
{
// Search for all names in each directory.
cmFindProgramHelper helper;
- for (std::vector<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
- helper.AddName(*ni);
+ for (std::string const& n : this->Names) {
+ helper.AddName(n);
}
// Check for the names themselves (e.g. absolute paths).
@@ -154,9 +151,8 @@ std::string cmFindProgramCommand::FindNormalProgramNamesPerDir()
}
// Search every directory.
- for (std::vector<std::string>::const_iterator p = this->SearchPaths.begin();
- p != this->SearchPaths.end(); ++p) {
- if (helper.CheckDirectory(*p)) {
+ for (std::string const& sp : this->SearchPaths) {
+ if (helper.CheckDirectory(sp)) {
return helper.BestPath;
}
}
@@ -168,10 +164,9 @@ std::string cmFindProgramCommand::FindNormalProgramDirsPerName()
{
// Search the entire path for each name.
cmFindProgramHelper helper;
- for (std::vector<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
+ for (std::string const& n : this->Names) {
// Switch to searching for this name.
- helper.SetName(*ni);
+ helper.SetName(n);
// Check for the name by itself (e.g. an absolute path).
if (helper.CheckDirectory(std::string())) {
@@ -179,10 +174,8 @@ std::string cmFindProgramCommand::FindNormalProgramDirsPerName()
}
// Search every directory.
- for (std::vector<std::string>::const_iterator p =
- this->SearchPaths.begin();
- p != this->SearchPaths.end(); ++p) {
- if (helper.CheckDirectory(*p)) {
+ for (std::string const& sp : this->SearchPaths) {
+ if (helper.CheckDirectory(sp)) {
return helper.BestPath;
}
}
@@ -193,10 +186,9 @@ std::string cmFindProgramCommand::FindNormalProgramDirsPerName()
std::string cmFindProgramCommand::FindAppBundle()
{
- for (std::vector<std::string>::const_iterator name = this->Names.begin();
- name != this->Names.end(); ++name) {
+ for (std::string const& name : this->Names) {
- std::string appName = *name + std::string(".app");
+ std::string appName = name + std::string(".app");
std::string appPath =
cmSystemTools::FindDirectory(appName, this->SearchPaths, true);
@@ -237,7 +229,7 @@ std::string cmFindProgramCommand::GetBundleExecutable(
// returned executableURL is relative to <appbundle>/Contents/MacOS/
CFURLRef executableURL = CFBundleCopyExecutableURL(appBundle);
- if (executableURL != NULL) {
+ if (executableURL != nullptr) {
const int MAX_OSX_PATH_SIZE = 1024;
char buffer[MAX_OSX_PATH_SIZE];
diff --git a/Source/cmFindProgramCommand.h b/Source/cmFindProgramCommand.h
index b0cd42096..147936cc0 100644
--- a/Source/cmFindProgramCommand.h
+++ b/Source/cmFindProgramCommand.h
@@ -3,7 +3,7 @@
#ifndef cmFindProgramCommand_h
#define cmFindProgramCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -28,14 +28,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmFindProgramCommand; }
+ cmCommand* Clone() override { return new cmFindProgramCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
std::string FindProgram();
diff --git a/Source/cmForEachCommand.cxx b/Source/cmForEachCommand.cxx
index 8346b2309..542a86025 100644
--- a/Source/cmForEachCommand.cxx
+++ b/Source/cmForEachCommand.cxx
@@ -2,6 +2,7 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmForEachCommand.h"
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
@@ -9,7 +10,6 @@
#include "cmExecutionStatus.h"
#include "cmMakefile.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
cmForEachFunctionBlocker::cmForEachFunctionBlocker(cmMakefile* mf)
@@ -35,7 +35,8 @@ bool cmForEachFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
// if this is the endofreach for this statement
if (!this->Depth) {
// Remove the function blocker for this scope or bail.
- CM_AUTO_PTR<cmFunctionBlocker> fb(mf.RemoveFunctionBlocker(this, lff));
+ std::unique_ptr<cmFunctionBlocker> fb(
+ mf.RemoveFunctionBlocker(this, lff));
if (!fb.get()) {
return false;
}
@@ -54,9 +55,9 @@ bool cmForEachFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
mf.AddDefinition(this->Args[0], j->c_str());
// Invoke all the functions that were collected in the block.
cmExecutionStatus status;
- for (unsigned int c = 0; c < this->Functions.size(); ++c) {
+ for (cmListFileFunction const& func : this->Functions) {
status.Clear();
- mf.ExecuteCommand(this->Functions[c], status);
+ mf.ExecuteCommand(func, status);
if (status.GetReturnInvoked()) {
inStatus.SetReturnInvoked();
// restore the variable to its prior value
@@ -181,7 +182,7 @@ bool cmForEachCommand::InitialPass(std::vector<std::string> const& args,
bool cmForEachCommand::HandleInMode(std::vector<std::string> const& args)
{
- CM_AUTO_PTR<cmForEachFunctionBlocker> f(
+ std::unique_ptr<cmForEachFunctionBlocker> f(
new cmForEachFunctionBlocker(this->Makefile));
f->Args.push_back(args[0]);
@@ -213,7 +214,7 @@ bool cmForEachCommand::HandleInMode(std::vector<std::string> const& args)
}
}
- this->Makefile->AddFunctionBlocker(f.release()); // TODO: pass auto_ptr
+ this->Makefile->AddFunctionBlocker(f.release()); // TODO: pass unique_ptr
return true;
}
diff --git a/Source/cmForEachCommand.h b/Source/cmForEachCommand.h
index 7c8a6d836..5131a4f18 100644
--- a/Source/cmForEachCommand.h
+++ b/Source/cmForEachCommand.h
@@ -3,7 +3,7 @@
#ifndef cmForEachCommand_h
#define cmForEachCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -19,10 +19,10 @@ class cmForEachFunctionBlocker : public cmFunctionBlocker
{
public:
cmForEachFunctionBlocker(cmMakefile* mf);
- ~cmForEachFunctionBlocker() CM_OVERRIDE;
+ ~cmForEachFunctionBlocker() override;
bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf,
- cmExecutionStatus&) CM_OVERRIDE;
- bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) CM_OVERRIDE;
+ cmExecutionStatus&) override;
+ bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) override;
std::vector<std::string> Args;
std::vector<cmListFileFunction> Functions;
@@ -39,14 +39,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmForEachCommand; }
+ cmCommand* Clone() override { return new cmForEachCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
bool HandleInMode(std::vector<std::string> const& args);
diff --git a/Source/cmFortranParser.h b/Source/cmFortranParser.h
index d8b002309..3f5ad8744 100644
--- a/Source/cmFortranParser.h
+++ b/Source/cmFortranParser.h
@@ -4,7 +4,7 @@
#define cmFortranParser_h
#if !defined(cmFortranLexer_cxx) && !defined(cmFortranParser_cxx)
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <set>
#include <string>
diff --git a/Source/cmFortranParserImpl.cxx b/Source/cmFortranParserImpl.cxx
index 4e23f3691..81f1286d2 100644
--- a/Source/cmFortranParserImpl.cxx
+++ b/Source/cmFortranParserImpl.cxx
@@ -3,7 +3,6 @@
#include "cmFortranParser.h"
#include "cmSystemTools.h"
-#include "cmConfigure.h"
#include <assert.h>
#include <set>
#include <stack>
@@ -31,9 +30,8 @@ bool cmFortranParser_s::FindIncludeFile(const char* dir,
}
// Search the include path for the file.
- for (std::vector<std::string>::const_iterator i = this->IncludePath.begin();
- i != this->IncludePath.end(); ++i) {
- fullName = *i;
+ for (std::string const& i : this->IncludePath) {
+ fullName = i;
fullName += "/";
fullName += includeName;
if (cmSystemTools::FileExists(fullName.c_str(), true)) {
@@ -61,7 +59,7 @@ cmFortranParser_s::cmFortranParser_s(std::vector<std::string> const& includes,
// Create a dummy buffer that is never read but is the fallback
// buffer when the last file is popped off the stack.
YY_BUFFER_STATE buffer =
- cmFortran_yy_create_buffer(CM_NULLPTR, 4, this->Scanner);
+ cmFortran_yy_create_buffer(nullptr, 4, this->Scanner);
cmFortran_yy_switch_to_buffer(buffer, this->Scanner);
}
@@ -79,7 +77,7 @@ bool cmFortranParser_FilePush(cmFortranParser* parser, const char* fname)
std::string dir = cmSystemTools::GetParentDirectory(fname);
cmFortranFile f(file, current, dir);
YY_BUFFER_STATE buffer =
- cmFortran_yy_create_buffer(CM_NULLPTR, 16384, parser->Scanner);
+ cmFortran_yy_create_buffer(nullptr, 16384, parser->Scanner);
cmFortran_yy_switch_to_buffer(buffer, parser->Scanner);
parser->FileStack.push(f);
return true;
@@ -121,14 +119,14 @@ int cmFortranParser_Input(cmFortranParser* parser, char* buffer,
n = 1;
ff.LastCharWasNewline = true;
}
- return (int)n;
+ return static_cast<int>(n);
}
return 0;
}
void cmFortranParser_StringStart(cmFortranParser* parser)
{
- parser->TokenString = "";
+ parser->TokenString.clear();
}
const char* cmFortranParser_StringEnd(cmFortranParser* parser)
diff --git a/Source/cmFunctionCommand.cxx b/Source/cmFunctionCommand.cxx
index ee52bde37..774df849c 100644
--- a/Source/cmFunctionCommand.cxx
+++ b/Source/cmFunctionCommand.cxx
@@ -18,12 +18,12 @@ public:
cmFunctionHelperCommand() {}
///! clean up any memory allocated by the function
- ~cmFunctionHelperCommand() CM_OVERRIDE {}
+ ~cmFunctionHelperCommand() override {}
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmFunctionHelperCommand* newC = new cmFunctionHelperCommand;
// we must copy when we clone
@@ -39,10 +39,10 @@ public:
* the CMakeLists.txt file.
*/
bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
- cmExecutionStatus&) CM_OVERRIDE;
+ cmExecutionStatus&) override;
bool InitialPass(std::vector<std::string> const&,
- cmExecutionStatus&) CM_OVERRIDE
+ cmExecutionStatus&) override
{
return false;
}
@@ -104,9 +104,9 @@ bool cmFunctionHelperCommand::InvokeInitialPass(
// Invoke all the functions that were collected in the block.
// for each function
- for (unsigned int c = 0; c < this->Functions.size(); ++c) {
+ for (cmListFileFunction const& func : this->Functions) {
cmExecutionStatus status;
- if (!this->Makefile->ExecuteCommand(this->Functions[c], status) ||
+ if (!this->Makefile->ExecuteCommand(func, status) ||
status.GetNestedError()) {
// The error message should have already included the call stack
// so we do not need to report an error here.
diff --git a/Source/cmFunctionCommand.h b/Source/cmFunctionCommand.h
index f26312632..3352b9235 100644
--- a/Source/cmFunctionCommand.h
+++ b/Source/cmFunctionCommand.h
@@ -3,7 +3,7 @@
#ifndef cmFunctionCommand_h
#define cmFunctionCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -19,10 +19,10 @@ class cmFunctionFunctionBlocker : public cmFunctionBlocker
{
public:
cmFunctionFunctionBlocker() { this->Depth = 0; }
- ~cmFunctionFunctionBlocker() CM_OVERRIDE {}
+ ~cmFunctionFunctionBlocker() override {}
bool IsFunctionBlocked(const cmListFileFunction&, cmMakefile& mf,
- cmExecutionStatus&) CM_OVERRIDE;
- bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf) CM_OVERRIDE;
+ cmExecutionStatus&) override;
+ bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf) override;
std::vector<std::string> Args;
std::vector<cmListFileFunction> Functions;
@@ -36,14 +36,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmFunctionCommand; }
+ cmCommand* Clone() override { return new cmFunctionCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmGeneratedFileStream.h b/Source/cmGeneratedFileStream.h
index 56f9988ff..a96f38fa8 100644
--- a/Source/cmGeneratedFileStream.h
+++ b/Source/cmGeneratedFileStream.h
@@ -3,7 +3,7 @@
#ifndef cmGeneratedFileStream_h
#define cmGeneratedFileStream_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cm_codecvt.hxx"
#include "cmsys/FStream.hxx"
@@ -94,7 +94,7 @@ public:
* file was successfully written before allowing the original to be
* replaced.
*/
- ~cmGeneratedFileStream() CM_OVERRIDE;
+ ~cmGeneratedFileStream() override;
/**
* Open an output file by name. This should be used only with a
diff --git a/Source/cmGeneratorExpression.cxx b/Source/cmGeneratorExpression.cxx
index 00b5ff4ef..86991c1c5 100644
--- a/Source/cmGeneratorExpression.cxx
+++ b/Source/cmGeneratorExpression.cxx
@@ -3,6 +3,7 @@
#include "cmGeneratorExpression.h"
#include "cmsys/RegularExpression.hxx"
+#include <memory> // IWYU pragma: keep
#include <utility>
#include "assert.h"
@@ -12,7 +13,6 @@
#include "cmGeneratorExpressionLexer.h"
#include "cmGeneratorExpressionParser.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
cmGeneratorExpression::cmGeneratorExpression(
const cmListFileBacktrace& backtrace)
@@ -20,14 +20,14 @@ cmGeneratorExpression::cmGeneratorExpression(
{
}
-CM_AUTO_PTR<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse(
+std::unique_ptr<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse(
std::string const& input)
{
- return CM_AUTO_PTR<cmCompiledGeneratorExpression>(
+ return std::unique_ptr<cmCompiledGeneratorExpression>(
new cmCompiledGeneratorExpression(this->Backtrace, input));
}
-CM_AUTO_PTR<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse(
+std::unique_ptr<cmCompiledGeneratorExpression> cmGeneratorExpression::Parse(
const char* input)
{
return this->Parse(std::string(input ? input : ""));
@@ -68,7 +68,7 @@ const char* cmCompiledGeneratorExpression::EvaluateWithContext(
return this->Input.c_str();
}
- this->Output = "";
+ this->Output.clear();
std::vector<cmGeneratorExpressionEvaluator*>::const_iterator it =
this->Evaluators.begin();
@@ -81,7 +81,7 @@ const char* cmCompiledGeneratorExpression::EvaluateWithContext(
this->SeenTargetProperties.insert(context.SeenTargetProperties.begin(),
context.SeenTargetProperties.end());
if (context.HadError) {
- this->Output = "";
+ this->Output.clear();
break;
}
}
@@ -199,15 +199,14 @@ static void prefixItems(const std::string& content, std::string& result,
std::vector<std::string> entries;
cmGeneratorExpression::Split(content, entries);
const char* sep = "";
- for (std::vector<std::string>::const_iterator ei = entries.begin();
- ei != entries.end(); ++ei) {
+ for (std::string const& e : entries) {
result += sep;
sep = ";";
- if (!cmSystemTools::FileIsFullPath(ei->c_str()) &&
- cmGeneratorExpression::Find(*ei) != 0) {
+ if (!cmSystemTools::FileIsFullPath(e.c_str()) &&
+ cmGeneratorExpression::Find(e) != 0) {
result += prefix;
}
- result += *ei;
+ result += e;
}
}
@@ -297,7 +296,7 @@ void cmGeneratorExpression::Split(const std::string& input,
std::string::size_type startPos = input.rfind(';', pos);
if (startPos == std::string::npos) {
preGenex = part;
- part = "";
+ part.clear();
} else if (startPos != pos - 1 && startPos >= lastPos) {
part = input.substr(lastPos, startPos - lastPos);
preGenex = input.substr(startPos + 1, pos - startPos - 1);
@@ -379,7 +378,7 @@ void cmCompiledGeneratorExpression::GetMaxLanguageStandard(
const cmGeneratorTarget* tgt, std::map<std::string, std::string>& mapping)
{
typedef std::map<cmGeneratorTarget const*,
- std::map<std::string, std::string> >
+ std::map<std::string, std::string>>
MapType;
MapType::const_iterator it = this->MaxLanguageStandard.find(tgt);
if (it != this->MaxLanguageStandard.end()) {
diff --git a/Source/cmGeneratorExpression.h b/Source/cmGeneratorExpression.h
index 34516f5c5..cface0d70 100644
--- a/Source/cmGeneratorExpression.h
+++ b/Source/cmGeneratorExpression.h
@@ -3,12 +3,12 @@
#ifndef cmGeneratorExpression_h
#define cmGeneratorExpression_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmListFileCache.h"
-#include "cm_auto_ptr.hxx"
#include <map>
+#include <memory> // IWYU pragma: keep
#include <set>
#include <string>
#include <vector>
@@ -39,8 +39,9 @@ public:
cmListFileBacktrace const& backtrace = cmListFileBacktrace());
~cmGeneratorExpression();
- CM_AUTO_PTR<cmCompiledGeneratorExpression> Parse(std::string const& input);
- CM_AUTO_PTR<cmCompiledGeneratorExpression> Parse(const char* input);
+ std::unique_ptr<cmCompiledGeneratorExpression> Parse(
+ std::string const& input);
+ std::unique_ptr<cmCompiledGeneratorExpression> Parse(const char* input);
enum PreprocessContext
{
@@ -71,12 +72,12 @@ class cmCompiledGeneratorExpression
CM_DISABLE_COPY(cmCompiledGeneratorExpression)
public:
- const char* Evaluate(
- cmLocalGenerator* lg, const std::string& config, bool quiet = false,
- cmGeneratorTarget const* headTarget = CM_NULLPTR,
- cmGeneratorTarget const* currentTarget = CM_NULLPTR,
- cmGeneratorExpressionDAGChecker* dagChecker = CM_NULLPTR,
- std::string const& language = std::string()) const;
+ const char* Evaluate(cmLocalGenerator* lg, const std::string& config,
+ bool quiet = false,
+ cmGeneratorTarget const* headTarget = nullptr,
+ cmGeneratorTarget const* currentTarget = nullptr,
+ cmGeneratorExpressionDAGChecker* dagChecker = nullptr,
+ std::string const& language = std::string()) const;
const char* Evaluate(cmLocalGenerator* lg, const std::string& config,
bool quiet, cmGeneratorTarget const* headTarget,
cmGeneratorExpressionDAGChecker* dagChecker,
@@ -143,7 +144,7 @@ private:
mutable std::set<cmGeneratorTarget const*> AllTargetsSeen;
mutable std::set<std::string> SeenTargetProperties;
mutable std::map<cmGeneratorTarget const*,
- std::map<std::string, std::string> >
+ std::map<std::string, std::string>>
MaxLanguageStandard;
mutable std::string Output;
mutable bool HadContextSensitiveCondition;
diff --git a/Source/cmGeneratorExpressionContext.h b/Source/cmGeneratorExpressionContext.h
index cf292dcef..5b0123ec8 100644
--- a/Source/cmGeneratorExpressionContext.h
+++ b/Source/cmGeneratorExpressionContext.h
@@ -26,7 +26,7 @@ struct cmGeneratorExpressionContext
std::set<cmGeneratorTarget const*> AllTargets;
std::set<std::string> SeenTargetProperties;
std::set<cmGeneratorTarget const*> SourceSensitiveTargets;
- std::map<cmGeneratorTarget const*, std::map<std::string, std::string> >
+ std::map<cmGeneratorTarget const*, std::map<std::string, std::string>>
MaxLanguageStandard;
cmLocalGenerator* LG;
std::string Config;
diff --git a/Source/cmGeneratorExpressionDAGChecker.cxx b/Source/cmGeneratorExpressionDAGChecker.cxx
index c0266311b..f0eafb46a 100644
--- a/Source/cmGeneratorExpressionDAGChecker.cxx
+++ b/Source/cmGeneratorExpressionDAGChecker.cxx
@@ -58,7 +58,7 @@ void cmGeneratorExpressionDAGChecker::Initialize()
TEST_TRANSITIVE_PROPERTY_METHOD) false)) // NOLINT(clang-tidy)
#undef TEST_TRANSITIVE_PROPERTY_METHOD
{
- std::map<std::string, std::set<std::string> >::const_iterator it =
+ std::map<std::string, std::set<std::string>>::const_iterator it =
top->Seen.find(this->Target);
if (it != top->Seen.end()) {
const std::set<std::string>& propSet = it->second;
diff --git a/Source/cmGeneratorExpressionDAGChecker.h b/Source/cmGeneratorExpressionDAGChecker.h
index 557a19220..3f73fca8a 100644
--- a/Source/cmGeneratorExpressionDAGChecker.h
+++ b/Source/cmGeneratorExpressionDAGChecker.h
@@ -3,7 +3,7 @@
#ifndef cmGeneratorExpressionDAGChecker_h
#define cmGeneratorExpressionDAGChecker_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmListFileCache.h"
@@ -61,7 +61,7 @@ struct cmGeneratorExpressionDAGChecker
void ReportError(cmGeneratorExpressionContext* context,
const std::string& expr);
- bool EvaluatingLinkLibraries(const char* tgt = CM_NULLPTR);
+ bool EvaluatingLinkLibraries(const char* tgt = nullptr);
#define DECLARE_TRANSITIVE_PROPERTY_METHOD(METHOD) bool METHOD() const;
@@ -82,7 +82,7 @@ private:
const cmGeneratorExpressionDAGChecker* const Parent;
const std::string Target;
const std::string Property;
- std::map<std::string, std::set<std::string> > Seen;
+ std::map<std::string, std::set<std::string>> Seen;
const GeneratorExpressionContent* const Content;
const cmListFileBacktrace Backtrace;
Result CheckResult;
diff --git a/Source/cmGeneratorExpressionEvaluationFile.cxx b/Source/cmGeneratorExpressionEvaluationFile.cxx
index 15264545b..87b6b342d 100644
--- a/Source/cmGeneratorExpressionEvaluationFile.cxx
+++ b/Source/cmGeneratorExpressionEvaluationFile.cxx
@@ -2,8 +2,8 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGeneratorExpressionEvaluationFile.h"
-#include "cmConfigure.h"
#include "cmsys/FStream.hxx"
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <utility>
@@ -14,17 +14,18 @@
#include "cmMakefile.h"
#include "cmSourceFile.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
cmGeneratorExpressionEvaluationFile::cmGeneratorExpressionEvaluationFile(
const std::string& input,
- CM_AUTO_PTR<cmCompiledGeneratorExpression> outputFileExpr,
- CM_AUTO_PTR<cmCompiledGeneratorExpression> condition, bool inputIsContent)
+ std::unique_ptr<cmCompiledGeneratorExpression> outputFileExpr,
+ std::unique_ptr<cmCompiledGeneratorExpression> condition,
+ bool inputIsContent, cmPolicies::PolicyStatus policyStatusCMP0070)
: Input(input)
- , OutputFileExpr(outputFileExpr)
- , Condition(condition)
+ , OutputFileExpr(std::move(outputFileExpr))
+ , Condition(std::move(condition))
, InputIsContent(inputIsContent)
+ , PolicyStatusCMP0070(policyStatusCMP0070)
{
}
@@ -36,7 +37,7 @@ void cmGeneratorExpressionEvaluationFile::Generate(
std::string rawCondition = this->Condition->GetInput();
if (!rawCondition.empty()) {
std::string condResult = this->Condition->Evaluate(
- lg, config, false, CM_NULLPTR, CM_NULLPTR, CM_NULLPTR, lang);
+ lg, config, false, nullptr, nullptr, nullptr, lang);
if (condResult == "0") {
return;
}
@@ -51,10 +52,16 @@ void cmGeneratorExpressionEvaluationFile::Generate(
}
}
- const std::string outputFileName = this->OutputFileExpr->Evaluate(
- lg, config, false, CM_NULLPTR, CM_NULLPTR, CM_NULLPTR, lang);
+ std::string outputFileName = this->OutputFileExpr->Evaluate(
+ lg, config, false, nullptr, nullptr, nullptr, lang);
const std::string outputContent = inputExpression->Evaluate(
- lg, config, false, CM_NULLPTR, CM_NULLPTR, CM_NULLPTR, lang);
+ lg, config, false, nullptr, nullptr, nullptr, lang);
+
+ if (cmSystemTools::FileIsFullPath(outputFileName)) {
+ outputFileName = cmSystemTools::CollapseFullPath(outputFileName);
+ } else {
+ outputFileName = this->FixRelativePath(outputFileName, PathForOutput, lg);
+ }
std::map<std::string, std::string>::iterator it =
outputFiles.find(outputFileName);
@@ -92,10 +99,9 @@ void cmGeneratorExpressionEvaluationFile::CreateOutputFile(
cmGlobalGenerator* gg = lg->GetGlobalGenerator();
gg->GetEnabledLanguages(enabledLanguages);
- for (std::vector<std::string>::const_iterator le = enabledLanguages.begin();
- le != enabledLanguages.end(); ++le) {
+ for (std::string const& le : enabledLanguages) {
std::string name = this->OutputFileExpr->Evaluate(
- lg, config, false, CM_NULLPTR, CM_NULLPTR, CM_NULLPTR, *le);
+ lg, config, false, nullptr, nullptr, nullptr, le);
cmSourceFile* sf = lg->GetMakefile()->GetOrCreateSource(name);
sf->SetProperty("GENERATED", "1");
@@ -111,12 +117,18 @@ void cmGeneratorExpressionEvaluationFile::Generate(cmLocalGenerator* lg)
if (this->InputIsContent) {
inputContent = this->Input;
} else {
- lg->GetMakefile()->AddCMakeDependFile(this->Input);
- cmSystemTools::GetPermissions(this->Input.c_str(), perm);
- cmsys::ifstream fin(this->Input.c_str());
+ std::string inputFileName = this->Input;
+ if (cmSystemTools::FileIsFullPath(inputFileName)) {
+ inputFileName = cmSystemTools::CollapseFullPath(inputFileName);
+ } else {
+ inputFileName = this->FixRelativePath(inputFileName, PathForInput, lg);
+ }
+ lg->GetMakefile()->AddCMakeDependFile(inputFileName);
+ cmSystemTools::GetPermissions(inputFileName.c_str(), perm);
+ cmsys::ifstream fin(inputFileName.c_str());
if (!fin) {
std::ostringstream e;
- e << "Evaluation file \"" << this->Input << "\" cannot be read.";
+ e << "Evaluation file \"" << inputFileName << "\" cannot be read.";
lg->IssueMessage(cmake::FATAL_ERROR, e.str());
return;
}
@@ -132,7 +144,7 @@ void cmGeneratorExpressionEvaluationFile::Generate(cmLocalGenerator* lg)
cmListFileBacktrace lfbt = this->OutputFileExpr->GetBacktrace();
cmGeneratorExpression contentGE(lfbt);
- CM_AUTO_PTR<cmCompiledGeneratorExpression> inputExpression =
+ std::unique_ptr<cmCompiledGeneratorExpression> inputExpression =
contentGE.Parse(inputContent);
std::map<std::string, std::string> outputFiles;
@@ -148,14 +160,66 @@ void cmGeneratorExpressionEvaluationFile::Generate(cmLocalGenerator* lg)
cmGlobalGenerator* gg = lg->GetGlobalGenerator();
gg->GetEnabledLanguages(enabledLanguages);
- for (std::vector<std::string>::const_iterator le = enabledLanguages.begin();
- le != enabledLanguages.end(); ++le) {
- for (std::vector<std::string>::const_iterator li = allConfigs.begin();
- li != allConfigs.end(); ++li) {
- this->Generate(lg, *li, *le, inputExpression.get(), outputFiles, perm);
+ for (std::string const& le : enabledLanguages) {
+ for (std::string const& li : allConfigs) {
+ this->Generate(lg, li, le, inputExpression.get(), outputFiles, perm);
if (cmSystemTools::GetFatalErrorOccured()) {
return;
}
}
}
}
+
+std::string cmGeneratorExpressionEvaluationFile::FixRelativePath(
+ std::string const& relativePath, PathRole role, cmLocalGenerator* lg)
+{
+ std::string resultPath;
+ switch (this->PolicyStatusCMP0070) {
+ case cmPolicies::WARN: {
+ std::string arg;
+ switch (role) {
+ case PathForInput:
+ arg = "INPUT";
+ break;
+ case PathForOutput:
+ arg = "OUTPUT";
+ break;
+ }
+ std::ostringstream w;
+ /* clang-format off */
+ w <<
+ cmPolicies::GetPolicyWarning(cmPolicies::CMP0070) << "\n"
+ "file(GENERATE) given relative " << arg << " path:\n"
+ " " << relativePath << "\n"
+ "This is not defined behavior unless CMP0070 is set to NEW. "
+ "For compatibility with older versions of CMake, the previous "
+ "undefined behavior will be used."
+ ;
+ /* clang-format on */
+ lg->IssueMessage(cmake::AUTHOR_WARNING, w.str());
+ }
+ CM_FALLTHROUGH;
+ case cmPolicies::OLD:
+ // OLD behavior is to use the relative path unchanged,
+ // which ends up being used relative to the working dir.
+ resultPath = relativePath;
+ break;
+ case cmPolicies::REQUIRED_IF_USED:
+ case cmPolicies::REQUIRED_ALWAYS:
+ case cmPolicies::NEW:
+ // NEW behavior is to interpret the relative path with respect
+ // to the current source or binary directory.
+ switch (role) {
+ case PathForInput:
+ resultPath = cmSystemTools::CollapseFullPath(
+ relativePath, lg->GetCurrentSourceDirectory());
+ break;
+ case PathForOutput:
+ resultPath = cmSystemTools::CollapseFullPath(
+ relativePath, lg->GetCurrentBinaryDirectory());
+ break;
+ }
+ break;
+ }
+ return resultPath;
+}
diff --git a/Source/cmGeneratorExpressionEvaluationFile.h b/Source/cmGeneratorExpressionEvaluationFile.h
index 98727460e..2a790697f 100644
--- a/Source/cmGeneratorExpressionEvaluationFile.h
+++ b/Source/cmGeneratorExpressionEvaluationFile.h
@@ -6,11 +6,12 @@
#include "cmConfigure.h" // IWYU pragma: keep
#include <map>
+#include <memory> // IWYU pragma: keep
#include <string>
#include <vector>
#include "cmGeneratorExpression.h"
-#include "cm_auto_ptr.hxx"
+#include "cmPolicies.h"
#include "cm_sys_stat.h"
class cmLocalGenerator;
@@ -20,8 +21,9 @@ class cmGeneratorExpressionEvaluationFile
public:
cmGeneratorExpressionEvaluationFile(
const std::string& input,
- CM_AUTO_PTR<cmCompiledGeneratorExpression> outputFileExpr,
- CM_AUTO_PTR<cmCompiledGeneratorExpression> condition, bool inputIsContent);
+ std::unique_ptr<cmCompiledGeneratorExpression> outputFileExpr,
+ std::unique_ptr<cmCompiledGeneratorExpression> condition,
+ bool inputIsContent, cmPolicies::PolicyStatus policyStatusCMP0070);
void Generate(cmLocalGenerator* lg);
@@ -35,12 +37,21 @@ private:
cmCompiledGeneratorExpression* inputExpression,
std::map<std::string, std::string>& outputFiles, mode_t perm);
+ enum PathRole
+ {
+ PathForInput,
+ PathForOutput
+ };
+ std::string FixRelativePath(std::string const& filePath, PathRole role,
+ cmLocalGenerator* lg);
+
private:
const std::string Input;
- const CM_AUTO_PTR<cmCompiledGeneratorExpression> OutputFileExpr;
- const CM_AUTO_PTR<cmCompiledGeneratorExpression> Condition;
+ const std::unique_ptr<cmCompiledGeneratorExpression> OutputFileExpr;
+ const std::unique_ptr<cmCompiledGeneratorExpression> Condition;
std::vector<std::string> Files;
const bool InputIsContent;
+ cmPolicies::PolicyStatus PolicyStatusCMP0070;
};
#endif
diff --git a/Source/cmGeneratorExpressionEvaluator.cxx b/Source/cmGeneratorExpressionEvaluator.cxx
index 6ce4a8e72..c73d48601 100644
--- a/Source/cmGeneratorExpressionEvaluator.cxx
+++ b/Source/cmGeneratorExpressionEvaluator.cxx
@@ -25,13 +25,13 @@ std::string GeneratorExpressionContent::ProcessArbitraryContent(
const cmGeneratorExpressionNode* node, const std::string& identifier,
cmGeneratorExpressionContext* context,
cmGeneratorExpressionDAGChecker* dagChecker,
- std::vector<std::vector<cmGeneratorExpressionEvaluator*> >::const_iterator
+ std::vector<std::vector<cmGeneratorExpressionEvaluator*>>::const_iterator
pit) const
{
std::string result;
const std::vector<
- std::vector<cmGeneratorExpressionEvaluator*> >::const_iterator pend =
+ std::vector<cmGeneratorExpressionEvaluator*>>::const_iterator pend =
this->ParamChildren.end();
for (; pit != pend; ++pit) {
std::vector<cmGeneratorExpressionEvaluator*>::const_iterator it =
@@ -122,10 +122,10 @@ std::string GeneratorExpressionContent::EvaluateParameters(
{
const int numExpected = node->NumExpectedParameters();
{
- std::vector<std::vector<cmGeneratorExpressionEvaluator*> >::const_iterator
+ std::vector<std::vector<cmGeneratorExpressionEvaluator*>>::const_iterator
pit = this->ParamChildren.begin();
const std::vector<
- std::vector<cmGeneratorExpressionEvaluator*> >::const_iterator pend =
+ std::vector<cmGeneratorExpressionEvaluator*>>::const_iterator pend =
this->ParamChildren.end();
const bool acceptsArbitraryContent =
node->AcceptsArbitraryContentParameter();
@@ -153,7 +153,7 @@ std::string GeneratorExpressionContent::EvaluateParameters(
}
if ((numExpected > cmGeneratorExpressionNode::DynamicParameters &&
- (unsigned int)numExpected != parameters.size())) {
+ static_cast<unsigned int>(numExpected) != parameters.size())) {
if (numExpected == 0) {
reportError(context, this->GetOriginalExpression(),
"$<" + identifier + "> expression requires no parameters.");
@@ -188,5 +188,5 @@ GeneratorExpressionContent::~GeneratorExpressionContent()
{
cmDeleteAll(this->IdentifierChildren);
std::for_each(this->ParamChildren.begin(), this->ParamChildren.end(),
- cmDeleteAll<std::vector<cmGeneratorExpressionEvaluator*> >);
+ cmDeleteAll<std::vector<cmGeneratorExpressionEvaluator*>>);
}
diff --git a/Source/cmGeneratorExpressionEvaluator.h b/Source/cmGeneratorExpressionEvaluator.h
index a0a826ac6..92dac79ea 100644
--- a/Source/cmGeneratorExpressionEvaluator.h
+++ b/Source/cmGeneratorExpressionEvaluator.h
@@ -3,7 +3,7 @@
#ifndef cmGeneratorExpressionEvaluator_h
#define cmGeneratorExpressionEvaluator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <stddef.h>
#include <string>
@@ -42,12 +42,12 @@ struct TextContent : public cmGeneratorExpressionEvaluator
}
std::string Evaluate(cmGeneratorExpressionContext*,
- cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE
+ cmGeneratorExpressionDAGChecker*) const override
{
return std::string(this->Content, this->Length);
}
- Type GetType() const CM_OVERRIDE
+ Type GetType() const override
{
return cmGeneratorExpressionEvaluator::Text;
}
@@ -71,23 +71,23 @@ struct GeneratorExpressionContent : public cmGeneratorExpressionEvaluator
}
void SetParameters(
- std::vector<std::vector<cmGeneratorExpressionEvaluator*> > const&
+ std::vector<std::vector<cmGeneratorExpressionEvaluator*>> const&
parameters)
{
this->ParamChildren = parameters;
}
- Type GetType() const CM_OVERRIDE
+ Type GetType() const override
{
return cmGeneratorExpressionEvaluator::Generator;
}
std::string Evaluate(cmGeneratorExpressionContext* context,
- cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE;
+ cmGeneratorExpressionDAGChecker*) const override;
std::string GetOriginalExpression() const;
- ~GeneratorExpressionContent() CM_OVERRIDE;
+ ~GeneratorExpressionContent() override;
private:
std::string EvaluateParameters(const cmGeneratorExpressionNode* node,
@@ -100,12 +100,12 @@ private:
const cmGeneratorExpressionNode* node, const std::string& identifier,
cmGeneratorExpressionContext* context,
cmGeneratorExpressionDAGChecker* dagChecker,
- std::vector<std::vector<cmGeneratorExpressionEvaluator*> >::const_iterator
+ std::vector<std::vector<cmGeneratorExpressionEvaluator*>>::const_iterator
pit) const;
private:
std::vector<cmGeneratorExpressionEvaluator*> IdentifierChildren;
- std::vector<std::vector<cmGeneratorExpressionEvaluator*> > ParamChildren;
+ std::vector<std::vector<cmGeneratorExpressionEvaluator*>> ParamChildren;
const char* StartContent;
size_t ContentLength;
};
diff --git a/Source/cmGeneratorExpressionNode.cxx b/Source/cmGeneratorExpressionNode.cxx
index a57d2a0d8..fea20ba87 100644
--- a/Source/cmGeneratorExpressionNode.cxx
+++ b/Source/cmGeneratorExpressionNode.cxx
@@ -17,16 +17,15 @@
#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#include "cmConfigure.h"
#include "cmsys/RegularExpression.hxx"
#include "cmsys/String.h"
#include <algorithm>
#include <assert.h>
#include <errno.h>
#include <map>
+#include <memory> // IWYU pragma: keep
#include <set>
#include <sstream>
#include <stdlib.h>
@@ -40,7 +39,7 @@ std::string cmGeneratorExpressionNode::EvaluateDependentExpression(
cmGeneratorExpressionDAGChecker* dagChecker)
{
cmGeneratorExpression ge(context->Backtrace);
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(prop);
cge->SetEvaluateForBuildsystem(context->EvaluateForBuildsystem);
std::string result =
cge->Evaluate(lg, context->Config, context->Quiet, headTarget,
@@ -58,15 +57,15 @@ static const struct ZeroNode : public cmGeneratorExpressionNode
{
ZeroNode() {}
- bool GeneratesContent() const CM_OVERRIDE { return false; }
+ bool GeneratesContent() const override { return false; }
- bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
+ bool AcceptsArbitraryContentParameter() const override { return true; }
- std::string Evaluate(const std::vector<std::string>& /*parameters*/,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& /*parameters*/,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return std::string();
}
@@ -76,13 +75,13 @@ static const struct OneNode : public cmGeneratorExpressionNode
{
OneNode() {}
- bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
+ bool AcceptsArbitraryContentParameter() const override { return true; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return parameters.front();
}
@@ -129,11 +128,11 @@ static const struct NotNode : public cmGeneratorExpressionNode
{
NotNode() {}
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
if (*parameters.begin() != "0" && *parameters.begin() != "1") {
reportError(
@@ -149,13 +148,13 @@ static const struct BoolNode : public cmGeneratorExpressionNode
{
BoolNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 1; }
+ int NumExpectedParameters() const override { return 1; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return !cmSystemTools::IsOff(parameters.begin()->c_str()) ? "1" : "0";
}
@@ -165,12 +164,12 @@ static const struct IfNode : public cmGeneratorExpressionNode
{
IfNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 3; }
+ int NumExpectedParameters() const override { return 3; }
std::string Evaluate(const std::vector<std::string>& parameters,
cmGeneratorExpressionContext* context,
const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker*) const CM_OVERRIDE
+ cmGeneratorExpressionDAGChecker*) const override
{
if (parameters[0] != "1" && parameters[0] != "0") {
reportError(context, content->GetOriginalExpression(),
@@ -186,13 +185,13 @@ static const struct StrEqualNode : public cmGeneratorExpressionNode
{
StrEqualNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 2; }
+ int NumExpectedParameters() const override { return 2; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return *parameters.begin() == parameters[1] ? "1" : "0";
}
@@ -202,13 +201,13 @@ static const struct EqualNode : public cmGeneratorExpressionNode
{
EqualNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 2; }
+ int NumExpectedParameters() const override { return 2; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
char* pEnd;
@@ -280,13 +279,13 @@ static const struct LowerCaseNode : public cmGeneratorExpressionNode
{
LowerCaseNode() {}
- bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
+ bool AcceptsArbitraryContentParameter() const override { return true; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return cmSystemTools::LowerCase(parameters.front());
}
@@ -296,13 +295,13 @@ static const struct UpperCaseNode : public cmGeneratorExpressionNode
{
UpperCaseNode() {}
- bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
+ bool AcceptsArbitraryContentParameter() const override { return true; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return cmSystemTools::UpperCase(parameters.front());
}
@@ -312,13 +311,13 @@ static const struct MakeCIdentifierNode : public cmGeneratorExpressionNode
{
MakeCIdentifierNode() {}
- bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
+ bool AcceptsArbitraryContentParameter() const override { return true; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return cmSystemTools::MakeCidentifier(parameters.front());
}
@@ -328,13 +327,13 @@ static const struct Angle_RNode : public cmGeneratorExpressionNode
{
Angle_RNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 0; }
+ int NumExpectedParameters() const override { return 0; }
- std::string Evaluate(const std::vector<std::string>& /*parameters*/,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& /*parameters*/,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return ">";
}
@@ -344,13 +343,13 @@ static const struct CommaNode : public cmGeneratorExpressionNode
{
CommaNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 0; }
+ int NumExpectedParameters() const override { return 0; }
- std::string Evaluate(const std::vector<std::string>& /*parameters*/,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& /*parameters*/,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return ",";
}
@@ -360,13 +359,13 @@ static const struct SemicolonNode : public cmGeneratorExpressionNode
{
SemicolonNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 0; }
+ int NumExpectedParameters() const override { return 0; }
- std::string Evaluate(const std::vector<std::string>& /*parameters*/,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& /*parameters*/,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return ";";
}
@@ -376,7 +375,7 @@ struct CompilerIdNode : public cmGeneratorExpressionNode
{
CompilerIdNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; }
+ int NumExpectedParameters() const override { return OneOrZeroParameters; }
std::string EvaluateWithLanguage(const std::vector<std::string>& parameters,
cmGeneratorExpressionContext* context,
@@ -428,11 +427,11 @@ static const struct CCompilerIdNode : public CompilerIdNode
{
CCompilerIdNode() {}
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* dagChecker) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* dagChecker) const override
{
if (!context->HeadTarget) {
reportError(
@@ -450,11 +449,11 @@ static const struct CXXCompilerIdNode : public CompilerIdNode
{
CXXCompilerIdNode() {}
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* dagChecker) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* dagChecker) const override
{
if (!context->HeadTarget) {
reportError(
@@ -472,7 +471,7 @@ struct CompilerVersionNode : public cmGeneratorExpressionNode
{
CompilerVersionNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; }
+ int NumExpectedParameters() const override { return OneOrZeroParameters; }
std::string EvaluateWithLanguage(const std::vector<std::string>& parameters,
cmGeneratorExpressionContext* context,
@@ -509,11 +508,11 @@ static const struct CCompilerVersionNode : public CompilerVersionNode
{
CCompilerVersionNode() {}
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* dagChecker) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* dagChecker) const override
{
if (!context->HeadTarget) {
reportError(
@@ -531,11 +530,11 @@ static const struct CxxCompilerVersionNode : public CompilerVersionNode
{
CxxCompilerVersionNode() {}
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* dagChecker) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* dagChecker) const override
{
if (!context->HeadTarget) {
reportError(
@@ -553,13 +552,13 @@ struct PlatformIdNode : public cmGeneratorExpressionNode
{
PlatformIdNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; }
+ int NumExpectedParameters() const override { return OneOrZeroParameters; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
const char* platformId =
context->LG->GetMakefile()->GetSafeDefinition("CMAKE_SYSTEM_NAME");
@@ -582,13 +581,13 @@ static const struct VersionGreaterNode : public cmGeneratorExpressionNode
{
VersionGreaterNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 2; }
+ int NumExpectedParameters() const override { return 2; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER,
parameters.front().c_str(),
@@ -602,13 +601,13 @@ static const struct VersionGreaterEqNode : public cmGeneratorExpressionNode
{
VersionGreaterEqNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 2; }
+ int NumExpectedParameters() const override { return 2; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
parameters.front().c_str(),
@@ -622,13 +621,13 @@ static const struct VersionLessNode : public cmGeneratorExpressionNode
{
VersionLessNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 2; }
+ int NumExpectedParameters() const override { return 2; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
parameters.front().c_str(),
@@ -642,13 +641,13 @@ static const struct VersionLessEqNode : public cmGeneratorExpressionNode
{
VersionLessEqNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 2; }
+ int NumExpectedParameters() const override { return 2; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return cmSystemTools::VersionCompare(cmSystemTools::OP_LESS_EQUAL,
parameters.front().c_str(),
@@ -662,13 +661,13 @@ static const struct VersionEqualNode : public cmGeneratorExpressionNode
{
VersionEqualNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 2; }
+ int NumExpectedParameters() const override { return 2; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return cmSystemTools::VersionCompare(cmSystemTools::OP_EQUAL,
parameters.front().c_str(),
@@ -682,11 +681,11 @@ static const struct LinkOnlyNode : public cmGeneratorExpressionNode
{
LinkOnlyNode() {}
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* dagChecker) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* dagChecker) const override
{
if (!dagChecker) {
reportError(context, content->GetOriginalExpression(),
@@ -704,13 +703,13 @@ static const struct ConfigurationNode : public cmGeneratorExpressionNode
{
ConfigurationNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 0; }
+ int NumExpectedParameters() const override { return 0; }
- std::string Evaluate(const std::vector<std::string>& /*parameters*/,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& /*parameters*/,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
context->HadContextSensitiveCondition = true;
return context->Config;
@@ -721,17 +720,16 @@ static const struct ConfigurationTestNode : public cmGeneratorExpressionNode
{
ConfigurationTestNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; }
+ int NumExpectedParameters() const override { return OneOrZeroParameters; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
if (parameters.empty()) {
- return configurationNode.Evaluate(parameters, context, content,
- CM_NULLPTR);
+ return configurationNode.Evaluate(parameters, context, content, nullptr);
}
static cmsys::RegularExpression configValidator("^[A-Za-z0-9_]*$");
if (!configValidator.find(*parameters.begin())) {
@@ -750,8 +748,8 @@ static const struct ConfigurationTestNode : public cmGeneratorExpressionNode
}
if (context->CurrentTarget && context->CurrentTarget->IsImported()) {
- const char* loc = CM_NULLPTR;
- const char* imp = CM_NULLPTR;
+ const char* loc = nullptr;
+ const char* imp = nullptr;
std::string suffix;
if (context->CurrentTarget->Target->GetMappedConfig(
context->Config, &loc, &imp, suffix)) {
@@ -781,15 +779,15 @@ static const struct JoinNode : public cmGeneratorExpressionNode
{
JoinNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 2; }
+ int NumExpectedParameters() const override { return 2; }
- bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
+ bool AcceptsArbitraryContentParameter() const override { return true; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
std::vector<std::string> list;
cmSystemTools::ExpandListArgument(parameters.front(), list);
@@ -801,19 +799,19 @@ static const struct CompileLanguageNode : public cmGeneratorExpressionNode
{
CompileLanguageNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return OneOrZeroParameters; }
+ int NumExpectedParameters() const override { return OneOrZeroParameters; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* dagChecker) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* dagChecker) const override
{
if (context->Language.empty()) {
reportError(
context, content->GetOriginalExpression(),
"$<COMPILE_LANGUAGE:...> may only be used to specify include "
- "directories compile definitions, compile options and to evaluate "
+ "directories, compile definitions, compile options, and to evaluate "
"components of the file(GENERATE) command.");
return std::string();
}
@@ -864,7 +862,7 @@ static const struct CompileLanguageNode : public cmGeneratorExpressionNode
#define TRANSITIVE_PROPERTY_NAME(PROPERTY) , "INTERFACE_" #PROPERTY
static const char* targetPropertyTransitiveWhitelist[] = {
- CM_NULLPTR CM_FOR_EACH_TRANSITIVE_PROPERTY_NAME(TRANSITIVE_PROPERTY_NAME)
+ nullptr CM_FOR_EACH_TRANSITIVE_PROPERTY_NAME(TRANSITIVE_PROPERTY_NAME)
};
#undef TRANSITIVE_PROPERTY_NAME
@@ -879,13 +877,12 @@ std::string getLinkedTargetsContent(
std::string linkedTargetsContent;
std::string sep;
std::string depString;
- for (typename std::vector<T>::const_iterator it = libraries.begin();
- it != libraries.end(); ++it) {
+ for (T const& l : libraries) {
// Broken code can have a target in its own link interface.
// Don't follow such link interface entries so as not to create a
// self-referencing loop.
- if (it->Target && it->Target != target) {
- depString += sep + "$<TARGET_PROPERTY:" + it->Target->GetName() + "," +
+ if (l.Target && l.Target != target) {
+ depString += sep + "$<TARGET_PROPERTY:" + l.Target->GetName() + "," +
interfacePropertyName + ">";
sep = ";";
}
@@ -906,13 +903,13 @@ static const struct TargetPropertyNode : public cmGeneratorExpressionNode
TargetPropertyNode() {}
// This node handles errors on parameter count itself.
- int NumExpectedParameters() const CM_OVERRIDE { return OneOrMoreParameters; }
+ int NumExpectedParameters() const override { return OneOrMoreParameters; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* dagCheckerParent) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* dagCheckerParent) const override
{
if (parameters.size() != 1 && parameters.size() != 2) {
reportError(
@@ -1199,21 +1196,21 @@ static const struct TargetNameNode : public cmGeneratorExpressionNode
{
TargetNameNode() {}
- bool GeneratesContent() const CM_OVERRIDE { return true; }
+ bool GeneratesContent() const override { return true; }
- bool AcceptsArbitraryContentParameter() const CM_OVERRIDE { return true; }
- bool RequiresLiteralInput() const CM_OVERRIDE { return true; }
+ bool AcceptsArbitraryContentParameter() const override { return true; }
+ bool RequiresLiteralInput() const override { return true; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* /*context*/,
- const GeneratorExpressionContent* /*content*/,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* /*context*/,
+ const GeneratorExpressionContent* /*content*/,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
return parameters.front();
}
- int NumExpectedParameters() const CM_OVERRIDE { return 1; }
+ int NumExpectedParameters() const override { return 1; }
} targetNameNode;
@@ -1221,11 +1218,11 @@ static const struct TargetObjectsNode : public cmGeneratorExpressionNode
{
TargetObjectsNode() {}
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
std::string tgtName = parameters.front();
cmGeneratorTarget* gt = context->LG->FindGeneratorTargetToUse(tgtName);
@@ -1260,8 +1257,8 @@ static const struct TargetObjectsNode : public cmGeneratorExpressionNode
std::vector<std::string> objects;
if (gt->IsImported()) {
- const char* loc = CM_NULLPTR;
- const char* imp = CM_NULLPTR;
+ const char* loc = nullptr;
+ const char* imp = nullptr;
std::string suffix;
if (gt->Target->GetMappedConfig(context->Config, &loc, &imp, suffix)) {
cmSystemTools::ExpandListArgument(loc, objects);
@@ -1283,17 +1280,15 @@ static const struct TargetObjectsNode : public cmGeneratorExpressionNode
context->HadContextSensitiveCondition = true;
}
- for (std::vector<std::string>::iterator oi = objects.begin();
- oi != objects.end(); ++oi) {
- *oi = obj_dir + *oi;
+ for (std::string& o : objects) {
+ o = obj_dir + o;
}
}
// Create the cmSourceFile instances in the referencing directory.
cmMakefile* mf = context->LG->GetMakefile();
- for (std::vector<std::string>::iterator oi = objects.begin();
- oi != objects.end(); ++oi) {
- mf->AddTargetObject(tgtName, *oi);
+ for (std::string& o : objects) {
+ mf->AddTargetObject(tgtName, o);
}
return cmJoin(objects, ";");
@@ -1304,13 +1299,13 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode
{
CompileFeaturesNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return OneOrMoreParameters; }
+ int NumExpectedParameters() const override { return OneOrMoreParameters; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* dagChecker) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* dagChecker) const override
{
cmGeneratorTarget const* target = context->HeadTarget;
if (!target) {
@@ -1322,21 +1317,20 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode
}
context->HadHeadSensitiveCondition = true;
- typedef std::map<std::string, std::vector<std::string> > LangMap;
+ typedef std::map<std::string, std::vector<std::string>> LangMap;
static LangMap availableFeatures;
LangMap testedFeatures;
- for (std::vector<std::string>::const_iterator it = parameters.begin();
- it != parameters.end(); ++it) {
+ for (std::string const& p : parameters) {
std::string error;
std::string lang;
if (!context->LG->GetMakefile()->CompileFeatureKnown(
- context->HeadTarget->Target, *it, lang, &error)) {
+ context->HeadTarget->Target, p, lang, &error)) {
reportError(context, content->GetOriginalExpression(), error);
return std::string();
}
- testedFeatures[lang].push_back(*it);
+ testedFeatures[lang].push_back(p);
if (availableFeatures.find(lang) == availableFeatures.end()) {
const char* featuresKnown =
@@ -1352,15 +1346,13 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode
bool evalLL = dagChecker && dagChecker->EvaluatingLinkLibraries();
- for (LangMap::const_iterator lit = testedFeatures.begin();
- lit != testedFeatures.end(); ++lit) {
+ for (auto const& lit : testedFeatures) {
std::vector<std::string> const& langAvailable =
- availableFeatures[lit->first];
+ availableFeatures[lit.first];
const char* standardDefault = context->LG->GetMakefile()->GetDefinition(
- "CMAKE_" + lit->first + "_STANDARD_DEFAULT");
- for (std::vector<std::string>::const_iterator it = lit->second.begin();
- it != lit->second.end(); ++it) {
- if (std::find(langAvailable.begin(), langAvailable.end(), *it) ==
+ "CMAKE_" + lit.first + "_STANDARD_DEFAULT");
+ for (std::string const& it : lit.second) {
+ if (std::find(langAvailable.begin(), langAvailable.end(), it) ==
langAvailable.end()) {
return "0";
}
@@ -1370,14 +1362,14 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode
continue;
}
if (!context->LG->GetMakefile()->HaveStandardAvailable(
- target->Target, lit->first, *it)) {
+ target->Target, lit.first, it)) {
if (evalLL) {
- const char* l = target->GetProperty(lit->first + "_STANDARD");
+ const char* l = target->GetProperty(lit.first + "_STANDARD");
if (!l) {
l = standardDefault;
}
assert(l);
- context->MaxLanguageStandard[target][lit->first] = l;
+ context->MaxLanguageStandard[target][lit.first] = l;
} else {
return "0";
}
@@ -1389,10 +1381,10 @@ static const struct CompileFeaturesNode : public cmGeneratorExpressionNode
} compileFeaturesNode;
static const char* targetPolicyWhitelist[] = {
- CM_NULLPTR
+ nullptr
#define TARGET_POLICY_STRING(POLICY) , #POLICY
- CM_FOR_EACH_TARGET_POLICY(TARGET_POLICY_STRING)
+ CM_FOR_EACH_TARGET_POLICY(TARGET_POLICY_STRING)
#undef TARGET_POLICY_STRING
};
@@ -1432,13 +1424,13 @@ static const struct TargetPolicyNode : public cmGeneratorExpressionNode
{
TargetPolicyNode() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 1; }
+ int NumExpectedParameters() const override { return 1; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
if (!context->HeadTarget) {
reportError(
@@ -1493,14 +1485,14 @@ static const struct InstallPrefixNode : public cmGeneratorExpressionNode
{
InstallPrefixNode() {}
- bool GeneratesContent() const CM_OVERRIDE { return true; }
- int NumExpectedParameters() const CM_OVERRIDE { return 0; }
+ bool GeneratesContent() const override { return true; }
+ int NumExpectedParameters() const override { return 0; }
- std::string Evaluate(const std::vector<std::string>& /*parameters*/,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& /*parameters*/,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
reportError(context, content->GetOriginalExpression(),
"INSTALL_PREFIX is a marker for install(EXPORT) only. It "
@@ -1713,13 +1705,13 @@ struct TargetFilesystemArtifact : public cmGeneratorExpressionNode
{
TargetFilesystemArtifact() {}
- int NumExpectedParameters() const CM_OVERRIDE { return 1; }
+ int NumExpectedParameters() const override { return 1; }
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* dagChecker) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* dagChecker) const override
{
// Lookup the referenced target.
std::string name = *parameters.begin();
@@ -1795,11 +1787,11 @@ static const struct ShellPathNode : public cmGeneratorExpressionNode
{
ShellPathNode() {}
- std::string Evaluate(const std::vector<std::string>& parameters,
- cmGeneratorExpressionContext* context,
- const GeneratorExpressionContent* content,
- cmGeneratorExpressionDAGChecker* /*dagChecker*/) const
- CM_OVERRIDE
+ std::string Evaluate(
+ const std::vector<std::string>& parameters,
+ cmGeneratorExpressionContext* context,
+ const GeneratorExpressionContent* content,
+ cmGeneratorExpressionDAGChecker* /*dagChecker*/) const override
{
if (!cmSystemTools::FileIsFullPath(parameters.front())) {
reportError(context, content->GetOriginalExpression(),
@@ -1873,7 +1865,7 @@ const cmGeneratorExpressionNode* cmGeneratorExpressionNode::GetNode(
}
NodeMap::const_iterator i = nodeMap.find(identifier);
if (i == nodeMap.end()) {
- return CM_NULLPTR;
+ return nullptr;
}
return i->second;
}
diff --git a/Source/cmGeneratorExpressionParser.cxx b/Source/cmGeneratorExpressionParser.cxx
index c33349a63..278de0444 100644
--- a/Source/cmGeneratorExpressionParser.cxx
+++ b/Source/cmGeneratorExpressionParser.cxx
@@ -97,7 +97,7 @@ void cmGeneratorExpressionParser::ParseGeneratorExpression(
return;
}
- std::vector<std::vector<cmGeneratorExpressionEvaluator*> > parameters;
+ std::vector<std::vector<cmGeneratorExpressionEvaluator*>> parameters;
std::vector<std::vector<cmGeneratorExpressionToken>::const_iterator>
commaTokens;
std::vector<cmGeneratorExpressionToken>::const_iterator colonToken;
diff --git a/Source/cmGeneratorTarget.cxx b/Source/cmGeneratorTarget.cxx
index c9924f670..103d0340e 100644
--- a/Source/cmGeneratorTarget.cxx
+++ b/Source/cmGeneratorTarget.cxx
@@ -7,11 +7,13 @@
#include <assert.h>
#include <errno.h>
#include <iterator>
+#include <memory> // IWYU pragma: keep
#include <queue>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <unordered_set>
#include "cmAlgorithms.h"
#include "cmComputeLinkInformation.h"
@@ -31,8 +33,6 @@
#include "cmTarget.h"
#include "cmTargetLinkLibraryType.h"
#include "cmTargetPropertyComputer.h"
-#include "cm_auto_ptr.hxx"
-#include "cm_unordered_set.hxx"
#include "cmake.h"
class cmMessenger;
@@ -64,13 +64,13 @@ class cmGeneratorTarget::TargetPropertyEntry
static cmLinkImplItem NoLinkImplItem;
public:
- TargetPropertyEntry(CM_AUTO_PTR<cmCompiledGeneratorExpression> cge,
+ TargetPropertyEntry(std::unique_ptr<cmCompiledGeneratorExpression> cge,
cmLinkImplItem const& item = NoLinkImplItem)
- : ge(cge)
+ : ge(std::move(cge))
, LinkImplItem(item)
{
}
- const CM_AUTO_PTR<cmCompiledGeneratorExpression> ge;
+ const std::unique_ptr<cmCompiledGeneratorExpression> ge;
cmLinkImplItem const& LinkImplItem;
};
cmLinkImplItem cmGeneratorTarget::TargetPropertyEntry::NoLinkImplItem;
@@ -84,9 +84,10 @@ void CreatePropertyGeneratorExpressions(
for (std::vector<std::string>::const_iterator it = entries.begin();
it != entries.end(); ++it, ++btIt) {
cmGeneratorExpression ge(*btIt);
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*it);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(*it);
cge->SetEvaluateForBuildsystem(evaluateForBuildsystem);
- items.push_back(new cmGeneratorTarget::TargetPropertyEntry(cge));
+ items.push_back(
+ new cmGeneratorTarget::TargetPropertyEntry(std::move(cge)));
}
}
@@ -150,11 +151,8 @@ cmGeneratorTarget::~cmGeneratorTarget()
const char* cmGeneratorTarget::GetSourcesProperty() const
{
std::vector<std::string> values;
- for (std::vector<cmGeneratorTarget::TargetPropertyEntry *>::const_iterator
- it = this->SourceEntries.begin(),
- end = this->SourceEntries.end();
- it != end; ++it) {
- values.push_back((*it)->ge->GetInput());
+ for (TargetPropertyEntry* se : this->SourceEntries) {
+ values.push_back(se->ge->GetInput());
}
static std::string value;
value.clear();
@@ -204,14 +202,14 @@ const char* cmGeneratorTarget::GetProperty(const std::string& prop) const
if (!cmTargetPropertyComputer::PassesWhitelist(
this->GetType(), prop, this->Makefile->GetMessenger(),
this->GetBacktrace())) {
- return CM_NULLPTR;
+ return nullptr;
}
if (const char* result = cmTargetPropertyComputer::GetProperty(
this, prop, this->Makefile->GetMessenger(), this->GetBacktrace())) {
return result;
}
if (cmSystemTools::GetFatalErrorOccured()) {
- return CM_NULLPTR;
+ return nullptr;
}
return this->Target->GetProperty(prop);
}
@@ -299,9 +297,8 @@ std::string cmGeneratorTarget::GetOutputName(
props.push_back("OUTPUT_NAME");
std::string outName;
- for (std::vector<std::string>::const_iterator it = props.begin();
- it != props.end(); ++it) {
- if (const char* outNameProp = this->GetProperty(*it)) {
+ for (std::string const& p : props) {
+ if (const char* outNameProp = this->GetProperty(p)) {
outName = outNameProp;
break;
}
@@ -313,7 +310,7 @@ std::string cmGeneratorTarget::GetOutputName(
// Now evaluate genex and update the previously-prepared map entry.
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(outName);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(outName);
i->second = cge->Evaluate(this->LocalGenerator, config);
} else if (i->second.empty()) {
// An empty map entry indicates we have been called recursively
@@ -326,15 +323,21 @@ std::string cmGeneratorTarget::GetOutputName(
return i->second;
}
+void cmGeneratorTarget::ClearSourcesCache()
+{
+ this->KindedSourcesMap.clear();
+ this->LinkImplementationLanguageIsContextDependent = true;
+ this->Objects.clear();
+}
+
void cmGeneratorTarget::AddSourceCommon(const std::string& src)
{
cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
cmGeneratorExpression ge(lfbt);
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(src);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(src);
cge->SetEvaluateForBuildsystem(true);
- this->SourceEntries.push_back(new TargetPropertyEntry(cge));
- this->KindedSourcesMap.clear();
- this->LinkImplementationLanguageIsContextDependent = true;
+ this->SourceEntries.push_back(new TargetPropertyEntry(std::move(cge)));
+ this->ClearSourcesCache();
}
void cmGeneratorTarget::AddSource(const std::string& src)
@@ -357,13 +360,14 @@ void cmGeneratorTarget::AddIncludeDirectory(const std::string& src,
this->Target->InsertInclude(src, this->Makefile->GetBacktrace(), before);
cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
cmGeneratorExpression ge(lfbt);
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(src);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(src);
cge->SetEvaluateForBuildsystem(true);
// Insert before begin/end
std::vector<TargetPropertyEntry*>::iterator pos = before
? this->IncludeDirectoriesEntries.begin()
: this->IncludeDirectoriesEntries.end();
- this->IncludeDirectoriesEntries.insert(pos, new TargetPropertyEntry(cge));
+ this->IncludeDirectoriesEntries.insert(
+ pos, new TargetPropertyEntry(std::move(cge)));
}
std::vector<cmSourceFile*> const* cmGeneratorTarget::GetSourceDepends(
@@ -373,7 +377,7 @@ std::vector<cmSourceFile*> const* cmGeneratorTarget::GetSourceDepends(
if (i != this->SourceDepends.end()) {
return &i->second.Depends;
}
- return CM_NULLPTR;
+ return nullptr;
}
static void handleSystemIncludesDep(
@@ -408,10 +412,9 @@ static void handleSystemIncludesDep(
#define IMPLEMENT_VISIT(KIND) \
{ \
KindedSources const& kinded = this->GetKindedSources(config); \
- for (std::vector<SourceAndKind>::const_iterator \
- si = kinded.Sources.begin(); si != kinded.Sources.end(); ++si) { \
- if (si->Kind == KIND) { \
- data.push_back(si->Source); \
+ for (SourceAndKind const& s : kinded.Sources) { \
+ if (s.Kind == KIND) { \
+ data.push_back(s.Source); \
} \
} \
}
@@ -426,9 +429,8 @@ void cmGeneratorTarget::GetObjectSources(
return;
}
- for (std::vector<cmSourceFile const*>::const_iterator it = data.begin();
- it != data.end(); ++it) {
- this->Objects[*it];
+ for (cmSourceFile const* it : data) {
+ this->Objects[it];
}
this->LocalGenerator->ComputeObjectFilenames(this->Objects, this);
@@ -445,10 +447,9 @@ void cmGeneratorTarget::ComputeObjectMapping()
if (configs.empty()) {
configs.push_back("");
}
- for (std::vector<std::string>::const_iterator ci = configs.begin();
- ci != configs.end(); ++ci) {
+ for (std::string const& c : configs) {
std::vector<cmSourceFile const*> sourceFiles;
- this->GetObjectSources(sourceFiles, *ci);
+ this->GetObjectSources(sourceFiles, c);
}
}
@@ -511,7 +512,7 @@ bool cmGeneratorTarget::IsIPOEnabled(std::string const& lang,
}
// Note: check consistency with messages from CheckIPOSupported
- const char* message = CM_NULLPTR;
+ const char* message = nullptr;
if (!this->Makefile->IsOn("_CMAKE_" + lang + "_IPO_SUPPORTED_BY_CMAKE")) {
message = "CMake doesn't support IPO for current compiler";
} else if (!this->Makefile->IsOn("_CMAKE_" + lang +
@@ -553,7 +554,7 @@ const char* cmGeneratorTarget::GetCustomObjectExtension() const
extension = ".ptx";
return extension.c_str();
}
- return CM_NULLPTR;
+ return nullptr;
}
void cmGeneratorTarget::AddExplicitObjectName(cmSourceFile const* sf)
@@ -649,11 +650,10 @@ std::set<cmLinkItem> const& cmGeneratorTarget::GetUtilityItems() const
if (!this->UtilityItemsDone) {
this->UtilityItemsDone = true;
std::set<std::string> const& utilities = this->GetUtilities();
- for (std::set<std::string>::const_iterator i = utilities.begin();
- i != utilities.end(); ++i) {
+ for (std::string const& i : utilities) {
cmGeneratorTarget* gt =
- this->LocalGenerator->FindGeneratorTargetToUse(*i);
- this->UtilityItems.insert(cmLinkItem(*i, gt));
+ this->LocalGenerator->FindGeneratorTargetToUse(i);
+ this->UtilityItems.insert(cmLinkItem(i, gt));
}
}
return this->UtilityItems;
@@ -743,34 +743,29 @@ bool cmGeneratorTarget::IsSystemIncludeDirectory(
config_upper = cmSystemTools::UpperCase(config);
}
- typedef std::map<std::string, std::vector<std::string> > IncludeCacheType;
+ typedef std::map<std::string, std::vector<std::string>> IncludeCacheType;
IncludeCacheType::const_iterator iter =
this->SystemIncludesCache.find(config_upper);
if (iter == this->SystemIncludesCache.end()) {
cmGeneratorExpressionDAGChecker dagChecker(
- this->GetName(), "SYSTEM_INCLUDE_DIRECTORIES", CM_NULLPTR, CM_NULLPTR);
+ this->GetName(), "SYSTEM_INCLUDE_DIRECTORIES", nullptr, nullptr);
bool excludeImported = this->GetPropertyAsBool("NO_SYSTEM_FROM_IMPORTED");
std::vector<std::string> result;
- for (std::set<std::string>::const_iterator it =
- this->Target->GetSystemIncludeDirectories().begin();
- it != this->Target->GetSystemIncludeDirectories().end(); ++it) {
+ for (std::string const& it : this->Target->GetSystemIncludeDirectories()) {
cmGeneratorExpression ge;
cmSystemTools::ExpandListArgument(
- ge.Parse(*it)->Evaluate(this->LocalGenerator, config, false, this,
- &dagChecker),
+ ge.Parse(it)->Evaluate(this->LocalGenerator, config, false, this,
+ &dagChecker),
result);
}
std::vector<cmGeneratorTarget const*> const& deps =
this->GetLinkImplementationClosure(config);
- for (std::vector<cmGeneratorTarget const *>::const_iterator
- li = deps.begin(),
- le = deps.end();
- li != le; ++li) {
- handleSystemIncludesDep(this->LocalGenerator, *li, config, this,
+ for (cmGeneratorTarget const* dep : deps) {
+ handleSystemIncludesDep(this->LocalGenerator, dep, config, this,
&dagChecker, result, excludeImported);
}
@@ -798,17 +793,14 @@ static void AddInterfaceEntries(
{
if (cmLinkImplementationLibraries const* impl =
thisTarget->GetLinkImplementationLibraries(config)) {
- for (std::vector<cmLinkImplItem>::const_iterator
- it = impl->Libraries.begin(),
- end = impl->Libraries.end();
- it != end; ++it) {
- if (it->Target) {
- std::string genex = "$<TARGET_PROPERTY:" + *it + "," + prop + ">";
- cmGeneratorExpression ge(it->Backtrace);
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(genex);
+ for (cmLinkImplItem const& lib : impl->Libraries) {
+ if (lib.Target) {
+ std::string genex = "$<TARGET_PROPERTY:" + lib + "," + prop + ">";
+ cmGeneratorExpression ge(lib.Backtrace);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(genex);
cge->SetEvaluateForBuildsystem(true);
entries.push_back(
- new cmGeneratorTarget::TargetPropertyEntry(cge, *it));
+ new cmGeneratorTarget::TargetPropertyEntry(std::move(cge), lib));
}
}
}
@@ -817,7 +809,7 @@ static void AddInterfaceEntries(
static bool processSources(
cmGeneratorTarget const* tgt,
const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries,
- std::vector<std::string>& srcs, CM_UNORDERED_SET<std::string>& uniqueSrcs,
+ std::vector<std::string>& srcs, std::unordered_set<std::string>& uniqueSrcs,
cmGeneratorExpressionDAGChecker* dagChecker, std::string const& config,
bool debugSources)
{
@@ -825,25 +817,20 @@ static bool processSources(
bool contextDependent = false;
- for (std::vector<cmGeneratorTarget::TargetPropertyEntry *>::const_iterator
- it = entries.begin(),
- end = entries.end();
- it != end; ++it) {
- cmLinkImplItem const& item = (*it)->LinkImplItem;
+ for (cmGeneratorTarget::TargetPropertyEntry* entry : entries) {
+ cmLinkImplItem const& item = entry->LinkImplItem;
std::string const& targetName = item;
std::vector<std::string> entrySources;
cmSystemTools::ExpandListArgument(
- (*it)->ge->Evaluate(tgt->GetLocalGenerator(), config, false, tgt, tgt,
+ entry->ge->Evaluate(tgt->GetLocalGenerator(), config, false, tgt, tgt,
dagChecker),
entrySources);
- if ((*it)->ge->GetHadContextSensitiveCondition()) {
+ if (entry->ge->GetHadContextSensitiveCondition()) {
contextDependent = true;
}
- for (std::vector<std::string>::iterator i = entrySources.begin();
- i != entrySources.end(); ++i) {
- std::string& src = *i;
+ for (std::string& src : entrySources) {
cmSourceFile* sf = mf->GetOrCreateSource(src);
std::string e;
std::string fullPath = sf->GetFullPath(&e);
@@ -874,10 +861,7 @@ static bool processSources(
src = fullPath;
}
std::string usedSources;
- for (std::vector<std::string>::iterator li = entrySources.begin();
- li != entrySources.end(); ++li) {
- std::string src = *li;
-
+ for (std::string const& src : entrySources) {
if (uniqueSrcs.insert(src).second) {
srcs.push_back(src);
if (debugSources) {
@@ -889,7 +873,7 @@ static bool processSources(
tgt->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
cmake::LOG, std::string("Used sources for target ") + tgt->GetName() +
":\n" + usedSources,
- (*it)->ge->GetBacktrace());
+ entry->ge->GetBacktrace());
}
}
return contextDependent;
@@ -908,19 +892,15 @@ void cmGeneratorTarget::GetSourceFiles(std::vector<std::string>& files,
// behavior of CMP0024 and CMP0026 only.
cmStringRange sourceEntries = this->Target->GetSourceEntries();
- for (cmStringRange::const_iterator i = sourceEntries.begin();
- i != sourceEntries.end(); ++i) {
- std::string const& entry = *i;
-
+ for (std::string const& entry : sourceEntries) {
std::vector<std::string> items;
cmSystemTools::ExpandListArgument(entry, items);
- for (std::vector<std::string>::const_iterator li = items.begin();
- li != items.end(); ++li) {
- if (cmHasLiteralPrefix(*li, "$<TARGET_OBJECTS:") &&
- (*li)[li->size() - 1] == '>') {
+ for (std::string const& item : items) {
+ if (cmHasLiteralPrefix(item, "$<TARGET_OBJECTS:") &&
+ item[item.size() - 1] == '>') {
continue;
}
- files.push_back(*li);
+ files.push_back(item);
}
}
return;
@@ -942,9 +922,9 @@ void cmGeneratorTarget::GetSourceFiles(std::vector<std::string>& files,
}
cmGeneratorExpressionDAGChecker dagChecker(this->GetName(), "SOURCES",
- CM_NULLPTR, CM_NULLPTR);
+ nullptr, nullptr);
- CM_UNORDERED_SET<std::string> uniqueSrcs;
+ std::unordered_set<std::string> uniqueSrcs;
bool contextDependentDirectSources =
processSources(this, this->SourceEntries, files, uniqueSrcs, &dagChecker,
config, debugSources);
@@ -981,9 +961,8 @@ void cmGeneratorTarget::GetSourceFiles(std::vector<cmSourceFile*>& files,
std::vector<std::string> srcs;
this->GetSourceFiles(srcs, config);
std::set<cmSourceFile*> emitted;
- for (std::vector<std::string>::const_iterator i = srcs.begin();
- i != srcs.end(); ++i) {
- cmSourceFile* sf = this->Makefile->GetOrCreateSource(*i);
+ for (std::string const& s : srcs) {
+ cmSourceFile* sf = this->Makefile->GetOrCreateSource(s);
if (emitted.insert(sf).second) {
files.push_back(sf);
}
@@ -993,9 +972,8 @@ void cmGeneratorTarget::GetSourceFiles(std::vector<cmSourceFile*>& files,
KindedSources const& kinded = this->GetKindedSources(config);
files.reserve(kinded.Sources.size());
- for (std::vector<SourceAndKind>::const_iterator si = kinded.Sources.begin();
- si != kinded.Sources.end(); ++si) {
- files.push_back(si->Source);
+ for (SourceAndKind const& si : kinded.Sources) {
+ files.push_back(si.Source);
}
}
@@ -1004,10 +982,9 @@ void cmGeneratorTarget::GetSourceFilesWithoutObjectLibraries(
{
KindedSources const& kinded = this->GetKindedSources(config);
files.reserve(kinded.Sources.size());
- for (std::vector<SourceAndKind>::const_iterator si = kinded.Sources.begin();
- si != kinded.Sources.end(); ++si) {
- if (si->Source->GetObjectLibrary().empty()) {
- files.push_back(si->Source);
+ for (SourceAndKind const& si : kinded.Sources) {
+ if (si.Source->GetObjectLibrary().empty()) {
+ files.push_back(si.Source);
}
}
}
@@ -1056,10 +1033,9 @@ void cmGeneratorTarget::ComputeKindedSources(KindedSources& files,
std::vector<cmSourceFile*> badObjLib;
std::set<cmSourceFile*> emitted;
- for (std::vector<std::string>::const_iterator i = srcs.begin();
- i != srcs.end(); ++i) {
+ for (std::string const& s : srcs) {
// Create each source at most once.
- cmSourceFile* sf = this->Makefile->GetOrCreateSource(*i);
+ cmSourceFile* sf = this->Makefile->GetOrCreateSource(s);
if (!emitted.insert(sf).second) {
continue;
}
@@ -1132,9 +1108,8 @@ void cmGeneratorTarget::ComputeKindedSources(KindedSources& files,
if (!badObjLib.empty()) {
std::ostringstream e;
e << "OBJECT library \"" << this->GetName() << "\" contains:\n";
- for (std::vector<cmSourceFile*>::const_iterator i = badObjLib.begin();
- i != badObjLib.end(); ++i) {
- e << " " << (*i)->GetLocation().GetName() << "\n";
+ for (cmSourceFile* i : badObjLib) {
+ e << " " << i->GetLocation().GetName() << "\n";
}
e << "but may contain only sources that compile, header files, and "
"other files that would not affect linking of a normal library.";
@@ -1161,18 +1136,16 @@ void cmGeneratorTarget::ComputeAllConfigSources() const
for (size_t ci = 0; ci < configs.size(); ++ci) {
KindedSources const& sources = this->GetKindedSources(configs[ci]);
- for (std::vector<cmGeneratorTarget::SourceAndKind>::const_iterator si =
- sources.Sources.begin();
- si != sources.Sources.end(); ++si) {
+ for (SourceAndKind const& src : sources.Sources) {
std::map<cmSourceFile const*, size_t>::iterator mi =
- index.find(si->Source);
+ index.find(src.Source);
if (mi == index.end()) {
AllConfigSource acs;
- acs.Source = si->Source;
- acs.Kind = si->Kind;
+ acs.Source = src.Source;
+ acs.Kind = src.Kind;
this->AllConfigSources.push_back(acs);
std::map<cmSourceFile const*, size_t>::value_type entry(
- si->Source, this->AllConfigSources.size() - 1);
+ src.Source, this->AllConfigSources.size() - 1);
mi = index.insert(entry).first;
}
this->AllConfigSources[mi->second].Configs.push_back(ci);
@@ -1714,7 +1687,7 @@ const char* cmGeneratorTarget::GetExportMacro() const
}
return this->ExportMacro.c_str();
}
- return CM_NULLPTR;
+ return nullptr;
}
class cmTargetCollectLinkLanguages
@@ -1722,7 +1695,7 @@ class cmTargetCollectLinkLanguages
public:
cmTargetCollectLinkLanguages(cmGeneratorTarget const* target,
const std::string& config,
- CM_UNORDERED_SET<std::string>& languages,
+ std::unordered_set<std::string>& languages,
cmGeneratorTarget const* head)
: Config(config)
, Languages(languages)
@@ -1775,21 +1748,18 @@ public:
return;
}
- for (std::vector<std::string>::const_iterator li =
- iface->Languages.begin();
- li != iface->Languages.end(); ++li) {
- this->Languages.insert(*li);
+ for (std::string const& language : iface->Languages) {
+ this->Languages.insert(language);
}
- for (std::vector<cmLinkItem>::const_iterator li = iface->Libraries.begin();
- li != iface->Libraries.end(); ++li) {
- this->Visit(*li);
+ for (cmLinkItem const& lib : iface->Libraries) {
+ this->Visit(lib);
}
}
private:
std::string Config;
- CM_UNORDERED_SET<std::string>& Languages;
+ std::unordered_set<std::string>& Languages;
cmGeneratorTarget const* HeadTarget;
const cmGeneratorTarget* Target;
std::set<cmGeneratorTarget const*> Visited;
@@ -1844,9 +1814,8 @@ public:
e << "Target " << this->Target->GetName()
<< " contains multiple languages with the highest linker preference"
<< " (" << this->Preference << "):\n";
- for (std::set<std::string>::const_iterator li = this->Preferred.begin();
- li != this->Preferred.end(); ++li) {
- e << " " << *li << "\n";
+ for (std::string const& li : this->Preferred) {
+ e << " " << li << "\n";
}
e << "Set the LINKER_LANGUAGE property for this target.";
cmake* cm = this->Target->GetLocalGenerator()->GetCMakeInstance();
@@ -1861,26 +1830,22 @@ void cmGeneratorTarget::ComputeLinkClosure(const std::string& config,
LinkClosure& lc) const
{
// Get languages built in this target.
- CM_UNORDERED_SET<std::string> languages;
+ std::unordered_set<std::string> languages;
cmLinkImplementation const* impl = this->GetLinkImplementation(config);
assert(impl);
- for (std::vector<std::string>::const_iterator li = impl->Languages.begin();
- li != impl->Languages.end(); ++li) {
- languages.insert(*li);
+ for (std::string const& li : impl->Languages) {
+ languages.insert(li);
}
// Add interface languages from linked targets.
cmTargetCollectLinkLanguages cll(this, config, languages, this);
- for (std::vector<cmLinkImplItem>::const_iterator li =
- impl->Libraries.begin();
- li != impl->Libraries.end(); ++li) {
- cll.Visit(*li);
+ for (cmLinkImplItem const& lib : impl->Libraries) {
+ cll.Visit(lib);
}
// Store the transitive closure of languages.
- for (CM_UNORDERED_SET<std::string>::const_iterator li = languages.begin();
- li != languages.end(); ++li) {
- lc.Languages.push_back(*li);
+ for (std::string const& lang : languages) {
+ lc.Languages.push_back(lang);
}
// Choose the language whose linker should be used.
@@ -1893,18 +1858,16 @@ void cmGeneratorTarget::ComputeLinkClosure(const std::string& config,
cmTargetSelectLinker tsl(this);
// First select from the languages compiled directly in this target.
- for (std::vector<std::string>::const_iterator li = impl->Languages.begin();
- li != impl->Languages.end(); ++li) {
- tsl.Consider(li->c_str());
+ for (std::string const& l : impl->Languages) {
+ tsl.Consider(l.c_str());
}
// Now consider languages that propagate from linked targets.
- for (CM_UNORDERED_SET<std::string>::const_iterator sit = languages.begin();
- sit != languages.end(); ++sit) {
+ for (std::string const& lang : languages) {
std::string propagates =
- "CMAKE_" + *sit + "_LINKER_PREFERENCE_PROPAGATES";
+ "CMAKE_" + lang + "_LINKER_PREFERENCE_PROPAGATES";
if (this->Makefile->IsOn(propagates)) {
- tsl.Consider(sit->c_str());
+ tsl.Consider(lang.c_str());
}
}
@@ -1973,7 +1936,7 @@ cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo(
{
// There is no compile information for imported targets.
if (this->IsImported()) {
- return CM_NULLPTR;
+ return nullptr;
}
if (this->GetType() > cmStateEnums::OBJECT_LIBRARY) {
@@ -1982,7 +1945,7 @@ cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo(
msg += " which has type ";
msg += cmState::GetTargetTypeName(this->GetType());
this->LocalGenerator->IssueMessage(cmake::INTERNAL_ERROR, msg);
- return CM_NULLPTR;
+ return nullptr;
}
// Lookup/compute/cache the compile information for this configuration.
@@ -2008,7 +1971,7 @@ cmGeneratorTarget::GetModuleDefinitionInfo(std::string const& config) const
if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
this->GetType() != cmStateEnums::MODULE_LIBRARY &&
!this->IsExecutableWithExports()) {
- return CM_NULLPTR;
+ return nullptr;
}
// Lookup/compute/cache the compile information for this configuration.
@@ -2059,7 +2022,7 @@ void cmGeneratorTarget::GetAutoUicOptions(std::vector<std::string>& result,
cmGeneratorExpression ge;
cmGeneratorExpressionDAGChecker dagChecker(
- this->GetName(), "AUTOUIC_OPTIONS", CM_NULLPTR, CM_NULLPTR);
+ this->GetName(), "AUTOUIC_OPTIONS", nullptr, nullptr);
cmSystemTools::ExpandListArgument(
ge.Parse(prop)->Evaluate(this->LocalGenerator, config, false, this,
&dagChecker),
@@ -2076,10 +2039,8 @@ void processILibs(const std::string& config,
tgts.push_back(item.Target);
if (cmLinkInterfaceLibraries const* iface =
item.Target->GetLinkInterfaceLibraries(config, headTarget, true)) {
- for (std::vector<cmLinkItem>::const_iterator it =
- iface->Libraries.begin();
- it != iface->Libraries.end(); ++it) {
- processILibs(config, headTarget, *it, gg, tgts, emitted);
+ for (cmLinkItem const& lib : iface->Libraries) {
+ processILibs(config, headTarget, lib, gg, tgts, emitted);
}
}
}
@@ -2097,10 +2058,8 @@ cmGeneratorTarget::GetLinkImplementationClosure(
cmLinkImplementationLibraries const* impl =
this->GetLinkImplementationLibraries(config);
- for (std::vector<cmLinkImplItem>::const_iterator it =
- impl->Libraries.begin();
- it != impl->Libraries.end(); ++it) {
- processILibs(config, this, *it,
+ for (cmLinkImplItem const& lib : impl->Libraries) {
+ processILibs(config, this, lib,
this->LocalGenerator->GetGlobalGenerator(), tgts, emitted);
}
}
@@ -2144,7 +2103,7 @@ cmTargetTraceDependencies::cmTargetTraceDependencies(cmGeneratorTarget* target)
this->Makefile = target->Target->GetMakefile();
this->LocalGenerator = target->GetLocalGenerator();
this->GlobalGenerator = this->LocalGenerator->GetGlobalGenerator();
- this->CurrentEntry = CM_NULLPTR;
+ this->CurrentEntry = nullptr;
// Queue all the source files already specified for the target.
if (target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
@@ -2154,13 +2113,10 @@ cmTargetTraceDependencies::cmTargetTraceDependencies(cmGeneratorTarget* target)
configs.push_back("");
}
std::set<cmSourceFile*> emitted;
- for (std::vector<std::string>::const_iterator ci = configs.begin();
- ci != configs.end(); ++ci) {
+ for (std::string const& c : configs) {
std::vector<cmSourceFile*> sources;
- this->GeneratorTarget->GetSourceFiles(sources, *ci);
- for (std::vector<cmSourceFile*>::const_iterator si = sources.begin();
- si != sources.end(); ++si) {
- cmSourceFile* sf = *si;
+ this->GeneratorTarget->GetSourceFiles(sources, c);
+ for (cmSourceFile* sf : sources) {
const std::set<cmGeneratorTarget const*> tgts =
this->GlobalGenerator->GetFilenameTargetDepends(sf);
if (tgts.find(this->GeneratorTarget) != tgts.end()) {
@@ -2199,10 +2155,9 @@ void cmTargetTraceDependencies::Trace()
if (const char* additionalDeps = sf->GetProperty("OBJECT_DEPENDS")) {
std::vector<std::string> objDeps;
cmSystemTools::ExpandListArgument(additionalDeps, objDeps);
- for (std::vector<std::string>::iterator odi = objDeps.begin();
- odi != objDeps.end(); ++odi) {
- if (cmSystemTools::FileIsFullPath(*odi)) {
- *odi = cmSystemTools::CollapseFullPath(*odi);
+ for (std::string& objDep : objDeps) {
+ if (cmSystemTools::FileIsFullPath(objDep)) {
+ objDep = cmSystemTools::CollapseFullPath(objDep);
}
}
this->FollowNames(objDeps);
@@ -2219,7 +2174,7 @@ void cmTargetTraceDependencies::Trace()
this->CheckCustomCommand(*cc);
}
}
- this->CurrentEntry = CM_NULLPTR;
+ this->CurrentEntry = nullptr;
this->GeneratorTarget->AddTracedSources(this->NewSources);
}
@@ -2255,9 +2210,8 @@ void cmTargetTraceDependencies::FollowName(std::string const& name)
void cmTargetTraceDependencies::FollowNames(
std::vector<std::string> const& names)
{
- for (std::vector<std::string>::const_iterator i = names.begin();
- i != names.end(); ++i) {
- this->FollowName(*i);
+ for (std::string const& name : names) {
+ this->FollowName(name);
}
}
@@ -2317,9 +2271,8 @@ void cmTargetTraceDependencies::CheckCustomCommand(cmCustomCommand const& cc)
// Add target-level dependencies referenced by generator expressions.
std::set<cmGeneratorTarget*> targets;
- for (cmCustomCommandLines::const_iterator cit = cc.GetCommandLines().begin();
- cit != cc.GetCommandLines().end(); ++cit) {
- std::string const& command = *cit->begin();
+ for (cmCustomCommandLine const& cCmdLine : cc.GetCommandLines()) {
+ std::string const& command = *cCmdLine.begin();
// Check for a target with this name.
if (cmGeneratorTarget* t =
this->LocalGenerator->FindGeneratorTargetToUse(command)) {
@@ -2333,18 +2286,16 @@ void cmTargetTraceDependencies::CheckCustomCommand(cmCustomCommand const& cc)
}
// Check for target references in generator expressions.
- for (cmCustomCommandLine::const_iterator cli = cit->begin();
- cli != cit->end(); ++cli) {
- const CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*cli);
+ for (std::string const& cl : cCmdLine) {
+ const std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(cl);
cge->Evaluate(this->GeneratorTarget->GetLocalGenerator(), "", true);
std::set<cmGeneratorTarget*> geTargets = cge->GetTargets();
targets.insert(geTargets.begin(), geTargets.end());
}
}
- for (std::set<cmGeneratorTarget*>::iterator ti = targets.begin();
- ti != targets.end(); ++ti) {
- this->GeneratorTarget->Target->AddUtility((*ti)->GetName());
+ for (cmGeneratorTarget* target : targets) {
+ this->GeneratorTarget->Target->AddUtility(target->GetName());
}
// Queue the custom command dependencies.
@@ -2354,9 +2305,8 @@ void cmTargetTraceDependencies::CheckCustomCommand(cmCustomCommand const& cc)
if (configs.empty()) {
configs.push_back("");
}
- for (std::vector<std::string>::const_iterator ci = configs.begin();
- ci != configs.end(); ++ci) {
- this->FollowCommandDepends(cc, *ci, emitted);
+ for (std::string const& conf : configs) {
+ this->FollowCommandDepends(cc, conf, emitted);
}
}
@@ -2369,9 +2319,7 @@ void cmTargetTraceDependencies::FollowCommandDepends(
const std::vector<std::string>& depends = ccg.GetDepends();
- for (std::vector<std::string>::const_iterator di = depends.begin();
- di != depends.end(); ++di) {
- std::string const& dep = *di;
+ for (std::string const& dep : depends) {
if (emitted.insert(dep).second) {
if (!this->IsUtility(dep)) {
// The dependency does not name a target and may be a file we
@@ -2385,9 +2333,8 @@ void cmTargetTraceDependencies::FollowCommandDepends(
void cmTargetTraceDependencies::CheckCustomCommands(
const std::vector<cmCustomCommand>& commands)
{
- for (std::vector<cmCustomCommand>::const_iterator cli = commands.begin();
- cli != commands.end(); ++cli) {
- this->CheckCustomCommand(*cli);
+ for (cmCustomCommand const& command : commands) {
+ this->CheckCustomCommand(command);
}
}
@@ -2418,7 +2365,7 @@ std::string cmGeneratorTarget::GetCompilePDBDirectory(
void cmGeneratorTarget::GetAppleArchs(const std::string& config,
std::vector<std::string>& archVec) const
{
- const char* archs = CM_NULLPTR;
+ const char* archs = nullptr;
if (!config.empty()) {
std::string defVarName = "OSX_ARCHITECTURES_";
defVarName += cmSystemTools::UpperCase(config);
@@ -2471,28 +2418,24 @@ static void processIncludeDirectories(
cmGeneratorTarget const* tgt,
const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries,
std::vector<std::string>& includes,
- CM_UNORDERED_SET<std::string>& uniqueIncludes,
+ std::unordered_set<std::string>& uniqueIncludes,
cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config,
bool debugIncludes, const std::string& language)
{
- for (std::vector<cmGeneratorTarget::TargetPropertyEntry *>::const_iterator
- it = entries.begin(),
- end = entries.end();
- it != end; ++it) {
- cmLinkImplItem const& item = (*it)->LinkImplItem;
+ for (cmGeneratorTarget::TargetPropertyEntry* entry : entries) {
+ cmLinkImplItem const& item = entry->LinkImplItem;
std::string const& targetName = item;
bool const fromImported = item.Target && item.Target->IsImported();
bool const checkCMP0027 = item.FromGenex;
std::vector<std::string> entryIncludes;
cmSystemTools::ExpandListArgument(
- (*it)->ge->Evaluate(tgt->GetLocalGenerator(), config, false, tgt,
+ entry->ge->Evaluate(tgt->GetLocalGenerator(), config, false, tgt,
dagChecker, language),
entryIncludes);
std::string usedIncludes;
- for (std::vector<std::string>::iterator li = entryIncludes.begin();
- li != entryIncludes.end(); ++li) {
- if (fromImported && !cmSystemTools::FileExists(li->c_str())) {
+ for (std::string& entryInclude : entryIncludes) {
+ if (fromImported && !cmSystemTools::FileExists(entryInclude.c_str())) {
std::ostringstream e;
cmake::MessageType messageType = cmake::FATAL_ERROR;
if (checkCMP0027) {
@@ -2511,7 +2454,7 @@ static void processIncludeDirectories(
}
/* clang-format off */
e << "Imported target \"" << targetName << "\" includes "
- "non-existent path\n \"" << *li << "\"\nin its "
+ "non-existent path\n \"" << entryInclude << "\"\nin its "
"INTERFACE_INCLUDE_DIRECTORIES. Possible reasons include:\n"
"* The path was deleted, renamed, or moved to another "
"location.\n"
@@ -2524,7 +2467,7 @@ static void processIncludeDirectories(
return;
}
- if (!cmSystemTools::FileIsFullPath(li->c_str())) {
+ if (!cmSystemTools::FileIsFullPath(entryInclude.c_str())) {
std::ostringstream e;
bool noMessage = false;
cmake::MessageType messageType = cmake::FATAL_ERROR;
@@ -2532,7 +2475,7 @@ static void processIncludeDirectories(
/* clang-format off */
e << "Target \"" << targetName << "\" contains relative "
"path in its INTERFACE_INCLUDE_DIRECTORIES:\n"
- " \"" << *li << "\"";
+ " \"" << entryInclude << "\"";
/* clang-format on */
} else {
switch (tgt->GetPolicyStatusCMP0021()) {
@@ -2550,7 +2493,7 @@ static void processIncludeDirectories(
}
e << "Found relative path while evaluating include directories of "
"\""
- << tgt->GetName() << "\":\n \"" << *li << "\"\n";
+ << tgt->GetName() << "\":\n \"" << entryInclude << "\"\n";
}
if (!noMessage) {
tgt->GetLocalGenerator()->IssueMessage(messageType, e.str());
@@ -2560,10 +2503,10 @@ static void processIncludeDirectories(
}
}
- if (!cmSystemTools::IsOff(li->c_str())) {
- cmSystemTools::ConvertToUnixSlashes(*li);
+ if (!cmSystemTools::IsOff(entryInclude.c_str())) {
+ cmSystemTools::ConvertToUnixSlashes(entryInclude);
}
- std::string inc = *li;
+ std::string inc = entryInclude;
if (uniqueIncludes.insert(inc).second) {
includes.push_back(inc);
@@ -2576,7 +2519,7 @@ static void processIncludeDirectories(
tgt->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
cmake::LOG, std::string("Used includes for target ") + tgt->GetName() +
":\n" + usedIncludes,
- (*it)->ge->GetBacktrace());
+ entry->ge->GetBacktrace());
}
}
}
@@ -2585,10 +2528,10 @@ std::vector<std::string> cmGeneratorTarget::GetIncludeDirectories(
const std::string& config, const std::string& lang) const
{
std::vector<std::string> includes;
- CM_UNORDERED_SET<std::string> uniqueIncludes;
+ std::unordered_set<std::string> uniqueIncludes;
cmGeneratorExpressionDAGChecker dagChecker(
- this->GetName(), "INCLUDE_DIRECTORIES", CM_NULLPTR, CM_NULLPTR);
+ this->GetName(), "INCLUDE_DIRECTORIES", nullptr, nullptr);
std::vector<std::string> debugProperties;
const char* debugProp =
@@ -2617,10 +2560,8 @@ std::vector<std::string> cmGeneratorTarget::GetIncludeDirectories(
if (this->Makefile->IsOn("APPLE")) {
cmLinkImplementationLibraries const* impl =
this->GetLinkImplementationLibraries(config);
- for (std::vector<cmLinkImplItem>::const_iterator it =
- impl->Libraries.begin();
- it != impl->Libraries.end(); ++it) {
- std::string libDir = cmSystemTools::CollapseFullPath(*it);
+ for (cmLinkImplItem const& lib : impl->Libraries) {
+ std::string libDir = cmSystemTools::CollapseFullPath(lib);
static cmsys::RegularExpression frameworkCheck(
"(.*\\.framework)(/Versions/[^/]+)?/[^/]+$");
@@ -2631,10 +2572,10 @@ std::vector<std::string> cmGeneratorTarget::GetIncludeDirectories(
libDir = frameworkCheck.match(1);
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
+ std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(libDir.c_str());
linkInterfaceIncludeDirectoriesEntries.push_back(
- new cmGeneratorTarget::TargetPropertyEntry(cge));
+ new cmGeneratorTarget::TargetPropertyEntry(std::move(cge)));
}
}
@@ -2651,24 +2592,18 @@ static void processCompileOptionsInternal(
cmGeneratorTarget const* tgt,
const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries,
std::vector<std::string>& options,
- CM_UNORDERED_SET<std::string>& uniqueOptions,
+ std::unordered_set<std::string>& uniqueOptions,
cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config,
bool debugOptions, const char* logName, std::string const& language)
{
- for (std::vector<cmGeneratorTarget::TargetPropertyEntry *>::const_iterator
- it = entries.begin(),
- end = entries.end();
- it != end; ++it) {
+ for (cmGeneratorTarget::TargetPropertyEntry* entry : entries) {
std::vector<std::string> entryOptions;
cmSystemTools::ExpandListArgument(
- (*it)->ge->Evaluate(tgt->GetLocalGenerator(), config, false, tgt,
+ entry->ge->Evaluate(tgt->GetLocalGenerator(), config, false, tgt,
dagChecker, language),
entryOptions);
std::string usedOptions;
- for (std::vector<std::string>::iterator li = entryOptions.begin();
- li != entryOptions.end(); ++li) {
- std::string const& opt = *li;
-
+ for (std::string const& opt : entryOptions) {
if (uniqueOptions.insert(opt).second) {
options.push_back(opt);
if (debugOptions) {
@@ -2680,7 +2615,7 @@ static void processCompileOptionsInternal(
tgt->GetLocalGenerator()->GetCMakeInstance()->IssueMessage(
cmake::LOG, std::string("Used compile ") + logName +
std::string(" for target ") + tgt->GetName() + ":\n" + usedOptions,
- (*it)->ge->GetBacktrace());
+ entry->ge->GetBacktrace());
}
}
}
@@ -2689,7 +2624,7 @@ static void processCompileOptions(
cmGeneratorTarget const* tgt,
const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries,
std::vector<std::string>& options,
- CM_UNORDERED_SET<std::string>& uniqueOptions,
+ std::unordered_set<std::string>& uniqueOptions,
cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config,
bool debugOptions, std::string const& language)
{
@@ -2702,10 +2637,10 @@ void cmGeneratorTarget::GetCompileOptions(std::vector<std::string>& result,
const std::string& config,
const std::string& language) const
{
- CM_UNORDERED_SET<std::string> uniqueOptions;
+ std::unordered_set<std::string> uniqueOptions;
cmGeneratorExpressionDAGChecker dagChecker(
- this->GetName(), "COMPILE_OPTIONS", CM_NULLPTR, CM_NULLPTR);
+ this->GetName(), "COMPILE_OPTIONS", nullptr, nullptr);
std::vector<std::string> debugProperties;
const char* debugProp =
@@ -2743,7 +2678,7 @@ static void processCompileFeatures(
cmGeneratorTarget const* tgt,
const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries,
std::vector<std::string>& options,
- CM_UNORDERED_SET<std::string>& uniqueOptions,
+ std::unordered_set<std::string>& uniqueOptions,
cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config,
bool debugOptions)
{
@@ -2755,10 +2690,10 @@ static void processCompileFeatures(
void cmGeneratorTarget::GetCompileFeatures(std::vector<std::string>& result,
const std::string& config) const
{
- CM_UNORDERED_SET<std::string> uniqueFeatures;
+ std::unordered_set<std::string> uniqueFeatures;
cmGeneratorExpressionDAGChecker dagChecker(
- this->GetName(), "COMPILE_FEATURES", CM_NULLPTR, CM_NULLPTR);
+ this->GetName(), "COMPILE_FEATURES", nullptr, nullptr);
std::vector<std::string> debugProperties;
const char* debugProp =
@@ -2793,7 +2728,7 @@ static void processCompileDefinitions(
cmGeneratorTarget const* tgt,
const std::vector<cmGeneratorTarget::TargetPropertyEntry*>& entries,
std::vector<std::string>& options,
- CM_UNORDERED_SET<std::string>& uniqueOptions,
+ std::unordered_set<std::string>& uniqueOptions,
cmGeneratorExpressionDAGChecker* dagChecker, const std::string& config,
bool debugOptions, std::string const& language)
{
@@ -2806,10 +2741,10 @@ void cmGeneratorTarget::GetCompileDefinitions(
std::vector<std::string>& list, const std::string& config,
const std::string& language) const
{
- CM_UNORDERED_SET<std::string> uniqueOptions;
+ std::unordered_set<std::string> uniqueOptions;
cmGeneratorExpressionDAGChecker dagChecker(
- this->GetName(), "COMPILE_DEFINITIONS", CM_NULLPTR, CM_NULLPTR);
+ this->GetName(), "COMPILE_DEFINITIONS", nullptr, nullptr);
std::vector<std::string> debugProperties;
const char* debugProp =
@@ -2848,10 +2783,10 @@ void cmGeneratorTarget::GetCompileDefinitions(
}
case cmPolicies::OLD: {
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
+ std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(configProp);
linkInterfaceCompileDefinitionsEntries.push_back(
- new cmGeneratorTarget::TargetPropertyEntry(cge));
+ new cmGeneratorTarget::TargetPropertyEntry(std::move(cge)));
} break;
case cmPolicies::NEW:
case cmPolicies::REQUIRED_ALWAYS:
@@ -2933,9 +2868,8 @@ bool cmGeneratorTarget::ComputeCompileFeatures(std::string const& config) const
{
std::vector<std::string> features;
this->GetCompileFeatures(features, config);
- for (std::vector<std::string>::const_iterator it = features.begin();
- it != features.end(); ++it) {
- if (!this->Makefile->AddRequiredTargetFeature(this->Target, *it)) {
+ for (std::string const& f : features) {
+ if (!this->Makefile->AddRequiredTargetFeature(this->Target, f)) {
return false;
}
}
@@ -3045,8 +2979,8 @@ void cmGeneratorTarget::GetLibraryNames(std::string& name, std::string& soName,
this->IsFrameworkOnApple()) {
// Versioning is supported only for shared libraries and modules,
// and then only when the platform supports an soname flag.
- version = CM_NULLPTR;
- soversion = CM_NULLPTR;
+ version = nullptr;
+ soversion = nullptr;
}
if (version && !soversion) {
// The soversion must be set if the library version is set. Use
@@ -3091,7 +3025,7 @@ void cmGeneratorTarget::GetLibraryNames(std::string& name, std::string& soName,
impName =
this->GetFullNameInternal(config, cmStateEnums::ImportLibraryArtifact);
} else {
- impName = "";
+ impName.clear();
}
// The program database file name.
@@ -3122,7 +3056,7 @@ void cmGeneratorTarget::GetExecutableNames(std::string& name,
const char* version = this->GetProperty("VERSION");
if (this->GetType() != cmStateEnums::EXECUTABLE ||
this->Makefile->IsOn("XCODE")) {
- version = CM_NULLPTR;
+ version = nullptr;
}
#endif
@@ -3194,9 +3128,9 @@ void cmGeneratorTarget::GetFullNameInternal(
this->GetType() != cmStateEnums::SHARED_LIBRARY &&
this->GetType() != cmStateEnums::MODULE_LIBRARY &&
this->GetType() != cmStateEnums::EXECUTABLE) {
- outPrefix = "";
+ outPrefix.clear();
outBase = this->GetName();
- outSuffix = "";
+ outSuffix.clear();
return;
}
@@ -3207,9 +3141,9 @@ void cmGeneratorTarget::GetFullNameInternal(
// does not support import libraries.
if (isImportedLibraryArtifact &&
!this->Makefile->GetDefinition("CMAKE_IMPORT_LIBRARY_SUFFIX")) {
- outPrefix = "";
- outBase = "";
- outSuffix = "";
+ outPrefix.clear();
+ outBase.clear();
+ outSuffix.clear();
return;
}
@@ -3228,7 +3162,7 @@ void cmGeneratorTarget::GetFullNameInternal(
const char* targetSuffix =
(isImportedLibraryArtifact ? this->GetProperty("IMPORT_SUFFIX")
: this->GetProperty("SUFFIX"));
- const char* configPostfix = CM_NULLPTR;
+ const char* configPostfix = nullptr;
if (!config.empty()) {
std::string configProp = cmSystemTools::UpperCase(config);
configProp += "_POSTFIX";
@@ -3236,7 +3170,7 @@ void cmGeneratorTarget::GetFullNameInternal(
// Mac application bundles and frameworks have no postfix.
if (configPostfix &&
(this->IsAppBundleOnApple() || this->IsFrameworkOnApple())) {
- configPostfix = CM_NULLPTR;
+ configPostfix = nullptr;
}
}
const char* prefixVar = this->Target->GetPrefixVariableInternal(artifact);
@@ -3270,14 +3204,14 @@ void cmGeneratorTarget::GetFullNameInternal(
fw_prefix = this->GetFrameworkDirectory(config, ContentLevel);
fw_prefix += "/";
targetPrefix = fw_prefix.c_str();
- targetSuffix = CM_NULLPTR;
+ targetSuffix = nullptr;
}
if (this->IsCFBundleOnApple()) {
fw_prefix = this->GetCFBundleDirectory(config, FullLevel);
fw_prefix += "/";
targetPrefix = fw_prefix.c_str();
- targetSuffix = CM_NULLPTR;
+ targetSuffix = nullptr;
}
// Begin the final name with the prefix.
@@ -3327,9 +3261,8 @@ std::string cmGeneratorTarget::GetPDBName(const std::string& config) const
// PDB_NAME
props.push_back("PDB_NAME");
- for (std::vector<std::string>::const_iterator i = props.begin();
- i != props.end(); ++i) {
- if (const char* outName = this->GetProperty(*i)) {
+ for (std::string const& p : props) {
+ if (const char* outName = this->GetProperty(p)) {
base = outName;
break;
}
@@ -3357,20 +3290,16 @@ void cmGeneratorTarget::GetTargetObjectNames(
this->GetObjectSources(objectSources, config);
std::map<cmSourceFile const*, std::string> mapping;
- for (std::vector<cmSourceFile const*>::const_iterator it =
- objectSources.begin();
- it != objectSources.end(); ++it) {
- mapping[*it];
+ for (cmSourceFile const* sf : objectSources) {
+ mapping[sf];
}
this->LocalGenerator->ComputeObjectFilenames(mapping, this);
- for (std::vector<cmSourceFile const*>::const_iterator it =
- objectSources.begin();
- it != objectSources.end(); ++it) {
+ for (cmSourceFile const* src : objectSources) {
// Find the object file name corresponding to this source file.
std::map<cmSourceFile const*, std::string>::const_iterator map_it =
- mapping.find(*it);
+ mapping.find(src);
// It must exist because we populated the mapping just above.
assert(!map_it->second.empty());
objects.push_back(map_it->second);
@@ -3433,9 +3362,8 @@ void cmGeneratorTarget::ConstructSourceFileFlags() const
if (const char* files = this->GetProperty("PUBLIC_HEADER")) {
std::vector<std::string> relFiles;
cmSystemTools::ExpandListArgument(files, relFiles);
- for (std::vector<std::string>::iterator it = relFiles.begin();
- it != relFiles.end(); ++it) {
- if (cmSourceFile* sf = this->Makefile->GetSource(*it)) {
+ for (std::string const& relFile : relFiles) {
+ if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
SourceFileFlags& flags = this->SourceFlagsMap[sf];
flags.MacFolder = "Headers";
flags.Type = cmGeneratorTarget::SourceFileTypePublicHeader;
@@ -3448,9 +3376,8 @@ void cmGeneratorTarget::ConstructSourceFileFlags() const
if (const char* files = this->GetProperty("PRIVATE_HEADER")) {
std::vector<std::string> relFiles;
cmSystemTools::ExpandListArgument(files, relFiles);
- for (std::vector<std::string>::iterator it = relFiles.begin();
- it != relFiles.end(); ++it) {
- if (cmSourceFile* sf = this->Makefile->GetSource(*it)) {
+ for (std::string const& relFile : relFiles) {
+ if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
SourceFileFlags& flags = this->SourceFlagsMap[sf];
flags.MacFolder = "PrivateHeaders";
flags.Type = cmGeneratorTarget::SourceFileTypePrivateHeader;
@@ -3462,9 +3389,8 @@ void cmGeneratorTarget::ConstructSourceFileFlags() const
if (const char* files = this->GetProperty("RESOURCE")) {
std::vector<std::string> relFiles;
cmSystemTools::ExpandListArgument(files, relFiles);
- for (std::vector<std::string>::iterator it = relFiles.begin();
- it != relFiles.end(); ++it) {
- if (cmSourceFile* sf = this->Makefile->GetSource(*it)) {
+ for (std::string const& relFile : relFiles) {
+ if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
SourceFileFlags& flags = this->SourceFlagsMap[sf];
flags.MacFolder = "";
if (!this->GlobalGenerator->ShouldStripResourcePath(this->Makefile)) {
@@ -3487,11 +3413,9 @@ cmGeneratorTarget::GetCompatibleInterfaces(std::string const& config) const
compat.PropsString.insert("AUTOUIC_OPTIONS");
std::vector<cmGeneratorTarget const*> const& deps =
this->GetLinkImplementationClosure(config);
- for (std::vector<cmGeneratorTarget const*>::const_iterator li =
- deps.begin();
- li != deps.end(); ++li) {
+ for (cmGeneratorTarget const* li : deps) {
#define CM_READ_COMPATIBLE_INTERFACE(X, x) \
- if (const char* prop = (*li)->GetProperty("COMPATIBLE_INTERFACE_" #X)) { \
+ if (const char* prop = li->GetProperty("COMPATIBLE_INTERFACE_" #X)) { \
std::vector<std::string> props; \
cmSystemTools::ExpandListArgument(prop, props); \
compat.Props##x.insert(props.begin(), props.end()); \
@@ -3581,7 +3505,7 @@ const char* getLinkInterfaceDependentProperty(cmGeneratorTarget const* tgt,
case BoolType:
assert(false &&
"String compatibility check function called for boolean");
- return CM_NULLPTR;
+ return nullptr;
case StringType:
return tgt->GetLinkInterfaceDependentStringProperty(prop, config);
case NumberMinType:
@@ -3590,7 +3514,7 @@ const char* getLinkInterfaceDependentProperty(cmGeneratorTarget const* tgt,
return tgt->GetLinkInterfaceDependentNumberMaxProperty(prop, config);
}
assert(false && "Unreachable!");
- return CM_NULLPTR;
+ return nullptr;
}
template <typename PropertyType>
@@ -3611,13 +3535,12 @@ void checkPropertyConsistency(cmGeneratorTarget const* depender,
std::string pdir = cmSystemTools::GetCMakeRoot();
pdir += "/Help/prop_tgt/";
- for (std::vector<std::string>::iterator pi = props.begin();
- pi != props.end(); ++pi) {
- std::string pname = cmSystemTools::HelpFileName(*pi);
+ for (std::string const& p : props) {
+ std::string pname = cmSystemTools::HelpFileName(p);
std::string pfile = pdir + pname + ".rst";
if (cmSystemTools::FileExists(pfile.c_str(), true)) {
std::ostringstream e;
- e << "Target \"" << dependee->GetName() << "\" has property \"" << *pi
+ e << "Target \"" << dependee->GetName() << "\" has property \"" << p
<< "\" listed in its " << propName
<< " property. "
"This is not allowed. Only user-defined properties may appear "
@@ -3626,9 +3549,9 @@ void checkPropertyConsistency(cmGeneratorTarget const* depender,
depender->GetLocalGenerator()->IssueMessage(cmake::FATAL_ERROR, e.str());
return;
}
- if (emitted.insert(*pi).second) {
- getLinkInterfaceDependentProperty<PropertyType>(depender, *pi, config, t,
- CM_NULLPTR);
+ if (emitted.insert(p).second) {
+ getLinkInterfaceDependentProperty<PropertyType>(depender, p, config, t,
+ nullptr);
if (cmSystemTools::GetErrorOccuredFlag()) {
return;
}
@@ -3699,32 +3622,31 @@ void cmGeneratorTarget::CheckPropertyCompatibility(
std::set<std::string> emittedMaxNumbers;
static std::string strNumMax = "COMPATIBLE_INTERFACE_NUMBER_MAX";
- for (cmComputeLinkInformation::ItemVector::const_iterator li = deps.begin();
- li != deps.end(); ++li) {
- if (!li->Target) {
+ for (auto const& dep : deps) {
+ if (!dep.Target) {
continue;
}
- checkPropertyConsistency<bool>(this, li->Target, strBool, emittedBools,
- config, BoolType, CM_NULLPTR);
+ checkPropertyConsistency<bool>(this, dep.Target, strBool, emittedBools,
+ config, BoolType, nullptr);
if (cmSystemTools::GetErrorOccuredFlag()) {
return;
}
- checkPropertyConsistency<const char*>(this, li->Target, strString,
+ checkPropertyConsistency<const char*>(this, dep.Target, strString,
emittedStrings, config, StringType,
- CM_NULLPTR);
+ nullptr);
if (cmSystemTools::GetErrorOccuredFlag()) {
return;
}
- checkPropertyConsistency<const char*>(this, li->Target, strNumMin,
+ checkPropertyConsistency<const char*>(this, dep.Target, strNumMin,
emittedMinNumbers, config,
- NumberMinType, CM_NULLPTR);
+ NumberMinType, nullptr);
if (cmSystemTools::GetErrorOccuredFlag()) {
return;
}
- checkPropertyConsistency<const char*>(this, li->Target, strNumMax,
+ checkPropertyConsistency<const char*>(this, dep.Target, strNumMax,
emittedMaxNumbers, config,
- NumberMaxType, CM_NULLPTR);
+ NumberMaxType, nullptr);
if (cmSystemTools::GetErrorOccuredFlag()) {
return;
}
@@ -3858,7 +3780,7 @@ std::pair<bool, const char*> consistentStringProperty(const char* lhs,
const char* rhs)
{
const bool b = strcmp(lhs, rhs) == 0;
- return std::make_pair(b, b ? lhs : CM_NULLPTR);
+ return std::make_pair(b, b ? lhs : nullptr);
}
std::pair<bool, const char*> consistentNumberProperty(const char* lhs,
@@ -3867,7 +3789,7 @@ std::pair<bool, const char*> consistentNumberProperty(const char* lhs,
{
char* pEnd;
- const char* const null_ptr = CM_NULLPTR;
+ const char* const null_ptr = nullptr;
long lnum = strtol(lhs, &pEnd, 0);
if (pEnd == lhs || *pEnd != '\0' || errno == ERANGE) {
@@ -3900,7 +3822,7 @@ std::pair<bool, const char*> consistentProperty(const char* lhs,
return std::make_pair(true, lhs);
}
- const char* const null_ptr = CM_NULLPTR;
+ const char* const null_ptr = nullptr;
switch (t) {
case BoolType:
@@ -3954,16 +3876,13 @@ PropertyType checkInterfacePropertyCompatibility(cmGeneratorTarget const* tgt,
}
std::string interfaceProperty = "INTERFACE_" + p;
- for (std::vector<cmGeneratorTarget const*>::const_iterator li = deps.begin();
- li != deps.end(); ++li) {
+ for (cmGeneratorTarget const* theTarget : deps) {
// An error should be reported if one dependency
// has INTERFACE_POSITION_INDEPENDENT_CODE ON and the other
// has INTERFACE_POSITION_INDEPENDENT_CODE OFF, or if the
// target itself has a POSITION_INDEPENDENT_CODE which disagrees
// with a dependency.
- cmGeneratorTarget const* theTarget = *li;
-
std::vector<std::string> propKeys = theTarget->GetPropertyKeys();
const bool ifaceIsSet = std::find(propKeys.begin(), propKeys.end(),
@@ -4063,28 +3982,28 @@ bool cmGeneratorTarget::GetLinkInterfaceDependentBoolProperty(
const std::string& p, const std::string& config) const
{
return checkInterfacePropertyCompatibility<bool>(this, p, config, "FALSE",
- BoolType, CM_NULLPTR);
+ BoolType, nullptr);
}
const char* cmGeneratorTarget::GetLinkInterfaceDependentStringProperty(
const std::string& p, const std::string& config) const
{
return checkInterfacePropertyCompatibility<const char*>(
- this, p, config, "empty", StringType, CM_NULLPTR);
+ this, p, config, "empty", StringType, nullptr);
}
const char* cmGeneratorTarget::GetLinkInterfaceDependentNumberMinProperty(
const std::string& p, const std::string& config) const
{
return checkInterfacePropertyCompatibility<const char*>(
- this, p, config, "empty", NumberMinType, CM_NULLPTR);
+ this, p, config, "empty", NumberMinType, nullptr);
}
const char* cmGeneratorTarget::GetLinkInterfaceDependentNumberMaxProperty(
const std::string& p, const std::string& config) const
{
return checkInterfacePropertyCompatibility<const char*>(
- this, p, config, "empty", NumberMaxType, CM_NULLPTR);
+ this, p, config, "empty", NumberMaxType, nullptr);
}
cmComputeLinkInformation* cmGeneratorTarget::GetLinkInformation(
@@ -4099,7 +4018,7 @@ cmComputeLinkInformation* cmGeneratorTarget::GetLinkInformation(
new cmComputeLinkInformation(this, config);
if (!info || !info->Compute()) {
delete info;
- info = CM_NULLPTR;
+ info = nullptr;
}
// Store the information for this configuration.
@@ -4233,9 +4152,8 @@ std::vector<std::string> cmGeneratorTarget::GetPropertyKeys() const
cmPropertyMap const& propsObject = this->Target->GetProperties();
std::vector<std::string> props;
props.reserve(propsObject.size());
- for (cmPropertyMap::const_iterator it = propsObject.begin();
- it != propsObject.end(); ++it) {
- props.push_back(it->first);
+ for (auto const& it : propsObject) {
+ props.push_back(it.first);
}
return props;
}
@@ -4275,9 +4193,8 @@ void cmGeneratorTarget::ReportPropertyOrigin(
void cmGeneratorTarget::LookupLinkItems(std::vector<std::string> const& names,
std::vector<cmLinkItem>& items) const
{
- for (std::vector<std::string>::const_iterator i = names.begin();
- i != names.end(); ++i) {
- std::string name = this->CheckCMP0004(*i);
+ for (std::string const& n : names) {
+ std::string name = this->CheckCMP0004(n);
if (name == this->GetName() || name.empty()) {
continue;
}
@@ -4291,15 +4208,15 @@ void cmGeneratorTarget::ExpandLinkItems(
std::vector<cmLinkItem>& items, bool& hadHeadSensitiveCondition) const
{
cmGeneratorExpression ge;
- cmGeneratorExpressionDAGChecker dagChecker(this->GetName(), prop, CM_NULLPTR,
- CM_NULLPTR);
+ cmGeneratorExpressionDAGChecker dagChecker(this->GetName(), prop, nullptr,
+ nullptr);
// The $<LINK_ONLY> expression may be in a link interface to specify private
// link dependencies that are otherwise excluded from usage requirements.
if (usage_requirements_only) {
dagChecker.SetTransitivePropertiesOnly();
}
std::vector<std::string> libs;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(value);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(value);
cmSystemTools::ExpandListArgument(cge->Evaluate(this->LocalGenerator, config,
false, headTarget, this,
&dagChecker),
@@ -4320,7 +4237,7 @@ cmLinkInterface const* cmGeneratorTarget::GetLinkInterface(
// export symbols.
if (this->GetType() == cmStateEnums::EXECUTABLE &&
!this->IsExecutableWithExports()) {
- return CM_NULLPTR;
+ return nullptr;
}
// Lookup any existing link interface for this configuration.
@@ -4344,7 +4261,7 @@ cmLinkInterface const* cmGeneratorTarget::GetLinkInterface(
}
}
- return iface.Exists ? &iface : CM_NULLPTR;
+ return iface.Exists ? &iface : nullptr;
}
void cmGeneratorTarget::ComputeLinkInterface(
@@ -4357,22 +4274,18 @@ void cmGeneratorTarget::ComputeLinkInterface(
this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
// Shared libraries may have runtime implementation dependencies
// on other shared libraries that are not in the interface.
- CM_UNORDERED_SET<std::string> emitted;
- for (std::vector<cmLinkItem>::const_iterator li =
- iface.Libraries.begin();
- li != iface.Libraries.end(); ++li) {
- emitted.insert(*li);
+ std::unordered_set<std::string> emitted;
+ for (cmLinkItem const& lib : iface.Libraries) {
+ emitted.insert(lib);
}
if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
cmLinkImplementation const* impl = this->GetLinkImplementation(config);
- for (std::vector<cmLinkImplItem>::const_iterator li =
- impl->Libraries.begin();
- li != impl->Libraries.end(); ++li) {
- if (emitted.insert(*li).second) {
- if (li->Target) {
+ for (cmLinkImplItem const& lib : impl->Libraries) {
+ if (emitted.insert(lib).second) {
+ if (lib.Target) {
// This is a runtime dependency on another shared library.
- if (li->Target->GetType() == cmStateEnums::SHARED_LIBRARY) {
- iface.SharedDeps.push_back(*li);
+ if (lib.Target->GetType() == cmStateEnums::SHARED_LIBRARY) {
+ iface.SharedDeps.push_back(lib);
}
} else {
// TODO: Recognize shared library file names. Perhaps this
@@ -4436,7 +4349,7 @@ const cmLinkInterfaceLibraries* cmGeneratorTarget::GetLinkInterfaceLibraries(
// export symbols.
if (this->GetType() == cmStateEnums::EXECUTABLE &&
!this->IsExecutableWithExports()) {
- return CM_NULLPTR;
+ return nullptr;
}
// Lookup any existing link interface for this configuration.
@@ -4459,7 +4372,7 @@ const cmLinkInterfaceLibraries* cmGeneratorTarget::GetLinkInterfaceLibraries(
usage_requirements_only);
}
- return iface.Exists ? &iface : CM_NULLPTR;
+ return iface.Exists ? &iface : nullptr;
}
std::string cmGeneratorTarget::GetDirectory(
@@ -4494,7 +4407,7 @@ cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
{
// There is no output information for imported targets.
if (this->IsImported()) {
- return CM_NULLPTR;
+ return nullptr;
}
// Only libraries and executables have well-defined output files.
@@ -4504,7 +4417,7 @@ cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
msg += " which has type ";
msg += cmState::GetTargetTypeName(this->GetType());
this->LocalGenerator->IssueMessage(cmake::INTERNAL_ERROR, msg);
- return CM_NULLPTR;
+ return nullptr;
}
// Lookup/compute/cache the output information for this configuration.
@@ -4537,7 +4450,7 @@ cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
cmake::FATAL_ERROR,
"Target '" + this->GetName() + "' OUTPUT_DIRECTORY depends on itself.",
this->GetBacktrace());
- return CM_NULLPTR;
+ return nullptr;
}
return &i->second;
}
@@ -4552,7 +4465,7 @@ bool cmGeneratorTarget::ComputeOutputDir(const std::string& config,
// Look for a target property defining the target output directory
// based on the target type.
std::string targetTypeName = this->GetOutputTargetType(artifact);
- const char* propertyName = CM_NULLPTR;
+ const char* propertyName = nullptr;
std::string propertyNameStr = targetTypeName;
if (!propertyNameStr.empty()) {
propertyNameStr += "_OUTPUT_DIRECTORY";
@@ -4561,7 +4474,7 @@ bool cmGeneratorTarget::ComputeOutputDir(const std::string& config,
// Check for a per-configuration output directory target property.
std::string configUpper = cmSystemTools::UpperCase(conf);
- const char* configProp = CM_NULLPTR;
+ const char* configProp = nullptr;
std::string configPropStr = targetTypeName;
if (!configPropStr.empty()) {
configPropStr += "_OUTPUT_DIRECTORY_";
@@ -4573,21 +4486,22 @@ bool cmGeneratorTarget::ComputeOutputDir(const std::string& config,
if (const char* config_outdir = this->GetProperty(configProp)) {
// Use the user-specified per-configuration output directory.
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(config_outdir);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge =
+ ge.Parse(config_outdir);
out = cge->Evaluate(this->LocalGenerator, config);
// Skip per-configuration subdirectory.
- conf = "";
+ conf.clear();
} else if (const char* outdir = this->GetProperty(propertyName)) {
// Use the user-specified output directory.
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(outdir);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(outdir);
out = cge->Evaluate(this->LocalGenerator, config);
// Skip per-configuration subdirectory if the value contained a
// generator expression.
if (out != outdir) {
- conf = "";
+ conf.clear();
}
} else if (this->GetType() == cmStateEnums::EXECUTABLE) {
// Lookup the output path for executables.
@@ -4629,7 +4543,7 @@ bool cmGeneratorTarget::ComputePDBOutputDir(const std::string& kind,
{
// Look for a target property defining the target output directory
// based on the target type.
- const char* propertyName = CM_NULLPTR;
+ const char* propertyName = nullptr;
std::string propertyNameStr = kind;
if (!propertyNameStr.empty()) {
propertyNameStr += "_OUTPUT_DIRECTORY";
@@ -4639,7 +4553,7 @@ bool cmGeneratorTarget::ComputePDBOutputDir(const std::string& kind,
// Check for a per-configuration output directory target property.
std::string configUpper = cmSystemTools::UpperCase(conf);
- const char* configProp = CM_NULLPTR;
+ const char* configProp = nullptr;
std::string configPropStr = kind;
if (!configPropStr.empty()) {
configPropStr += "_OUTPUT_DIRECTORY_";
@@ -4653,7 +4567,7 @@ bool cmGeneratorTarget::ComputePDBOutputDir(const std::string& kind,
out = config_outdir;
// Skip per-configuration subdirectory.
- conf = "";
+ conf.clear();
} else if (const char* outdir = this->GetProperty(propertyName)) {
// Use the user-specified output directory.
out = outdir;
@@ -4697,7 +4611,7 @@ void cmGeneratorTarget::ComputeLinkInterfaceLibraries(
// An explicit list of interface libraries may be set for shared
// libraries and executables that export symbols.
- const char* explicitLibraries = CM_NULLPTR;
+ const char* explicitLibraries = nullptr;
std::string linkIfaceProp;
if (this->GetPolicyStatusCMP0022() != cmPolicies::OLD &&
this->GetPolicyStatusCMP0022() != cmPolicies::WARN) {
@@ -4740,7 +4654,7 @@ void cmGeneratorTarget::ComputeLinkInterfaceLibraries(
"INTERFACE_LINK_LIBRARIES:\n"
" " << newExplicitLibraries << "\n" <<
linkIfaceProp << ":\n"
- " " << (explicitLibraries ? explicitLibraries : "(empty)") << "\n";
+ " " << explicitLibraries << "\n";
/* clang-format on */
this->LocalGenerator->IssueMessage(cmake::AUTHOR_WARNING, w.str());
this->PolicyWarnedCMP0022 = true;
@@ -4824,7 +4738,7 @@ const cmLinkInterface* cmGeneratorTarget::GetImportLinkInterface(
{
cmGeneratorTarget::ImportInfo const* info = this->GetImportInfo(config);
if (!info) {
- return CM_NULLPTR;
+ return nullptr;
}
std::string CONFIG = cmSystemTools::UpperCase(config);
@@ -4860,7 +4774,7 @@ cmGeneratorTarget::ImportInfo const* cmGeneratorTarget::GetImportInfo(
{
// There is no imported information for non-imported targets.
if (!this->IsImported()) {
- return CM_NULLPTR;
+ return nullptr;
}
// Lookup/compute/cache the import information for this
@@ -4886,7 +4800,7 @@ cmGeneratorTarget::ImportInfo const* cmGeneratorTarget::GetImportInfo(
// If the location is empty then the target is not available for
// this configuration.
if (i->second.Location.empty() && i->second.ImportLibrary.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
// Return the import information.
@@ -4903,8 +4817,8 @@ void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
// Initialize members.
info.NoSOName = false;
- const char* loc = CM_NULLPTR;
- const char* imp = CM_NULLPTR;
+ const char* loc = nullptr;
+ const char* imp = nullptr;
std::string suffix;
if (!this->Target->GetMappedConfig(desired_config, &loc, &imp, suffix)) {
return;
@@ -5049,7 +4963,7 @@ const cmLinkImplementation* cmGeneratorTarget::GetLinkImplementation(
{
// There is no link implementation for imported targets.
if (this->IsImported()) {
- return CM_NULLPTR;
+ return nullptr;
}
std::string CONFIG = cmSystemTools::UpperCase(config);
@@ -5084,19 +4998,17 @@ bool cmGeneratorTarget::GetConfigCommonSourceFiles(
if (configFiles != files) {
std::string firstConfigFiles;
const char* sep = "";
- for (std::vector<cmSourceFile*>::const_iterator fi = files.begin();
- fi != files.end(); ++fi) {
+ for (cmSourceFile* f : files) {
firstConfigFiles += sep;
- firstConfigFiles += (*fi)->GetFullPath();
+ firstConfigFiles += f->GetFullPath();
sep = "\n ";
}
std::string thisConfigFiles;
sep = "";
- for (std::vector<cmSourceFile*>::const_iterator fi = configFiles.begin();
- fi != configFiles.end(); ++fi) {
+ for (cmSourceFile* f : configFiles) {
thisConfigFiles += sep;
- thisConfigFiles += (*fi)->GetFullPath();
+ thisConfigFiles += f->GetFullPath();
sep = "\n ";
}
std::ostringstream e;
@@ -5127,17 +5039,13 @@ void cmGeneratorTarget::GetObjectLibrariesCMP0026(
// for TARGET_OBJECTS instead for backwards compatibility with OLD
// behavior of CMP0024 and CMP0026 only.
cmStringRange rng = this->Target->GetSourceEntries();
- for (std::vector<std::string>::const_iterator i = rng.begin();
- i != rng.end(); ++i) {
- std::string const& entry = *i;
-
+ for (std::string const& entry : rng) {
std::vector<std::string> files;
cmSystemTools::ExpandListArgument(entry, files);
- for (std::vector<std::string>::const_iterator li = files.begin();
- li != files.end(); ++li) {
- if (cmHasLiteralPrefix(*li, "$<TARGET_OBJECTS:") &&
- (*li)[li->size() - 1] == '>') {
- std::string objLibName = li->substr(17, li->size() - 18);
+ for (std::string const& li : files) {
+ if (cmHasLiteralPrefix(li, "$<TARGET_OBJECTS:") &&
+ li[li.size() - 1] == '>') {
+ std::string objLibName = li.substr(17, li.size() - 18);
if (cmGeneratorExpression::Find(objLibName) != std::string::npos) {
continue;
@@ -5203,9 +5111,8 @@ void cmGeneratorTarget::GetLanguages(std::set<std::string>& languages,
{
std::vector<cmSourceFile*> sourceFiles;
this->GetSourceFiles(sourceFiles, config);
- for (std::vector<cmSourceFile*>::const_iterator i = sourceFiles.begin();
- i != sourceFiles.end(); ++i) {
- const std::string& lang = (*i)->GetLanguage();
+ for (cmSourceFile* src : sourceFiles) {
+ const std::string& lang = src->GetLanguage();
if (!lang.empty()) {
languages.insert(lang);
}
@@ -5217,27 +5124,21 @@ void cmGeneratorTarget::GetLanguages(std::set<std::string>& languages,
std::vector<cmGeneratorTarget*> objectTargets;
this->GetObjectLibrariesCMP0026(objectTargets);
objectLibraries.reserve(objectTargets.size());
- for (std::vector<cmGeneratorTarget*>::const_iterator it =
- objectTargets.begin();
- it != objectTargets.end(); ++it) {
- objectLibraries.push_back(*it);
+ for (cmGeneratorTarget* gt : objectTargets) {
+ objectLibraries.push_back(gt);
}
} else {
this->GetExternalObjects(externalObjects, config);
- for (std::vector<cmSourceFile const*>::const_iterator i =
- externalObjects.begin();
- i != externalObjects.end(); ++i) {
- std::string objLib = (*i)->GetObjectLibrary();
+ for (cmSourceFile const* extObj : externalObjects) {
+ std::string objLib = extObj->GetObjectLibrary();
if (cmGeneratorTarget* tgt =
this->LocalGenerator->FindGeneratorTargetToUse(objLib)) {
objectLibraries.push_back(tgt);
}
}
}
- for (std::vector<cmGeneratorTarget*>::const_iterator i =
- objectLibraries.begin();
- i != objectLibraries.end(); ++i) {
- (*i)->GetLanguages(languages, config);
+ for (cmGeneratorTarget* objLib : objectLibraries) {
+ objLib->GetLanguages(languages, config);
}
}
@@ -5281,7 +5182,7 @@ cmGeneratorTarget::GetLinkImplementationLibrariesInternal(
{
// There is no link implementation for imported targets.
if (this->IsImported()) {
- return CM_NULLPTR;
+ return nullptr;
}
// Populate the link implementation libraries for this configuration.
@@ -5322,9 +5223,9 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries(
le != end; ++le, ++btIt) {
std::vector<std::string> llibs;
cmGeneratorExpressionDAGChecker dagChecker(
- this->GetName(), "LINK_LIBRARIES", CM_NULLPTR, CM_NULLPTR);
+ this->GetName(), "LINK_LIBRARIES", nullptr, nullptr);
cmGeneratorExpression ge(*btIt);
- CM_AUTO_PTR<cmCompiledGeneratorExpression> const cge = ge.Parse(*le);
+ std::unique_ptr<cmCompiledGeneratorExpression> const cge = ge.Parse(*le);
std::string const evaluated =
cge->Evaluate(this->LocalGenerator, config, false, head, &dagChecker);
cmSystemTools::ExpandListArgument(evaluated, llibs);
@@ -5332,10 +5233,9 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries(
impl.HadHeadSensitiveCondition = true;
}
- for (std::vector<std::string>::const_iterator li = llibs.begin();
- li != llibs.end(); ++li) {
+ for (std::string const& lib : llibs) {
// Skip entries that resolve to the target itself or are empty.
- std::string name = this->CheckCMP0004(*li);
+ std::string name = this->CheckCMP0004(lib);
if (name == this->GetName() || name.empty()) {
if (name == this->GetName()) {
bool noMessage = false;
@@ -5373,10 +5273,9 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries(
}
std::set<std::string> const& seenProps = cge->GetSeenTargetProperties();
- for (std::set<std::string>::const_iterator it = seenProps.begin();
- it != seenProps.end(); ++it) {
- if (!this->GetProperty(*it)) {
- this->LinkImplicitNullProperties.insert(*it);
+ for (std::string const& sp : seenProps) {
+ if (!this->GetProperty(sp)) {
+ this->LinkImplicitNullProperties.insert(sp);
}
}
cge->GetMaxLanguageStandard(this, this->MaxLanguageStandards);
@@ -5390,10 +5289,9 @@ void cmGeneratorTarget::ComputeLinkImplementationLibraries(
CMP0003_ComputeLinkType(config, debugConfigs);
cmTarget::LinkLibraryVectorType const& oldllibs =
this->Target->GetOriginalLinkLibraries();
- for (cmTarget::LinkLibraryVectorType::const_iterator li = oldllibs.begin();
- li != oldllibs.end(); ++li) {
- if (li->second != GENERAL_LibraryType && li->second != linkType) {
- std::string name = this->CheckCMP0004(li->first);
+ for (cmTarget::LibraryID const& oldllib : oldllibs) {
+ if (oldllib.second != GENERAL_LibraryType && oldllib.second != linkType) {
+ std::string name = this->CheckCMP0004(oldllib.first);
if (name == this->GetName() || name.empty()) {
continue;
}
@@ -5415,7 +5313,7 @@ cmGeneratorTarget* cmGeneratorTarget::FindTargetToLink(
// within the project.
if (tgt && tgt->GetType() == cmStateEnums::EXECUTABLE &&
!tgt->IsExecutableWithExports()) {
- tgt = CM_NULLPTR;
+ tgt = nullptr;
}
if (tgt && tgt->GetType() == cmStateEnums::OBJECT_LIBRARY) {
@@ -5429,7 +5327,7 @@ cmGeneratorTarget* cmGeneratorTarget::FindTargetToLink(
"with the ENABLE_EXPORTS property set.";
cmake* cm = this->LocalGenerator->GetCMakeInstance();
cm->IssueMessage(cmake::FATAL_ERROR, e.str(), this->GetBacktrace());
- tgt = CM_NULLPTR;
+ tgt = nullptr;
}
return tgt;
diff --git a/Source/cmGeneratorTarget.h b/Source/cmGeneratorTarget.h
index 52147e319..1ee8a16fb 100644
--- a/Source/cmGeneratorTarget.h
+++ b/Source/cmGeneratorTarget.h
@@ -3,7 +3,7 @@
#ifndef cmGeneratorTarget_h
#define cmGeneratorTarget_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmLinkItem.h"
#include "cmListFileCache.h"
@@ -491,6 +491,11 @@ public:
std::string GetOutputName(const std::string& config,
cmStateEnums::ArtifactType artifact) const;
+ /** Clears cached meta data for local and external source files.
+ * The meta data will be recomputed on demand.
+ */
+ void ClearSourcesCache();
+
void AddSource(const std::string& src);
void AddTracedSources(std::vector<std::string> const& srcs);
@@ -519,7 +524,7 @@ public:
{
SourceFileFlags()
: Type(SourceFileTypeNormal)
- , MacFolder(CM_NULLPTR)
+ , MacFolder(nullptr)
{
}
SourceFileType Type;
@@ -565,7 +570,7 @@ public:
/** Convert the given GNU import library name (.dll.a) to a name with a new
extension (.lib or ${CMAKE_IMPORT_LIBRARY_SUFFIX}). */
bool GetImplibGNUtoMS(std::string const& gnuName, std::string& out,
- const char* newExt = CM_NULLPTR) const;
+ const char* newExt = nullptr) const;
bool IsExecutableWithExports() const;
@@ -656,7 +661,7 @@ private:
SourceEntriesType SourceDepends;
mutable std::map<cmSourceFile const*, std::string> Objects;
std::set<cmSourceFile const*> ExplicitObjectName;
- mutable std::map<std::string, std::vector<std::string> > SystemIncludesCache;
+ mutable std::map<std::string, std::vector<std::string>> SystemIncludesCache;
mutable std::string ExportMacro;
diff --git a/Source/cmGetCMakePropertyCommand.cxx b/Source/cmGetCMakePropertyCommand.cxx
index 5ba3326cb..fc82feef5 100644
--- a/Source/cmGetCMakePropertyCommand.cxx
+++ b/Source/cmGetCMakePropertyCommand.cxx
@@ -37,7 +37,7 @@ bool cmGetCMakePropertyCommand::InitialPass(
this->Makefile->GetGlobalGenerator()->GetInstallComponents();
output = cmJoin(*components, ";");
} else {
- const char* prop = CM_NULLPTR;
+ const char* prop = nullptr;
if (!args[1].empty()) {
prop = this->Makefile->GetState()->GetGlobalProperty(args[1]);
}
diff --git a/Source/cmGetCMakePropertyCommand.h b/Source/cmGetCMakePropertyCommand.h
index 9dfc40fda..1f29c78dc 100644
--- a/Source/cmGetCMakePropertyCommand.h
+++ b/Source/cmGetCMakePropertyCommand.h
@@ -3,7 +3,7 @@
#ifndef cmGetCMakePropertyCommand_h
#define cmGetCMakePropertyCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,14 +15,14 @@ class cmExecutionStatus;
class cmGetCMakePropertyCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmGetCMakePropertyCommand; }
+ cmCommand* Clone() override { return new cmGetCMakePropertyCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmGetDirectoryPropertyCommand.cxx b/Source/cmGetDirectoryPropertyCommand.cxx
index 1005b1543..a8cf6ab9c 100644
--- a/Source/cmGetDirectoryPropertyCommand.cxx
+++ b/Source/cmGetDirectoryPropertyCommand.cxx
@@ -70,7 +70,7 @@ bool cmGetDirectoryPropertyCommand::InitialPass(
return true;
}
- const char* prop = CM_NULLPTR;
+ const char* prop = nullptr;
if (!i->empty()) {
if (*i == "DEFINITIONS") {
switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0059)) {
diff --git a/Source/cmGetDirectoryPropertyCommand.h b/Source/cmGetDirectoryPropertyCommand.h
index 7d9795065..02ea0566f 100644
--- a/Source/cmGetDirectoryPropertyCommand.h
+++ b/Source/cmGetDirectoryPropertyCommand.h
@@ -3,7 +3,7 @@
#ifndef cmGetDirectoryPropertyCommand_h
#define cmGetDirectoryPropertyCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,14 +15,14 @@ class cmExecutionStatus;
class cmGetDirectoryPropertyCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmGetDirectoryPropertyCommand; }
+ cmCommand* Clone() override { return new cmGetDirectoryPropertyCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
void StoreResult(const std::string& variable, const char* prop);
diff --git a/Source/cmGetFilenameComponentCommand.cxx b/Source/cmGetFilenameComponentCommand.cxx
index c23684c22..1b358aba8 100644
--- a/Source/cmGetFilenameComponentCommand.cxx
+++ b/Source/cmGetFilenameComponentCommand.cxx
@@ -60,7 +60,30 @@ bool cmGetFilenameComponentCommand::InitialPass(
}
}
}
- cmSystemTools::SplitProgramFromArgs(filename, result, programArgs);
+
+ // First assume the path to the program was specified with no
+ // arguments and with no quoting or escaping for spaces.
+ // Only bother doing this if there is non-whitespace.
+ if (!cmSystemTools::TrimWhitespace(filename).empty()) {
+ result = cmSystemTools::FindProgram(filename);
+ }
+
+ // If that failed then assume a command-line string was given
+ // and split the program part from the rest of the arguments.
+ if (result.empty()) {
+ std::string program;
+ if (cmSystemTools::SplitProgramFromArgs(filename, program,
+ programArgs)) {
+ if (cmSystemTools::FileExists(program)) {
+ result = program;
+ } else {
+ result = cmSystemTools::FindProgram(program);
+ }
+ }
+ if (result.empty()) {
+ programArgs.clear();
+ }
+ }
} else if (args[2] == "EXT") {
result = cmSystemTools::GetFilenameExtension(filename);
} else if (args[2] == "NAME_WE") {
diff --git a/Source/cmGetFilenameComponentCommand.h b/Source/cmGetFilenameComponentCommand.h
index c8a23c70e..8c266552c 100644
--- a/Source/cmGetFilenameComponentCommand.h
+++ b/Source/cmGetFilenameComponentCommand.h
@@ -3,7 +3,7 @@
#ifndef cmGetFilenameComponentCommand_h
#define cmGetFilenameComponentCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmGetFilenameComponentCommand; }
+ cmCommand* Clone() override { return new cmGetFilenameComponentCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmGetPropertyCommand.cxx b/Source/cmGetPropertyCommand.cxx
index ddecdf621..4494c3e87 100644
--- a/Source/cmGetPropertyCommand.cxx
+++ b/Source/cmGetPropertyCommand.cxx
@@ -258,9 +258,9 @@ bool cmGetPropertyCommand::HandleTargetMode()
if (this->Makefile->IsAlias(this->Name)) {
return this->StoreResult(target->GetName().c_str());
}
- return this->StoreResult(CM_NULLPTR);
+ return this->StoreResult(nullptr);
}
- const char* prop_cstr = CM_NULLPTR;
+ const char* prop_cstr = nullptr;
cmListFileBacktrace bt = this->Makefile->GetBacktrace();
cmMessenger* messenger = this->Makefile->GetMessenger();
if (cmTargetPropertyComputer::PassesWhitelist(
@@ -333,7 +333,7 @@ bool cmGetPropertyCommand::HandleCacheMode()
return false;
}
- const char* value = CM_NULLPTR;
+ const char* value = nullptr;
if (this->Makefile->GetState()->GetCacheEntryValue(this->Name)) {
value = this->Makefile->GetState()->GetCacheEntryProperty(
this->Name, this->PropertyName);
@@ -357,7 +357,7 @@ bool cmGetPropertyCommand::HandleInstallMode()
std::string value;
bool isSet = file->GetProperty(this->PropertyName, value);
- return this->StoreResult(isSet ? value.c_str() : CM_NULLPTR);
+ return this->StoreResult(isSet ? value.c_str() : nullptr);
}
std::ostringstream e;
e << "given INSTALL name that could not be found or created: " << this->Name;
diff --git a/Source/cmGetPropertyCommand.h b/Source/cmGetPropertyCommand.h
index 649780168..c3f653e2e 100644
--- a/Source/cmGetPropertyCommand.h
+++ b/Source/cmGetPropertyCommand.h
@@ -3,7 +3,7 @@
#ifndef cmGetPropertyCommand_h
#define cmGetPropertyCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -17,14 +17,14 @@ class cmGetPropertyCommand : public cmCommand
public:
cmGetPropertyCommand();
- cmCommand* Clone() CM_OVERRIDE { return new cmGetPropertyCommand; }
+ cmCommand* Clone() override { return new cmGetPropertyCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
enum OutType
diff --git a/Source/cmGetSourceFilePropertyCommand.cxx b/Source/cmGetSourceFilePropertyCommand.cxx
index 1a5f08ef8..75879a553 100644
--- a/Source/cmGetSourceFilePropertyCommand.cxx
+++ b/Source/cmGetSourceFilePropertyCommand.cxx
@@ -28,7 +28,7 @@ bool cmGetSourceFilePropertyCommand::InitialPass(
this->Makefile->AddDefinition(var, sf->GetLanguage().c_str());
return true;
}
- const char* prop = CM_NULLPTR;
+ const char* prop = nullptr;
if (!args[2].empty()) {
prop = sf->GetPropertyForUser(args[2]);
}
diff --git a/Source/cmGetSourceFilePropertyCommand.h b/Source/cmGetSourceFilePropertyCommand.h
index e96bb29ed..43bc330a8 100644
--- a/Source/cmGetSourceFilePropertyCommand.h
+++ b/Source/cmGetSourceFilePropertyCommand.h
@@ -3,7 +3,7 @@
#ifndef cmGetSourceFilePropertyCommand_h
#define cmGetSourceFilePropertyCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,14 +15,14 @@ class cmExecutionStatus;
class cmGetSourceFilePropertyCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmGetSourceFilePropertyCommand; }
+ cmCommand* Clone() override { return new cmGetSourceFilePropertyCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmGetTargetPropertyCommand.cxx b/Source/cmGetTargetPropertyCommand.cxx
index 0910a5324..ec485aa3e 100644
--- a/Source/cmGetTargetPropertyCommand.cxx
+++ b/Source/cmGetTargetPropertyCommand.cxx
@@ -34,7 +34,7 @@ bool cmGetTargetPropertyCommand::InitialPass(
prop_exists = true;
}
} else if (!args[2].empty()) {
- const char* prop_cstr = CM_NULLPTR;
+ const char* prop_cstr = nullptr;
cmListFileBacktrace bt = this->Makefile->GetBacktrace();
cmMessenger* messenger = this->Makefile->GetMessenger();
if (cmTargetPropertyComputer::PassesWhitelist(tgt->GetType(), args[2],
diff --git a/Source/cmGetTargetPropertyCommand.h b/Source/cmGetTargetPropertyCommand.h
index 5de322563..63ee5fd9b 100644
--- a/Source/cmGetTargetPropertyCommand.h
+++ b/Source/cmGetTargetPropertyCommand.h
@@ -3,7 +3,7 @@
#ifndef cmGetTargetPropertyCommand_h
#define cmGetTargetPropertyCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,14 +15,14 @@ class cmExecutionStatus;
class cmGetTargetPropertyCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmGetTargetPropertyCommand; }
+ cmCommand* Clone() override { return new cmGetTargetPropertyCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmGetTestPropertyCommand.cxx b/Source/cmGetTestPropertyCommand.cxx
index 6424515ec..0b0d6eb3d 100644
--- a/Source/cmGetTestPropertyCommand.cxx
+++ b/Source/cmGetTestPropertyCommand.cxx
@@ -20,7 +20,7 @@ bool cmGetTestPropertyCommand::InitialPass(
std::string const& var = args[2];
cmTest* test = this->Makefile->GetTest(testName);
if (test) {
- const char* prop = CM_NULLPTR;
+ const char* prop = nullptr;
if (!args[1].empty()) {
prop = test->GetProperty(args[1]);
}
diff --git a/Source/cmGetTestPropertyCommand.h b/Source/cmGetTestPropertyCommand.h
index b17e7a1cc..4a74f593f 100644
--- a/Source/cmGetTestPropertyCommand.h
+++ b/Source/cmGetTestPropertyCommand.h
@@ -3,7 +3,7 @@
#ifndef cmGetTestPropertyCommand_h
#define cmGetTestPropertyCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,14 +15,14 @@ class cmExecutionStatus;
class cmGetTestPropertyCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmGetTestPropertyCommand; }
+ cmCommand* Clone() override { return new cmGetTestPropertyCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmGhsMultiGpj.h b/Source/cmGhsMultiGpj.h
index 7bc7bfc46..b1eead101 100644
--- a/Source/cmGhsMultiGpj.h
+++ b/Source/cmGhsMultiGpj.h
@@ -3,7 +3,7 @@
#ifndef cmGhsMultiGpj_h
#define cmGhsMultiGpj_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
class cmGeneratedFileStream;
diff --git a/Source/cmGhsMultiTargetGenerator.cxx b/Source/cmGhsMultiTargetGenerator.cxx
index 7032cd582..a31e415b8 100644
--- a/Source/cmGhsMultiTargetGenerator.cxx
+++ b/Source/cmGhsMultiTargetGenerator.cxx
@@ -363,7 +363,7 @@ void cmGhsMultiTargetGenerator::WriteTargetLinkLibraries(
this->GeneratorTarget->GetCreateRuleVariable(language, config);
bool useWatcomQuote =
this->Makefile->IsOn(createRule + "_USE_WATCOM_QUOTE");
- CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ std::unique_ptr<cmLinkLineComputer> linkLineComputer(
this->GetGlobalGenerator()->CreateLinkLineComputer(
this->LocalGenerator,
this->LocalGenerator->GetStateSnapshot().GetDirectory()));
@@ -439,7 +439,7 @@ cmGhsMultiTargetGenerator::GetObjectNames(
cmLocalGhsMultiGenerator* const localGhsMultiGenerator,
cmGeneratorTarget* const generatorTarget)
{
- std::map<std::string, std::vector<cmSourceFile*> > filenameToSource;
+ std::map<std::string, std::vector<cmSourceFile*>> filenameToSource;
std::map<cmSourceFile*, std::string> sourceToFilename;
for (std::vector<cmSourceFile*>::const_iterator sf = objectSources->begin();
sf != objectSources->end(); ++sf) {
@@ -451,7 +451,7 @@ cmGhsMultiTargetGenerator::GetObjectNames(
}
std::vector<cmSourceFile*> duplicateSources;
- for (std::map<std::string, std::vector<cmSourceFile*> >::const_iterator
+ for (std::map<std::string, std::vector<cmSourceFile*>>::const_iterator
msvSourceI = filenameToSource.begin();
msvSourceI != filenameToSource.end(); ++msvSourceI) {
if (msvSourceI->second.size() > 1) {
diff --git a/Source/cmGlobalCommonGenerator.h b/Source/cmGlobalCommonGenerator.h
index f2ad059de..e19118b50 100644
--- a/Source/cmGlobalCommonGenerator.h
+++ b/Source/cmGlobalCommonGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmGlobalCommonGenerator_h
#define cmGlobalCommonGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmGlobalGenerator.h"
@@ -16,7 +16,7 @@ class cmGlobalCommonGenerator : public cmGlobalGenerator
{
public:
cmGlobalCommonGenerator(cmake* cm);
- ~cmGlobalCommonGenerator() CM_OVERRIDE;
+ ~cmGlobalCommonGenerator() override;
};
#endif
diff --git a/Source/cmGlobalGenerator.cxx b/Source/cmGlobalGenerator.cxx
index 099f705f4..05efff317 100644
--- a/Source/cmGlobalGenerator.cxx
+++ b/Source/cmGlobalGenerator.cxx
@@ -89,9 +89,9 @@ cmGlobalGenerator::cmGlobalGenerator(cmake* cm)
// how long to let try compiles run
this->TryCompileTimeout = 0;
- this->ExtraGenerator = CM_NULLPTR;
- this->CurrentMakefile = CM_NULLPTR;
- this->TryCompileOuterMakefile = CM_NULLPTR;
+ this->ExtraGenerator = nullptr;
+ this->CurrentConfigureMakefile = nullptr;
+ this->TryCompileOuterMakefile = nullptr;
this->ConfigureDoneCMP0026AndCMP0024 = false;
this->FirstTimeProgress = 0.0f;
@@ -244,15 +244,13 @@ bool cmGlobalGenerator::GenerateImportFile(const std::string& file)
bool result = it->second->GenerateImportFile();
if (!this->ConfigureDoneCMP0026AndCMP0024) {
- for (std::vector<cmMakefile*>::const_iterator mit =
- this->Makefiles.begin();
- mit != this->Makefiles.end(); ++mit) {
- (*mit)->RemoveExportBuildFileGeneratorCMP0024(it->second);
+ for (cmMakefile* m : this->Makefiles) {
+ m->RemoveExportBuildFileGeneratorCMP0024(it->second);
}
}
delete it->second;
- it->second = CM_NULLPTR;
+ it->second = nullptr;
this->BuildExportSets.erase(it);
return result;
}
@@ -383,12 +381,11 @@ void cmGlobalGenerator::EnableLanguage(
}
std::set<std::string> cur_languages(languages.begin(), languages.end());
- for (std::set<std::string>::iterator li = cur_languages.begin();
- li != cur_languages.end(); ++li) {
- if (!this->LanguagesInProgress.insert(*li).second) {
+ for (std::string const& li : cur_languages) {
+ if (!this->LanguagesInProgress.insert(li).second) {
std::ostringstream e;
- e << "Language '" << *li << "' is currently being enabled. "
- "Recursive call not allowed.";
+ e << "Language '" << li << "' is currently being enabled. "
+ "Recursive call not allowed.";
mf->IssueMessage(cmake::FATAL_ERROR, e.str());
cmSystemTools::SetFatalErrorOccured();
return;
@@ -397,12 +394,11 @@ void cmGlobalGenerator::EnableLanguage(
if (this->TryCompileOuterMakefile) {
// In a try-compile we can only enable languages provided by caller.
- for (std::vector<std::string>::const_iterator li = languages.begin();
- li != languages.end(); ++li) {
- if (*li == "NONE") {
+ for (std::string const& li : languages) {
+ if (li == "NONE") {
this->SetLanguageEnabled("NONE", mf);
} else {
- const char* lang = li->c_str();
+ const char* lang = li.c_str();
if (this->LanguagesReady.find(lang) == this->LanguagesReady.end()) {
std::ostringstream e;
e << "The test project needs language " << lang
@@ -451,15 +447,6 @@ void cmGlobalGenerator::EnableLanguage(
"Platform information initialized", cmStateEnums::INTERNAL);
}
- // find and make sure CMAKE_MAKE_PROGRAM is defined
- if (!this->FindMakeProgram(mf)) {
- return;
- }
-
- if (!this->CheckLanguages(languages, mf)) {
- return;
- }
-
// try and load the CMakeSystem.cmake if it is there
std::string fpath = rootBin;
bool const readCMakeSystem = !mf->GetDefinition("CMAKE_SYSTEM_LOADED");
@@ -490,7 +477,6 @@ void cmGlobalGenerator::EnableLanguage(
windowsVersionString << osviex.dwMajorVersion << "."
<< osviex.dwMinorVersion << "."
<< osviex.dwBuildNumber;
- windowsVersionString.str();
mf->AddDefinition("CMAKE_HOST_SYSTEM_VERSION",
windowsVersionString.str().c_str());
#endif
@@ -505,6 +491,11 @@ void cmGlobalGenerator::EnableLanguage(
}
if (readCMakeSystem) {
+ // Find the native build tool for this generator.
+ if (!this->FindMakeProgram(mf)) {
+ return;
+ }
+
// Tell the generator about the target system.
std::string system = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME");
if (!this->SetSystemName(system, mf)) {
@@ -527,6 +518,12 @@ void cmGlobalGenerator::EnableLanguage(
}
}
+ // Check that the languages are supported by the generator and its
+ // native build tool found above.
+ if (!this->CheckLanguages(languages, mf)) {
+ return;
+ }
+
// **** Load the system specific initialization if not yet loaded
if (!mf->GetDefinition("CMAKE_SYSTEM_SPECIFIC_INITIALIZE_LOADED")) {
fpath = mf->GetModulesFile("CMakeSystemSpecificInitialize.cmake");
@@ -542,11 +539,10 @@ void cmGlobalGenerator::EnableLanguage(
// load the CMakeDetermine(LANG)Compiler.cmake file to find
// the compiler
- for (std::vector<std::string>::const_iterator l = languages.begin();
- l != languages.end(); ++l) {
- const char* lang = l->c_str();
+ for (std::string const& l : languages) {
+ const char* lang = l.c_str();
needSetLanguageEnabledMaps[lang] = false;
- if (*l == "NONE") {
+ if (l == "NONE") {
this->SetLanguageEnabled("NONE", mf);
continue;
}
@@ -648,10 +644,9 @@ void cmGlobalGenerator::EnableLanguage(
}
// loop over languages again loading CMake(LANG)Information.cmake
//
- for (std::vector<std::string>::const_iterator l = languages.begin();
- l != languages.end(); ++l) {
- const char* lang = l->c_str();
- if (*l == "NONE") {
+ for (std::string const& l : languages) {
+ const char* lang = l.c_str();
+ if (l == "NONE") {
this->SetLanguageEnabled("NONE", mf);
continue;
}
@@ -794,9 +789,8 @@ void cmGlobalGenerator::EnableLanguage(
cmSystemTools::SetFatalErrorOccured();
}
- for (std::set<std::string>::iterator li = cur_languages.begin();
- li != cur_languages.end(); ++li) {
- this->LanguagesInProgress.erase(*li);
+ for (std::string const& lang : cur_languages) {
+ this->LanguagesInProgress.erase(lang);
}
}
@@ -1021,9 +1015,8 @@ void cmGlobalGenerator::SetLanguageEnabledMaps(const std::string& l,
std::string ignoreExts = mf->GetSafeDefinition(ignoreExtensionsVar);
std::vector<std::string> extensionList;
cmSystemTools::ExpandListArgument(ignoreExts, extensionList);
- for (std::vector<std::string>::iterator i = extensionList.begin();
- i != extensionList.end(); ++i) {
- this->IgnoreExtensions[*i] = true;
+ for (std::string const& i : extensionList) {
+ this->IgnoreExtensions[i] = true;
}
}
@@ -1035,9 +1028,8 @@ void cmGlobalGenerator::FillExtensionToLanguageMap(const std::string& l,
std::string exts = mf->GetSafeDefinition(extensionsVar);
std::vector<std::string> extensionList;
cmSystemTools::ExpandListArgument(exts, extensionList);
- for (std::vector<std::string>::iterator i = extensionList.begin();
- i != extensionList.end(); ++i) {
- this->ExtensionToLanguage[*i] = l;
+ for (std::string const& i : extensionList) {
+ this->ExtensionToLanguage[i] = l;
}
}
@@ -1075,7 +1067,7 @@ bool cmGlobalGenerator::GetLanguageEnabled(const std::string& l) const
void cmGlobalGenerator::ClearEnabledLanguages()
{
- return this->CMakeInstance->GetState()->ClearEnabledLanguages();
+ this->CMakeInstance->GetState()->ClearEnabledLanguages();
}
void cmGlobalGenerator::CreateLocalGenerators()
@@ -1083,9 +1075,8 @@ void cmGlobalGenerator::CreateLocalGenerators()
cmDeleteAll(this->LocalGenerators);
this->LocalGenerators.clear();
this->LocalGenerators.reserve(this->Makefiles.size());
- for (std::vector<cmMakefile*>::const_iterator it = this->Makefiles.begin();
- it != this->Makefiles.end(); ++it) {
- this->LocalGenerators.push_back(this->CreateLocalGenerator(*it));
+ for (cmMakefile* m : this->Makefiles) {
+ this->LocalGenerators.push_back(this->CreateLocalGenerator(m));
}
}
@@ -1119,13 +1110,11 @@ void cmGlobalGenerator::Configure()
std::vector<GlobalTargetInfo> globalTargets;
this->CreateDefaultGlobalTargets(globalTargets);
- for (unsigned int i = 0; i < this->Makefiles.size(); ++i) {
- cmMakefile* mf = this->Makefiles[i];
+ for (cmMakefile* mf : this->Makefiles) {
cmTargets* targets = &(mf->GetTargets());
- for (std::vector<GlobalTargetInfo>::iterator gti = globalTargets.begin();
- gti != globalTargets.end(); ++gti) {
- targets->insert(
- cmTargets::value_type(gti->Name, this->CreateGlobalTarget(*gti, mf)));
+ for (GlobalTargetInfo const& globalTarget : globalTargets) {
+ targets->insert(cmTargets::value_type(
+ globalTarget.Name, this->CreateGlobalTarget(globalTarget, mf)));
}
}
@@ -1145,7 +1134,7 @@ void cmGlobalGenerator::Configure()
std::ostringstream msg;
if (cmSystemTools::GetErrorOccuredFlag()) {
msg << "Configuring incomplete, errors occurred!";
- const char* logs[] = { "CMakeOutput.log", "CMakeError.log", CM_NULLPTR };
+ const char* logs[] = { "CMakeOutput.log", "CMakeError.log", nullptr };
for (const char** log = logs; *log; ++log) {
std::string f = this->CMakeInstance->GetHomeOutputDirectory();
f += this->CMakeInstance->GetCMakeFilesDirectory();
@@ -1178,9 +1167,8 @@ void cmGlobalGenerator::CreateImportedGenerationObjects(
std::find(this->Makefiles.begin(), this->Makefiles.end(), mf);
cmLocalGenerator* lg =
this->LocalGenerators[std::distance(this->Makefiles.begin(), mfit)];
- for (std::vector<std::string>::const_iterator it = targets.begin();
- it != targets.end(); ++it) {
- cmGeneratorTarget* gt = lg->FindGeneratorTargetToUse(*it);
+ for (std::string const& t : targets) {
+ cmGeneratorTarget* gt = lg->FindGeneratorTargetToUse(t);
if (gt) {
exports.push_back(gt);
}
@@ -1192,7 +1180,7 @@ cmExportBuildFileGenerator* cmGlobalGenerator::GetExportedTargetsFile(
{
std::map<std::string, cmExportBuildFileGenerator*>::const_iterator it =
this->BuildExportSets.find(filename);
- return it == this->BuildExportSets.end() ? CM_NULLPTR : it->second;
+ return it == this->BuildExportSets.end() ? nullptr : it->second;
}
void cmGlobalGenerator::AddCMP0042WarnTarget(const std::string& target)
@@ -1230,10 +1218,8 @@ void cmGlobalGenerator::ComputeBuildFileGenerators()
for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
std::vector<cmExportBuildFileGenerator*> gens =
this->Makefiles[i]->GetExportBuildFileGenerators();
- for (std::vector<cmExportBuildFileGenerator*>::const_iterator it =
- gens.begin();
- it != gens.end(); ++it) {
- (*it)->Compute(this->LocalGenerators[i]);
+ for (cmExportBuildFileGenerator* g : gens) {
+ g->Compute(this->LocalGenerators[i]);
}
}
}
@@ -1264,15 +1250,12 @@ bool cmGlobalGenerator::Compute()
#ifdef CMAKE_BUILD_WITH_CMAKE
// Iterate through all targets and set up automoc for those which have
// the AUTOMOC, AUTOUIC or AUTORCC property set
- std::vector<cmGeneratorTarget const*> autogenTargets =
- this->CreateQtAutoGeneratorsTargets();
+ cmQtAutoGenDigestUPV autogenDigests = this->CreateQtAutoGeneratorsTargets();
#endif
- unsigned int i;
-
// Add generator specific helper commands
- for (i = 0; i < this->LocalGenerators.size(); ++i) {
- this->LocalGenerators[i]->AddHelperCommands();
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ localGen->AddHelperCommands();
}
// Finalize the set of compile features for each target.
@@ -1281,26 +1264,23 @@ bool cmGlobalGenerator::Compute()
// on the original cmTarget instance. It accumulates features
// across all configurations. Some refactoring is needed to
// compute a per-config resulta purely during generation.
- for (i = 0; i < this->LocalGenerators.size(); ++i) {
- if (!this->LocalGenerators[i]->ComputeTargetCompileFeatures()) {
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ if (!localGen->ComputeTargetCompileFeatures()) {
return false;
}
}
#ifdef CMAKE_BUILD_WITH_CMAKE
- for (std::vector<cmGeneratorTarget const*>::iterator it =
- autogenTargets.begin();
- it != autogenTargets.end(); ++it) {
- cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget(*it);
+ for (cmQtAutoGenDigestUP const& digest : autogenDigests) {
+ cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget(*digest);
}
+ autogenDigests.clear();
#endif
- for (i = 0; i < this->LocalGenerators.size(); ++i) {
- cmMakefile* mf = this->LocalGenerators[i]->GetMakefile();
- std::vector<cmInstallGenerator*>& gens = mf->GetInstallGenerators();
- for (std::vector<cmInstallGenerator*>::const_iterator git = gens.begin();
- git != gens.end(); ++git) {
- (*git)->Compute(this->LocalGenerators[i]);
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ cmMakefile* mf = localGen->GetMakefile();
+ for (cmInstallGenerator* g : mf->GetInstallGenerators()) {
+ g->Compute(localGen);
}
}
@@ -1308,15 +1288,15 @@ bool cmGlobalGenerator::Compute()
// Trace the dependencies, after that no custom commands should be added
// because their dependencies might not be handled correctly
- for (i = 0; i < this->LocalGenerators.size(); ++i) {
- this->LocalGenerators[i]->TraceDependencies();
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ localGen->TraceDependencies();
}
this->ForceLinkerLanguages();
// Compute the manifest of main targets generated.
- for (i = 0; i < this->LocalGenerators.size(); ++i) {
- this->LocalGenerators[i]->ComputeTargetManifest();
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ localGen->ComputeTargetManifest();
}
// Compute the inter-target dependencies.
@@ -1324,8 +1304,8 @@ bool cmGlobalGenerator::Compute()
return false;
}
- for (i = 0; i < this->LocalGenerators.size(); ++i) {
- this->LocalGenerators[i]->ComputeHomeRelativeOutputPath();
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ localGen->ComputeHomeRelativeOutputPath();
}
return true;
@@ -1352,17 +1332,15 @@ void cmGlobalGenerator::Generate()
"Generating", (static_cast<float>(i) + 1.0f) /
static_cast<float>(this->LocalGenerators.size()));
}
- this->SetCurrentMakefile(CM_NULLPTR);
+ this->SetCurrentMakefile(nullptr);
if (!this->GenerateCPackPropertiesFile()) {
this->GetCMakeInstance()->IssueMessage(
cmake::FATAL_ERROR, "Could not write CPack properties file.");
}
- for (std::map<std::string, cmExportBuildFileGenerator*>::iterator it =
- this->BuildExportSets.begin();
- it != this->BuildExportSets.end(); ++it) {
- if (!it->second->GenerateImportFile()) {
+ for (auto& buildExpSet : this->BuildExportSets) {
+ if (!buildExpSet.second->GenerateImportFile()) {
if (!cmSystemTools::GetErrorOccuredFlag()) {
this->GetCMakeInstance()->IssueMessage(cmake::FATAL_ERROR,
"Could not write export file.");
@@ -1375,7 +1353,7 @@ void cmGlobalGenerator::Generate()
this->WriteSummary();
- if (this->ExtraGenerator != CM_NULLPTR) {
+ if (this->ExtraGenerator != nullptr) {
this->ExtraGenerator->Generate();
}
@@ -1384,10 +1362,8 @@ void cmGlobalGenerator::Generate()
w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0042) << "\n";
w << "MACOSX_RPATH is not specified for"
" the following targets:\n";
- for (std::set<std::string>::iterator iter =
- this->CMP0042WarnTargets.begin();
- iter != this->CMP0042WarnTargets.end(); ++iter) {
- w << " " << *iter << "\n";
+ for (std::string const& t : this->CMP0042WarnTargets) {
+ w << " " << t << "\n";
}
this->GetCMakeInstance()->IssueMessage(cmake::AUTHOR_WARNING, w.str());
}
@@ -1402,10 +1378,8 @@ void cmGlobalGenerator::Generate()
"settings:\n"
;
/* clang-format on */
- for (std::set<std::string>::iterator iter =
- this->CMP0068WarnTargets.begin();
- iter != this->CMP0068WarnTargets.end(); ++iter) {
- w << " " << *iter << "\n";
+ for (std::string const& t : this->CMP0068WarnTargets) {
+ w << " " << t << "\n";
}
this->GetCMakeInstance()->IssueMessage(cmake::AUTHOR_WARNING, w.str());
}
@@ -1420,68 +1394,69 @@ bool cmGlobalGenerator::ComputeTargetDepends()
return false;
}
std::vector<cmGeneratorTarget const*> const& targets = ctd.GetTargets();
- for (std::vector<cmGeneratorTarget const*>::const_iterator ti =
- targets.begin();
- ti != targets.end(); ++ti) {
- ctd.GetTargetDirectDepends(*ti, this->TargetDependencies[*ti]);
+ for (cmGeneratorTarget const* target : targets) {
+ ctd.GetTargetDirectDepends(target, this->TargetDependencies[target]);
}
return true;
}
-std::vector<const cmGeneratorTarget*>
-cmGlobalGenerator::CreateQtAutoGeneratorsTargets()
+cmQtAutoGenDigestUPV cmGlobalGenerator::CreateQtAutoGeneratorsTargets()
{
- std::vector<const cmGeneratorTarget*> autogenTargets;
+ cmQtAutoGenDigestUPV autogenDigests;
#ifdef CMAKE_BUILD_WITH_CMAKE
- for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
- std::vector<cmGeneratorTarget*> targets =
- this->LocalGenerators[i]->GetGeneratorTargets();
- std::vector<cmGeneratorTarget*> filteredTargets;
- filteredTargets.reserve(targets.size());
- for (std::vector<cmGeneratorTarget*>::iterator ti = targets.begin();
- ti != targets.end(); ++ti) {
- if ((*ti)->GetType() == cmStateEnums::GLOBAL_TARGET) {
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ const std::vector<cmGeneratorTarget*>& targets =
+ localGen->GetGeneratorTargets();
+ // Find targets that require AUTOGEN processing
+ for (cmGeneratorTarget* target : targets) {
+ if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
continue;
}
- if ((*ti)->GetType() != cmStateEnums::EXECUTABLE &&
- (*ti)->GetType() != cmStateEnums::STATIC_LIBRARY &&
- (*ti)->GetType() != cmStateEnums::SHARED_LIBRARY &&
- (*ti)->GetType() != cmStateEnums::MODULE_LIBRARY &&
- (*ti)->GetType() != cmStateEnums::OBJECT_LIBRARY) {
+ if (target->GetType() != cmStateEnums::EXECUTABLE &&
+ target->GetType() != cmStateEnums::STATIC_LIBRARY &&
+ target->GetType() != cmStateEnums::SHARED_LIBRARY &&
+ target->GetType() != cmStateEnums::MODULE_LIBRARY &&
+ target->GetType() != cmStateEnums::OBJECT_LIBRARY) {
continue;
}
- if ((!(*ti)->GetPropertyAsBool("AUTOMOC") &&
- !(*ti)->GetPropertyAsBool("AUTOUIC") &&
- !(*ti)->GetPropertyAsBool("AUTORCC")) ||
- (*ti)->IsImported()) {
+ if (target->IsImported()) {
continue;
}
- // don't do anything if there is no Qt4 or Qt5Core (which contains moc):
- cmMakefile* mf = (*ti)->Target->GetMakefile();
- std::string qtMajorVersion = mf->GetSafeDefinition("QT_VERSION_MAJOR");
- if (qtMajorVersion == "") {
- qtMajorVersion = mf->GetSafeDefinition("Qt5Core_VERSION_MAJOR");
- }
- if (qtMajorVersion != "4" && qtMajorVersion != "5") {
+
+ const bool mocEnabled = target->GetPropertyAsBool("AUTOMOC");
+ const bool uicEnabled = target->GetPropertyAsBool("AUTOUIC");
+ const bool rccEnabled = target->GetPropertyAsBool("AUTORCC");
+ if (!mocEnabled && !uicEnabled && !rccEnabled) {
continue;
}
- cmGeneratorTarget* gt = *ti;
+ std::string qtVersionMajor =
+ cmQtAutoGeneratorInitializer::GetQtMajorVersion(target);
+ // don't do anything if there is no Qt4 or Qt5Core (which contains moc)
+ if (qtVersionMajor != "4" && qtVersionMajor != "5") {
+ continue;
+ }
- cmQtAutoGeneratorInitializer::InitializeAutogenSources(gt);
- filteredTargets.push_back(gt);
- }
- for (std::vector<cmGeneratorTarget*>::iterator ti =
- filteredTargets.begin();
- ti != filteredTargets.end(); ++ti) {
- cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
- this->LocalGenerators[i], *ti);
- autogenTargets.push_back(*ti);
+ {
+ cmQtAutoGenDigestUP digest(new cmQtAutoGenDigest(target));
+ digest->QtVersionMajor = std::move(qtVersionMajor);
+ digest->QtVersionMinor =
+ cmQtAutoGeneratorInitializer::GetQtMinorVersion(
+ target, digest->QtVersionMajor);
+ digest->MocEnabled = mocEnabled;
+ digest->UicEnabled = uicEnabled;
+ digest->RccEnabled = rccEnabled;
+ autogenDigests.emplace_back(std::move(digest));
+ }
}
}
+ // Initialize autogen targets
+ for (const cmQtAutoGenDigestUP& digest : autogenDigests) {
+ cmQtAutoGeneratorInitializer::InitializeAutogenTarget(*digest);
+ }
#endif
- return autogenTargets;
+ return autogenDigests;
}
cmLinkLineComputer* cmGlobalGenerator::CreateLinkLineComputer(
@@ -1502,17 +1477,15 @@ void cmGlobalGenerator::FinalizeTargetCompileInfo()
this->CMakeInstance->GetState()->GetEnabledLanguages();
// Construct per-target generator information.
- for (unsigned int i = 0; i < this->Makefiles.size(); ++i) {
- cmMakefile* mf = this->Makefiles[i];
-
+ for (cmMakefile* mf : this->Makefiles) {
const cmStringRange noconfig_compile_definitions =
mf->GetCompileDefinitionsEntries();
const cmBacktraceRange noconfig_compile_definitions_bts =
mf->GetCompileDefinitionsBacktraces();
cmTargets& targets = mf->GetTargets();
- for (cmTargets::iterator ti = targets.begin(); ti != targets.end(); ++ti) {
- cmTarget* t = &ti->second;
+ for (auto& target : targets) {
+ cmTarget* t = &target.second;
if (t->GetType() == cmStateEnums::GLOBAL_TARGET) {
continue;
}
@@ -1537,10 +1510,9 @@ void cmGlobalGenerator::FinalizeTargetCompileInfo()
std::vector<std::string> configs;
mf->GetConfigurations(configs);
- for (std::vector<std::string>::const_iterator ci = configs.begin();
- ci != configs.end(); ++ci) {
+ for (std::string const& c : configs) {
std::string defPropName = "COMPILE_DEFINITIONS_";
- defPropName += cmSystemTools::UpperCase(*ci);
+ defPropName += cmSystemTools::UpperCase(c);
t->AppendProperty(defPropName, mf->GetProperty(defPropName));
}
}
@@ -1549,10 +1521,9 @@ void cmGlobalGenerator::FinalizeTargetCompileInfo()
// The standard include directories for each language
// should be treated as system include directories.
std::set<std::string> standardIncludesSet;
- for (std::vector<std::string>::const_iterator li = langs.begin();
- li != langs.end(); ++li) {
+ for (std::string const& li : langs) {
std::string const standardIncludesVar =
- "CMAKE_" + *li + "_STANDARD_INCLUDE_DIRECTORIES";
+ "CMAKE_" + li + "_STANDARD_INCLUDE_DIRECTORIES";
std::string const standardIncludesStr =
mf->GetSafeDefinition(standardIncludesVar);
std::vector<std::string> standardIncludesVec;
@@ -1571,8 +1542,8 @@ void cmGlobalGenerator::CreateGeneratorTargets(
{
if (targetTypes == AllTargets) {
cmTargets& targets = mf->GetTargets();
- for (cmTargets::iterator ti = targets.begin(); ti != targets.end(); ++ti) {
- cmTarget* t = &ti->second;
+ for (auto& target : targets) {
+ cmTarget* t = &target.second;
cmGeneratorTarget* gt = new cmGeneratorTarget(t, lg);
lg->AddGeneratorTarget(gt);
}
@@ -1580,9 +1551,8 @@ void cmGlobalGenerator::CreateGeneratorTargets(
std::vector<cmTarget*> itgts = mf->GetImportedTargets();
- for (std::vector<cmTarget*>::const_iterator j = itgts.begin();
- j != itgts.end(); ++j) {
- lg->AddImportedGeneratorTarget(importedMap.find(*j)->second);
+ for (cmTarget* t : itgts) {
+ lg->AddImportedGeneratorTarget(importedMap.find(t)->second);
}
}
@@ -1591,13 +1561,11 @@ void cmGlobalGenerator::CreateGeneratorTargets(TargetTypes targetTypes)
std::map<cmTarget*, cmGeneratorTarget*> importedMap;
for (unsigned int i = 0; i < this->Makefiles.size(); ++i) {
cmMakefile* mf = this->Makefiles[i];
- for (std::vector<cmTarget*>::const_iterator j =
- mf->GetOwnedImportedTargets().begin();
- j != mf->GetOwnedImportedTargets().end(); ++j) {
+ for (cmTarget* ownedImpTgt : mf->GetOwnedImportedTargets()) {
cmLocalGenerator* lg = this->LocalGenerators[i];
- cmGeneratorTarget* gt = new cmGeneratorTarget(*j, lg);
+ cmGeneratorTarget* gt = new cmGeneratorTarget(ownedImpTgt, lg);
lg->AddOwnedImportedGeneratorTarget(gt);
- importedMap[*j] = gt;
+ importedMap[ownedImpTgt] = gt;
}
}
@@ -1644,30 +1612,30 @@ void cmGlobalGenerator::CheckTargetProperties()
for (unsigned int i = 0; i < this->Makefiles.size(); ++i) {
this->Makefiles[i]->ConfigureFinalPass();
cmTargets& targets = this->Makefiles[i]->GetTargets();
- for (cmTargets::iterator l = targets.begin(); l != targets.end(); l++) {
- if (l->second.GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+ for (auto const& target : targets) {
+ if (target.second.GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
const cmTarget::LinkLibraryVectorType& libs =
- l->second.GetOriginalLinkLibraries();
- for (cmTarget::LinkLibraryVectorType::const_iterator lib = libs.begin();
- lib != libs.end(); ++lib) {
- if (lib->first.size() > 9 &&
- cmSystemTools::IsNOTFOUND(lib->first.c_str())) {
- std::string varName = lib->first.substr(0, lib->first.size() - 9);
+ target.second.GetOriginalLinkLibraries();
+ for (auto const& lib : libs) {
+ if (lib.first.size() > 9 &&
+ cmSystemTools::IsNOTFOUND(lib.first.c_str())) {
+ std::string varName = lib.first.substr(0, lib.first.size() - 9);
if (state->GetCacheEntryPropertyAsBool(varName, "ADVANCED")) {
varName += " (ADVANCED)";
}
std::string text = notFoundMap[varName];
text += "\n linked by target \"";
- text += l->second.GetName();
+ text += target.second.GetName();
text += "\" in directory ";
text += this->Makefiles[i]->GetCurrentSourceDirectory();
notFoundMap[varName] = text;
}
}
std::vector<std::string> incs;
- const char* incDirProp = l->second.GetProperty("INCLUDE_DIRECTORIES");
+ const char* incDirProp =
+ target.second.GetProperty("INCLUDE_DIRECTORIES");
if (!incDirProp) {
continue;
}
@@ -1677,10 +1645,9 @@ void cmGlobalGenerator::CheckTargetProperties()
cmSystemTools::ExpandListArgument(incDirs, incs);
- for (std::vector<std::string>::const_iterator incDir = incs.begin();
- incDir != incs.end(); ++incDir) {
- if (incDir->size() > 9 && cmSystemTools::IsNOTFOUND(incDir->c_str())) {
- std::string varName = incDir->substr(0, incDir->size() - 9);
+ for (std::string const& incDir : incs) {
+ if (incDir.size() > 9 && cmSystemTools::IsNOTFOUND(incDir.c_str())) {
+ std::string varName = incDir.substr(0, incDir.size() - 9);
if (state->GetCacheEntryPropertyAsBool(varName, "ADVANCED")) {
varName += " (ADVANCED)";
}
@@ -1699,11 +1666,9 @@ void cmGlobalGenerator::CheckTargetProperties()
if (!notFoundMap.empty()) {
std::string notFoundVars;
- for (std::map<std::string, std::string>::const_iterator ii =
- notFoundMap.begin();
- ii != notFoundMap.end(); ++ii) {
- notFoundVars += ii->first;
- notFoundVars += ii->second;
+ for (auto const& notFound : notFoundMap) {
+ notFoundVars += notFound.first;
+ notFoundVars += notFound.second;
notFoundVars += "\n";
}
cmSystemTools::Error("The following variables are used in this project, "
@@ -1815,7 +1780,7 @@ int cmGlobalGenerator::Build(const std::string& /*unused*/,
output += "\n";
if (!cmSystemTools::RunSingleCommand(cleanCommand, outputPtr, outputPtr,
- &retVal, CM_NULLPTR, outputflag,
+ &retVal, nullptr, outputflag,
timeout)) {
cmSystemTools::SetRunCommandHideConsole(hideconsole);
cmSystemTools::Error("Generator: execution of make clean failed.");
@@ -1834,7 +1799,7 @@ int cmGlobalGenerator::Build(const std::string& /*unused*/,
output += "\n";
if (!cmSystemTools::RunSingleCommand(makeCommand, outputPtr, outputPtr,
- &retVal, CM_NULLPTR, outputflag,
+ &retVal, nullptr, outputflag,
timeout)) {
cmSystemTools::SetRunCommandHideConsole(hideconsole);
cmSystemTools::Error(
@@ -2035,16 +2000,15 @@ int cmGlobalGenerator::GetLinkerPreference(const std::string& lang) const
void cmGlobalGenerator::FillProjectMap()
{
this->ProjectMap.clear(); // make sure we start with a clean map
- unsigned int i;
- for (i = 0; i < this->LocalGenerators.size(); ++i) {
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
// for each local generator add all projects
- cmStateSnapshot snp = this->LocalGenerators[i]->GetStateSnapshot();
+ cmStateSnapshot snp = localGen->GetStateSnapshot();
std::string name;
do {
std::string snpProjName = snp.GetProjectName();
if (name != snpProjName) {
name = snpProjName;
- this->ProjectMap[name].push_back(this->LocalGenerators[i]);
+ this->ProjectMap[name].push_back(localGen);
}
snp = snp.GetBuildsystemDirectoryParent();
} while (snp.IsValid());
@@ -2057,22 +2021,20 @@ cmMakefile* cmGlobalGenerator::FindMakefile(const std::string& start_dir) const
if (i != this->MakefileSearchIndex.end()) {
return i->second;
}
- return CM_NULLPTR;
+ return nullptr;
}
///! Find a local generator by its startdirectory
cmLocalGenerator* cmGlobalGenerator::FindLocalGenerator(
const std::string& start_dir) const
{
- for (std::vector<cmLocalGenerator*>::const_iterator it =
- this->LocalGenerators.begin();
- it != this->LocalGenerators.end(); ++it) {
- std::string sd = (*it)->GetCurrentSourceDirectory();
+ for (cmLocalGenerator* lg : this->LocalGenerators) {
+ std::string sd = lg->GetCurrentSourceDirectory();
if (sd == start_dir) {
- return *it;
+ return lg;
}
}
- return CM_NULLPTR;
+ return nullptr;
}
void cmGlobalGenerator::AddAlias(const std::string& name,
@@ -2117,7 +2079,7 @@ cmTarget* cmGlobalGenerator::FindTargetImpl(std::string const& name) const
if (i != this->TargetSearchIndex.end()) {
return i->second;
}
- return CM_NULLPTR;
+ return nullptr;
}
cmGeneratorTarget* cmGlobalGenerator::FindGeneratorTargetImpl(
@@ -2128,7 +2090,7 @@ cmGeneratorTarget* cmGlobalGenerator::FindGeneratorTargetImpl(
if (i != this->GeneratorTargetSearchIndex.end()) {
return i->second;
}
- return CM_NULLPTR;
+ return nullptr;
}
cmTarget* cmGlobalGenerator::FindTarget(const std::string& name,
@@ -2413,7 +2375,7 @@ void cmGlobalGenerator::AddGlobalTarget_Install(
// install_strip
const char* install_strip = this->GetInstallStripTargetName();
- if ((install_strip != CM_NULLPTR) && (mf->IsSet("CMAKE_STRIP"))) {
+ if ((install_strip != nullptr) && (mf->IsSet("CMAKE_STRIP"))) {
gti.Name = install_strip;
gti.Message = "Installing the project stripped...";
gti.UsesTerminal = true;
@@ -2470,16 +2432,15 @@ cmTarget cmGlobalGenerator::CreateGlobalTarget(GlobalTargetInfo const& gti,
std::vector<std::string> no_byproducts;
std::vector<std::string> no_depends;
// Store the custom command in the target.
- cmCustomCommand cc(CM_NULLPTR, no_outputs, no_byproducts, no_depends,
- gti.CommandLines, CM_NULLPTR, gti.WorkingDir.c_str());
+ cmCustomCommand cc(nullptr, no_outputs, no_byproducts, no_depends,
+ gti.CommandLines, nullptr, gti.WorkingDir.c_str());
cc.SetUsesTerminal(gti.UsesTerminal);
target.AddPostBuildCommand(cc);
if (!gti.Message.empty()) {
target.SetProperty("EchoString", gti.Message.c_str());
}
- for (std::vector<std::string>::const_iterator dit = gti.Depends.begin();
- dit != gti.Depends.end(); ++dit) {
- target.AddUtility(*dit);
+ for (std::string const& d : gti.Depends) {
+ target.AddUtility(d);
}
// Organize in the "predefined targets" folder:
@@ -2556,7 +2517,7 @@ void cmGlobalGenerator::SetExternalMakefileProjectGenerator(
cmExternalMakefileProjectGenerator* extraGenerator)
{
this->ExtraGenerator = extraGenerator;
- if (this->ExtraGenerator != CM_NULLPTR) {
+ if (this->ExtraGenerator != nullptr) {
this->ExtraGenerator->SetGlobalGenerator(this);
}
}
@@ -2587,18 +2548,16 @@ void cmGlobalGenerator::GetTargetSets(TargetDependSet& projectTargets,
GeneratorVector const& generators)
{
// loop over all local generators
- for (std::vector<cmLocalGenerator*>::const_iterator i = generators.begin();
- i != generators.end(); ++i) {
+ for (cmLocalGenerator* generator : generators) {
// check to make sure generator is not excluded
- if (this->IsExcluded(root, *i)) {
+ if (this->IsExcluded(root, generator)) {
continue;
}
// Get the targets in the makefile
- std::vector<cmGeneratorTarget*> tgts = (*i)->GetGeneratorTargets();
+ const std::vector<cmGeneratorTarget*>& tgts =
+ generator->GetGeneratorTargets();
// loop over all the targets
- for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
- l != tgts.end(); ++l) {
- cmGeneratorTarget* target = *l;
+ for (cmGeneratorTarget* target : tgts) {
if (this->IsRootOnlyTarget(target) &&
target->GetLocalGenerator() != root) {
continue;
@@ -2625,8 +2584,8 @@ void cmGlobalGenerator::AddTargetDepends(cmGeneratorTarget const* target,
// This is the first time we have encountered the target.
// Recursively follow its dependencies.
TargetDependSet const& ts = this->GetTargetDirectDepends(target);
- for (TargetDependSet::const_iterator i = ts.begin(); i != ts.end(); ++i) {
- this->AddTargetDepends(*i, projectTargets);
+ for (auto const& t : ts) {
+ this->AddTargetDepends(t, projectTargets);
}
}
}
@@ -2771,11 +2730,9 @@ void cmGlobalGenerator::WriteRuleHashes(std::string const& pfile)
} else {
cmGeneratedFileStream fout(pfile.c_str());
fout << "# Hashes of file build rules.\n";
- for (std::map<std::string, RuleHash>::const_iterator rhi =
- this->RuleHashes.begin();
- rhi != this->RuleHashes.end(); ++rhi) {
- fout.write(rhi->second.Data, 32);
- fout << " " << rhi->first << "\n";
+ for (auto const& rh : this->RuleHashes) {
+ fout.write(rh.second.Data, 32);
+ fout << " " << rh.first << "\n";
}
}
}
@@ -2788,16 +2745,14 @@ void cmGlobalGenerator::WriteSummary()
fname += "/TargetDirectories.txt";
cmGeneratedFileStream fout(fname.c_str());
- for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
- std::vector<cmGeneratorTarget*> tgts =
- this->LocalGenerators[i]->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator it = tgts.begin();
- it != tgts.end(); ++it) {
- if ((*it)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+ for (cmLocalGenerator* lg : this->LocalGenerators) {
+ const std::vector<cmGeneratorTarget*>& tgts = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* tgt : tgts) {
+ if (tgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
- this->WriteSummary(*it);
- fout << (*it)->GetSupportDirectory() << "\n";
+ this->WriteSummary(tgt);
+ fout << tgt->GetSupportDirectory() << "\n";
}
}
}
@@ -2812,7 +2767,12 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target)
#ifdef CMAKE_BUILD_WITH_CMAKE
// Check whether labels are enabled for this target.
- if (const char* value = target->GetProperty("LABELS")) {
+ const char* targetLabels = target->GetProperty("LABELS");
+ const char* directoryLabels =
+ target->Target->GetMakefile()->GetProperty("LABELS");
+ const char* cmakeDirectoryLabels =
+ target->Target->GetMakefile()->GetDefinition("CMAKE_DIRECTORY_LABELS");
+ if (targetLabels || directoryLabels || cmakeDirectoryLabels) {
Json::Value lj_root(Json::objectValue);
Json::Value& lj_target = lj_root["target"] = Json::objectValue;
lj_target["name"] = target->GetName();
@@ -2822,19 +2782,48 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target)
cmSystemTools::MakeDirectory(dir.c_str());
cmGeneratedFileStream fout(file.c_str());
+ std::vector<std::string> labels;
+
// List the target-wide labels. All sources in the target get
// these labels.
- std::vector<std::string> labels;
- cmSystemTools::ExpandListArgument(value, labels);
- if (!labels.empty()) {
- fout << "# Target labels\n";
- for (std::vector<std::string>::const_iterator li = labels.begin();
- li != labels.end(); ++li) {
- fout << " " << *li << "\n";
- lj_target_labels.append(*li);
+ if (targetLabels) {
+ cmSystemTools::ExpandListArgument(targetLabels, labels);
+ if (!labels.empty()) {
+ fout << "# Target labels\n";
+ for (std::string const& l : labels) {
+ fout << " " << l << "\n";
+ lj_target_labels.append(l);
+ }
}
}
+ // List directory labels
+ std::vector<std::string> directoryLabelsList;
+ std::vector<std::string> cmakeDirectoryLabelsList;
+
+ if (directoryLabels) {
+ cmSystemTools::ExpandListArgument(directoryLabels, directoryLabelsList);
+ }
+
+ if (cmakeDirectoryLabels) {
+ cmSystemTools::ExpandListArgument(cmakeDirectoryLabels,
+ cmakeDirectoryLabelsList);
+ }
+
+ if (!directoryLabelsList.empty() || !cmakeDirectoryLabelsList.empty()) {
+ fout << "# Directory labels\n";
+ }
+
+ for (std::string const& li : directoryLabelsList) {
+ fout << " " << li << "\n";
+ lj_target_labels.append(li);
+ }
+
+ for (std::string const& li : cmakeDirectoryLabelsList) {
+ fout << " " << li << "\n";
+ lj_target_labels.append(li);
+ }
+
// List the source files with any per-source labels.
fout << "# Source files and their labels\n";
std::vector<cmSourceFile*> sources;
@@ -2843,9 +2832,8 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target)
if (configs.empty()) {
configs.push_back("");
}
- for (std::vector<std::string>::const_iterator ci = configs.begin();
- ci != configs.end(); ++ci) {
- target->GetSourceFiles(sources, *ci);
+ for (std::string const& c : configs) {
+ target->GetSourceFiles(sources, c);
}
std::vector<cmSourceFile*>::const_iterator sourcesEnd =
cmRemoveDuplicates(sources);
@@ -2860,10 +2848,9 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target)
labels.clear();
Json::Value& lj_source_labels = lj_source["labels"] = Json::arrayValue;
cmSystemTools::ExpandListArgument(svalue, labels);
- for (std::vector<std::string>::const_iterator li = labels.begin();
- li != labels.end(); ++li) {
- fout << " " << *li << "\n";
- lj_source_labels.append(*li);
+ for (std::string const& label : labels) {
+ fout << " " << label << "\n";
+ lj_source_labels.append(label);
}
}
}
@@ -2881,11 +2868,11 @@ void cmGlobalGenerator::WriteSummary(cmGeneratorTarget* target)
std::string cmGlobalGenerator::EscapeJSON(const std::string& s)
{
std::string result;
- for (std::string::size_type i = 0; i < s.size(); ++i) {
- if (s[i] == '"' || s[i] == '\\') {
+ for (char i : s) {
+ if (i == '"' || i == '\\') {
result += '\\';
}
- result += s[i];
+ result += i;
}
return result;
}
@@ -2905,18 +2892,16 @@ cmGlobalGenerator::GetFilenameTargetDepends(cmSourceFile* sf) const
void cmGlobalGenerator::CreateEvaluationSourceFiles(
std::string const& config) const
{
- unsigned int i;
- for (i = 0; i < this->LocalGenerators.size(); ++i) {
- this->LocalGenerators[i]->CreateEvaluationFileOutputs(config);
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ localGen->CreateEvaluationFileOutputs(config);
}
}
void cmGlobalGenerator::ProcessEvaluationFiles()
{
std::vector<std::string> generatedFiles;
- unsigned int i;
- for (i = 0; i < this->LocalGenerators.size(); ++i) {
- this->LocalGenerators[i]->ProcessEvaluationFiles(generatedFiles);
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ localGen->ProcessEvaluationFiles(generatedFiles);
}
}
@@ -2947,9 +2932,8 @@ bool cmGlobalGenerator::GenerateCPackPropertiesFile()
cmGeneratedFileStream file(path.c_str());
file << "# CPack properties\n";
- for (cmake::InstalledFilesMap::const_iterator i = installedFiles.begin();
- i != installedFiles.end(); ++i) {
- cmInstalledFile const& installedFile = i->second;
+ for (auto const& i : installedFiles) {
+ cmInstalledFile const& installedFile = i.second;
cmCPackPropertiesGenerator cpackPropertiesGenerator(lg, installedFile,
configs);
diff --git a/Source/cmGlobalGenerator.h b/Source/cmGlobalGenerator.h
index 871178be1..18ca682c7 100644
--- a/Source/cmGlobalGenerator.h
+++ b/Source/cmGlobalGenerator.h
@@ -3,23 +3,24 @@
#ifndef cmGlobalGenerator_h
#define cmGlobalGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <map>
#include <set>
#include <string>
+#include <unordered_map>
#include <utility>
#include <vector>
#include "cmCustomCommandLines.h"
#include "cmExportSetMap.h"
+#include "cmQtAutoGenDigest.h"
#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
#include "cmTargetDepend.h"
#include "cm_codecvt.hxx"
-#include "cm_unordered_map.hxx"
#if defined(CMAKE_BUILD_WITH_CMAKE)
#include "cmFileLockPool.h"
@@ -187,9 +188,15 @@ public:
return this->LocalGenerators;
}
- cmMakefile* GetCurrentMakefile() const { return this->CurrentMakefile; }
+ cmMakefile* GetCurrentMakefile() const
+ {
+ return this->CurrentConfigureMakefile;
+ }
- void SetCurrentMakefile(cmMakefile* mf) { this->CurrentMakefile = mf; }
+ void SetCurrentMakefile(cmMakefile* mf)
+ {
+ this->CurrentConfigureMakefile = mf;
+ }
void AddMakefile(cmMakefile* mf);
@@ -289,15 +296,15 @@ public:
virtual const char* GetAllTargetName() const { return "ALL_BUILD"; }
virtual const char* GetInstallTargetName() const { return "INSTALL"; }
- virtual const char* GetInstallLocalTargetName() const { return CM_NULLPTR; }
- virtual const char* GetInstallStripTargetName() const { return CM_NULLPTR; }
- virtual const char* GetPreinstallTargetName() const { return CM_NULLPTR; }
+ virtual const char* GetInstallLocalTargetName() const { return nullptr; }
+ virtual const char* GetInstallStripTargetName() const { return nullptr; }
+ virtual const char* GetPreinstallTargetName() const { return nullptr; }
virtual const char* GetTestTargetName() const { return "RUN_TESTS"; }
virtual const char* GetPackageTargetName() const { return "PACKAGE"; }
- virtual const char* GetPackageSourceTargetName() const { return CM_NULLPTR; }
- virtual const char* GetEditCacheTargetName() const { return CM_NULLPTR; }
- virtual const char* GetRebuildCacheTargetName() const { return CM_NULLPTR; }
- virtual const char* GetCleanTargetName() const { return CM_NULLPTR; }
+ virtual const char* GetPackageSourceTargetName() const { return nullptr; }
+ virtual const char* GetEditCacheTargetName() const { return nullptr; }
+ virtual const char* GetRebuildCacheTargetName() const { return nullptr; }
+ virtual const char* GetCleanTargetName() const { return nullptr; }
// Lookup edit_cache target command preferred by this generator.
virtual std::string GetEditCacheCommand() const { return ""; }
@@ -310,7 +317,7 @@ public:
TargetDependSet const& GetTargetDirectDepends(
const cmGeneratorTarget* target);
- const std::map<std::string, std::vector<cmLocalGenerator*> >& GetProjectMap()
+ const std::map<std::string, std::vector<cmLocalGenerator*>>& GetProjectMap()
const
{
return this->ProjectMap;
@@ -416,7 +423,8 @@ protected:
virtual bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const;
- std::vector<const cmGeneratorTarget*> CreateQtAutoGeneratorsTargets();
+ // Qt auto generators
+ cmQtAutoGenDigestUPV CreateQtAutoGeneratorsTargets();
std::string SelectMakeProgram(const std::string& makeProgram,
const std::string& makeDefault = "") const;
@@ -460,9 +468,9 @@ protected:
cmake* CMakeInstance;
std::vector<cmMakefile*> Makefiles;
std::vector<cmLocalGenerator*> LocalGenerators;
- cmMakefile* CurrentMakefile;
+ cmMakefile* CurrentConfigureMakefile;
// map from project name to vector of local generators in that project
- std::map<std::string, std::vector<cmLocalGenerator*> > ProjectMap;
+ std::map<std::string, std::vector<cmLocalGenerator*>> ProjectMap;
// Set of named installation components requested by the project.
std::set<std::string> InstallComponents;
@@ -482,9 +490,10 @@ protected:
const char* GetPredefinedTargetsFolder();
private:
- typedef CM_UNORDERED_MAP<std::string, cmTarget*> TargetMap;
- typedef CM_UNORDERED_MAP<std::string, cmGeneratorTarget*> GeneratorTargetMap;
- typedef CM_UNORDERED_MAP<std::string, cmMakefile*> MakefileMap;
+ typedef std::unordered_map<std::string, cmTarget*> TargetMap;
+ typedef std::unordered_map<std::string, cmGeneratorTarget*>
+ GeneratorTargetMap;
+ typedef std::unordered_map<std::string, cmMakefile*> MakefileMap;
// Map efficiently from target name to cmTarget instance.
// Do not use this structure for looping over all targets.
// It contains both normal and globally visible imported targets.
@@ -550,7 +559,7 @@ private:
void IndexMakefile(cmMakefile* mf);
- virtual const char* GetBuildIgnoreErrorsFlag() const { return CM_NULLPTR; }
+ virtual const char* GetBuildIgnoreErrorsFlag() const { return nullptr; }
// Cache directory content and target files to be built.
struct DirectoryContent
@@ -573,7 +582,7 @@ private:
// track targets to issue CMP0068 warning for.
std::set<std::string> CMP0068WarnTargets;
- mutable std::map<cmSourceFile*, std::set<cmGeneratorTarget const*> >
+ mutable std::map<cmSourceFile*, std::set<cmGeneratorTarget const*>>
FilenameTargetDepends;
#if defined(CMAKE_BUILD_WITH_CMAKE)
diff --git a/Source/cmGlobalGeneratorFactory.h b/Source/cmGlobalGeneratorFactory.h
index d5a6db06e..4e3e7705b 100644
--- a/Source/cmGlobalGeneratorFactory.h
+++ b/Source/cmGlobalGeneratorFactory.h
@@ -3,7 +3,7 @@
#ifndef cmGlobalGeneratorFactory_h
#define cmGlobalGeneratorFactory_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -45,31 +45,31 @@ class cmGlobalGeneratorSimpleFactory : public cmGlobalGeneratorFactory
public:
/** Create a GlobalGenerator */
cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
- cmake* cm) const CM_OVERRIDE
+ cmake* cm) const override
{
if (name != T::GetActualName()) {
- return CM_NULLPTR;
+ return nullptr;
}
return new T(cm);
}
/** Get the documentation entry for this factory */
- void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
+ void GetDocumentation(cmDocumentationEntry& entry) const override
{
T::GetDocumentation(entry);
}
/** Get the names of the current registered generators */
- void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
+ void GetGenerators(std::vector<std::string>& names) const override
{
names.push_back(T::GetActualName());
}
/** Determine whether or not this generator supports toolsets */
- bool SupportsToolset() const CM_OVERRIDE { return T::SupportsToolset(); }
+ bool SupportsToolset() const override { return T::SupportsToolset(); }
/** Determine whether or not this generator supports platforms */
- bool SupportsPlatform() const CM_OVERRIDE { return T::SupportsPlatform(); }
+ bool SupportsPlatform() const override { return T::SupportsPlatform(); }
};
#endif
diff --git a/Source/cmGlobalGhsMultiGenerator.cxx b/Source/cmGlobalGhsMultiGenerator.cxx
index 42ab4d98a..788a1798a 100644
--- a/Source/cmGlobalGhsMultiGenerator.cxx
+++ b/Source/cmGlobalGhsMultiGenerator.cxx
@@ -260,7 +260,7 @@ void cmGlobalGhsMultiGenerator::Generate()
for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
cmLocalGhsMultiGenerator* lg =
static_cast<cmLocalGhsMultiGenerator*>(this->LocalGenerators[i]);
- std::vector<cmGeneratorTarget*> tgts = lg->GetGeneratorTargets();
+ const std::vector<cmGeneratorTarget*>& tgts = lg->GetGeneratorTargets();
this->UpdateBuildFiles(tgts);
}
}
@@ -436,9 +436,9 @@ std::string cmGlobalGhsMultiGenerator::GetFileNameFromPath(
}
void cmGlobalGhsMultiGenerator::UpdateBuildFiles(
- std::vector<cmGeneratorTarget*> tgts)
+ const std::vector<cmGeneratorTarget*>& tgts)
{
- for (std::vector<cmGeneratorTarget*>::iterator tgtsI = tgts.begin();
+ for (std::vector<cmGeneratorTarget*>::const_iterator tgtsI = tgts.begin();
tgtsI != tgts.end(); ++tgtsI) {
const cmGeneratorTarget* tgt = *tgtsI;
if (IsTgtForBuild(tgt)) {
diff --git a/Source/cmGlobalGhsMultiGenerator.h b/Source/cmGlobalGhsMultiGenerator.h
index 7b3eebbdf..7d4b2ba7f 100644
--- a/Source/cmGlobalGhsMultiGenerator.h
+++ b/Source/cmGlobalGhsMultiGenerator.h
@@ -57,7 +57,7 @@ public:
/*
* Determine what program to use for building the project.
*/
- bool FindMakeProgram(cmMakefile* mf) CM_OVERRIDE;
+ bool FindMakeProgram(cmMakefile* mf) override;
cmGeneratedFileStream* GetBuildFileStream()
{
@@ -116,7 +116,7 @@ private:
std::vector<cmsys::String>::const_iterator end,
GhsMultiGpj::Types projType);
static std::string GetFileNameFromPath(std::string const& path);
- void UpdateBuildFiles(std::vector<cmGeneratorTarget*> tgts);
+ void UpdateBuildFiles(const std::vector<cmGeneratorTarget*>& tgts);
bool IsTgtForBuild(const cmGeneratorTarget* tgt);
std::vector<cmGeneratedFileStream*> TargetSubProjects;
diff --git a/Source/cmGlobalKdevelopGenerator.cxx b/Source/cmGlobalKdevelopGenerator.cxx
index e72c6e384..b1e630e29 100644
--- a/Source/cmGlobalKdevelopGenerator.cxx
+++ b/Source/cmGlobalKdevelopGenerator.cxx
@@ -16,7 +16,6 @@
#include "cmsys/Directory.hxx"
#include "cmsys/FStream.hxx"
-#include <map>
#include <set>
#include <string.h>
#include <utility>
@@ -49,15 +48,13 @@ void cmGlobalKdevelopGenerator::Generate()
{
// for each sub project in the project create
// a kdevelop project
- for (std::map<std::string, std::vector<cmLocalGenerator*> >::const_iterator
- it = this->GlobalGenerator->GetProjectMap().begin();
- it != this->GlobalGenerator->GetProjectMap().end(); ++it) {
- std::string outputDir = it->second[0]->GetCurrentBinaryDirectory();
- std::string projectDir = it->second[0]->GetSourceDirectory();
- std::string projectName = it->second[0]->GetProjectName();
+ for (auto const& it : this->GlobalGenerator->GetProjectMap()) {
+ std::string outputDir = it.second[0]->GetCurrentBinaryDirectory();
+ std::string projectDir = it.second[0]->GetSourceDirectory();
+ std::string projectName = it.second[0]->GetProjectName();
std::string cmakeFilePattern("CMakeLists.txt;*.cmake;");
std::string fileToOpen;
- const std::vector<cmLocalGenerator*>& lgs = it->second;
+ const std::vector<cmLocalGenerator*>& lgs = it.second;
// create the project.kdevelop.filelist file
if (!this->CreateFilelistFile(lgs, outputDir, projectDir, projectName,
cmakeFilePattern, fileToOpen)) {
@@ -67,15 +64,12 @@ void cmGlobalKdevelopGenerator::Generate()
// try to find the name of an executable so we have something to
// run from kdevelop for now just pick the first executable found
std::string executable;
- for (std::vector<cmLocalGenerator*>::const_iterator lg = lgs.begin();
- lg != lgs.end(); lg++) {
+ for (cmLocalGenerator* lg : lgs) {
std::vector<cmGeneratorTarget*> const& targets =
- (*lg)->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::const_iterator ti =
- targets.begin();
- ti != targets.end(); ti++) {
- if ((*ti)->GetType() == cmStateEnums::EXECUTABLE) {
- executable = (*ti)->GetLocation("");
+ lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
+ if (target->GetType() == cmStateEnums::EXECUTABLE) {
+ executable = target->GetLocation("");
break;
}
}
@@ -104,40 +98,35 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile(
std::vector<std::string> const& hdrExts =
this->GlobalGenerator->GetCMakeInstance()->GetHeaderExtensions();
- for (std::vector<cmLocalGenerator*>::const_iterator it = lgs.begin();
- it != lgs.end(); it++) {
- cmMakefile* makefile = (*it)->GetMakefile();
+ for (cmLocalGenerator* lg : lgs) {
+ cmMakefile* makefile = lg->GetMakefile();
const std::vector<std::string>& listFiles = makefile->GetListFiles();
- for (std::vector<std::string>::const_iterator lt = listFiles.begin();
- lt != listFiles.end(); lt++) {
- tmp = *lt;
+ for (std::string const& listFile : listFiles) {
+ tmp = listFile;
cmSystemTools::ReplaceString(tmp, projectDir.c_str(), "");
// make sure the file is part of this source tree
if ((tmp[0] != '/') &&
(strstr(tmp.c_str(), cmake::GetCMakeFilesDirectoryPostSlash()) ==
- CM_NULLPTR)) {
+ nullptr)) {
files.insert(tmp);
tmp = cmSystemTools::GetFilenameName(tmp);
// add all files which dont match the default
// */CMakeLists.txt;*cmake; to the file pattern
if ((tmp != "CMakeLists.txt") &&
- (strstr(tmp.c_str(), ".cmake") == CM_NULLPTR)) {
+ (strstr(tmp.c_str(), ".cmake") == nullptr)) {
cmakeFilePattern += tmp + ";";
}
}
}
// get all sources
- std::vector<cmGeneratorTarget*> targets = (*it)->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator ti = targets.begin();
- ti != targets.end(); ti++) {
+ const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* gt : targets) {
std::vector<cmSourceFile*> sources;
- cmGeneratorTarget* gt = *ti;
gt->GetSourceFiles(sources, gt->Target->GetMakefile()->GetSafeDefinition(
"CMAKE_BUILD_TYPE"));
- for (std::vector<cmSourceFile*>::const_iterator si = sources.begin();
- si != sources.end(); si++) {
- tmp = (*si)->GetFullPath();
+ for (cmSourceFile* sf : sources) {
+ tmp = sf->GetFullPath();
std::string headerBasename = cmSystemTools::GetFilenamePath(tmp);
headerBasename += "/";
headerBasename += cmSystemTools::GetFilenameWithoutExtension(tmp);
@@ -146,16 +135,15 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile(
if ((tmp[0] != '/') &&
(strstr(tmp.c_str(), cmake::GetCMakeFilesDirectoryPostSlash()) ==
- CM_NULLPTR) &&
+ nullptr) &&
(cmSystemTools::GetFilenameExtension(tmp) != ".moc")) {
files.insert(tmp);
// check if there's a matching header around
- for (std::vector<std::string>::const_iterator ext = hdrExts.begin();
- ext != hdrExts.end(); ++ext) {
+ for (std::string const& hdrExt : hdrExts) {
std::string hname = headerBasename;
hname += ".";
- hname += *ext;
+ hname += hdrExt;
if (cmSystemTools::FileExists(hname.c_str())) {
cmSystemTools::ReplaceString(hname, projectDir.c_str(), "");
files.insert(hname);
@@ -164,13 +152,12 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile(
}
}
}
- for (std::vector<std::string>::const_iterator lt = listFiles.begin();
- lt != listFiles.end(); lt++) {
- tmp = *lt;
+ for (std::string const& listFile : listFiles) {
+ tmp = listFile;
cmSystemTools::ReplaceString(tmp, projectDir.c_str(), "");
if ((tmp[0] != '/') &&
(strstr(tmp.c_str(), cmake::GetCMakeFilesDirectoryPostSlash()) ==
- CM_NULLPTR)) {
+ nullptr)) {
files.insert(tmp);
}
}
@@ -200,10 +187,9 @@ bool cmGlobalKdevelopGenerator::CreateFilelistFile(
}
fileToOpen = "";
- for (std::set<std::string>::const_iterator it = files.begin();
- it != files.end(); it++) {
+ for (std::string const& file : files) {
// get the full path to the file
- tmp = cmSystemTools::CollapseFullPath(*it, projectDir.c_str());
+ tmp = cmSystemTools::CollapseFullPath(file, projectDir.c_str());
// just select the first source file
if (fileToOpen.empty()) {
std::string ext = cmSystemTools::GetFilenameExtension(tmp);
@@ -296,21 +282,20 @@ void cmGlobalKdevelopGenerator::MergeProjectFiles(
return;
}
- for (std::vector<std::string>::const_iterator it = lines.begin();
- it != lines.end(); it++) {
- const char* line = (*it).c_str();
+ for (std::string const& l : lines) {
+ const char* line = l.c_str();
// skip these tags as they are always replaced
- if ((strstr(line, "<projectdirectory>") != CM_NULLPTR) ||
- (strstr(line, "<projectmanagement>") != CM_NULLPTR) ||
- (strstr(line, "<absoluteprojectpath>") != CM_NULLPTR) ||
- (strstr(line, "<filelistdirectory>") != CM_NULLPTR) ||
- (strstr(line, "<buildtool>") != CM_NULLPTR) ||
- (strstr(line, "<builddir>") != CM_NULLPTR)) {
+ if ((strstr(line, "<projectdirectory>") != nullptr) ||
+ (strstr(line, "<projectmanagement>") != nullptr) ||
+ (strstr(line, "<absoluteprojectpath>") != nullptr) ||
+ (strstr(line, "<filelistdirectory>") != nullptr) ||
+ (strstr(line, "<buildtool>") != nullptr) ||
+ (strstr(line, "<builddir>") != nullptr)) {
continue;
}
// output the line from the file if it is not one of the above tags
- fout << *it << "\n";
+ fout << l << "\n";
// if this is the <general> tag output the stuff that goes in the
// general tag
if (strstr(line, "<general>")) {
@@ -433,10 +418,8 @@ void cmGlobalKdevelopGenerator::CreateNewProjectFile(
xml.EndElement(); // make
xml.StartElement("blacklist");
- for (std::vector<std::string>::const_iterator dirIt =
- this->Blacklist.begin();
- dirIt != this->Blacklist.end(); ++dirIt) {
- xml.Element("path", *dirIt);
+ for (std::string const& dir : this->Blacklist) {
+ xml.Element("path", dir);
}
xml.EndElement();
diff --git a/Source/cmGlobalKdevelopGenerator.h b/Source/cmGlobalKdevelopGenerator.h
index bdcf8a190..d6c43f3f9 100644
--- a/Source/cmGlobalKdevelopGenerator.h
+++ b/Source/cmGlobalKdevelopGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmGlobalKdevelopGenerator_h
#define cmGlobalKdevelopGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmExternalMakefileProjectGenerator.h"
@@ -30,7 +30,7 @@ public:
static cmExternalMakefileProjectGeneratorFactory* GetFactory();
- void Generate() CM_OVERRIDE;
+ void Generate() override;
private:
/*** Create the foo.kdevelop.filelist file, return false if it doesn't
diff --git a/Source/cmGlobalNMakeMakefileGenerator.h b/Source/cmGlobalNMakeMakefileGenerator.h
index 6eb21249d..05ab90435 100644
--- a/Source/cmGlobalNMakeMakefileGenerator.h
+++ b/Source/cmGlobalNMakeMakefileGenerator.h
@@ -27,7 +27,7 @@ public:
static std::string GetActualName() { return "NMake Makefiles"; }
/** Get encoding used by generator for makefile files */
- codecvt::Encoding GetMakefileEncoding() const CM_OVERRIDE
+ codecvt::Encoding GetMakefileEncoding() const override
{
return codecvt::ANSI;
}
diff --git a/Source/cmGlobalNinjaGenerator.cxx b/Source/cmGlobalNinjaGenerator.cxx
index 2eef9e492..d5531cbe8 100644
--- a/Source/cmGlobalNinjaGenerator.cxx
+++ b/Source/cmGlobalNinjaGenerator.cxx
@@ -10,6 +10,7 @@
#include <ctype.h>
#include <functional>
#include <iterator>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
@@ -32,7 +33,6 @@
#include "cmTarget.h"
#include "cmTargetDepend.h"
#include "cmVersion.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
class cmLinkLineComputer;
@@ -90,12 +90,12 @@ std::string cmGlobalNinjaGenerator::EncodeRuleName(std::string const& name)
// Ninja rule names must match "[a-zA-Z0-9_.-]+". Use ".xx" to encode
// "." and all invalid characters as hexadecimal.
std::string encoded;
- for (std::string::const_iterator i = name.begin(); i != name.end(); ++i) {
- if (isalnum(*i) || *i == '_' || *i == '-') {
- encoded += *i;
+ for (char i : name) {
+ if (isalnum(i) || i == '_' || i == '-') {
+ encoded += i;
} else {
char buf[16];
- sprintf(buf, ".%02x", static_cast<unsigned int>(*i));
+ sprintf(buf, ".%02x", static_cast<unsigned int>(i));
encoded += buf;
}
}
@@ -177,26 +177,23 @@ void cmGlobalNinjaGenerator::WriteBuild(
// TODO: Better formatting for when there are multiple input/output files.
// Write explicit dependencies.
- for (cmNinjaDeps::const_iterator i = explicitDeps.begin();
- i != explicitDeps.end(); ++i) {
- arguments += " " + EncodeIdent(EncodePath(*i), os);
+ for (std::string const& explicitDep : explicitDeps) {
+ arguments += " " + EncodeIdent(EncodePath(explicitDep), os);
}
// Write implicit dependencies.
if (!implicitDeps.empty()) {
arguments += " |";
- for (cmNinjaDeps::const_iterator i = implicitDeps.begin();
- i != implicitDeps.end(); ++i) {
- arguments += " " + EncodeIdent(EncodePath(*i), os);
+ for (std::string const& implicitDep : implicitDeps) {
+ arguments += " " + EncodeIdent(EncodePath(implicitDep), os);
}
}
// Write order-only dependencies.
if (!orderOnlyDeps.empty()) {
arguments += " ||";
- for (cmNinjaDeps::const_iterator i = orderOnlyDeps.begin();
- i != orderOnlyDeps.end(); ++i) {
- arguments += " " + EncodeIdent(EncodePath(*i), os);
+ for (std::string const& orderOnlyDep : orderOnlyDeps) {
+ arguments += " " + EncodeIdent(EncodePath(orderOnlyDep), os);
}
}
@@ -206,18 +203,16 @@ void cmGlobalNinjaGenerator::WriteBuild(
// Write outputs files.
build += "build";
- for (cmNinjaDeps::const_iterator i = outputs.begin(); i != outputs.end();
- ++i) {
- build += " " + EncodeIdent(EncodePath(*i), os);
+ for (std::string const& output : outputs) {
+ build += " " + EncodeIdent(EncodePath(output), os);
if (this->ComputingUnknownDependencies) {
- this->CombinedBuildOutputs.insert(*i);
+ this->CombinedBuildOutputs.insert(output);
}
}
if (!implicitOuts.empty()) {
build += " |";
- for (cmNinjaDeps::const_iterator i = implicitOuts.begin();
- i != implicitOuts.end(); ++i) {
- build += " " + EncodeIdent(EncodePath(*i), os);
+ for (std::string const& implicitOut : implicitOuts) {
+ build += " " + EncodeIdent(EncodePath(implicitOut), os);
}
}
build += ":";
@@ -227,20 +222,18 @@ void cmGlobalNinjaGenerator::WriteBuild(
// Write the variables bound to this build statement.
std::ostringstream variable_assignments;
- for (cmNinjaVars::const_iterator i = variables.begin(); i != variables.end();
- ++i) {
- cmGlobalNinjaGenerator::WriteVariable(variable_assignments, i->first,
- i->second, "", 1);
+ for (auto const& variable : variables) {
+ cmGlobalNinjaGenerator::WriteVariable(variable_assignments, variable.first,
+ variable.second, "", 1);
}
// check if a response file rule should be used
std::string buildstr = build;
std::string assignments = variable_assignments.str();
- const std::string& args = arguments;
bool useResponseFile = false;
if (cmdLineLimit < 0 ||
(cmdLineLimit > 0 &&
- (args.size() + buildstr.size() + assignments.size() + 1000) >
+ (arguments.size() + buildstr.size() + assignments.size() + 1000) >
static_cast<size_t>(cmdLineLimit))) {
variable_assignments.str(std::string());
cmGlobalNinjaGenerator::WriteVariable(variable_assignments, "RSP_FILE",
@@ -252,7 +245,7 @@ void cmGlobalNinjaGenerator::WriteBuild(
*usedResponseFile = useResponseFile;
}
- os << buildstr << args << assignments;
+ os << buildstr << arguments << assignments;
}
void cmGlobalNinjaGenerator::WritePhonyBuild(
@@ -311,8 +304,8 @@ void cmGlobalNinjaGenerator::WriteCustomCommandBuild(
if (this->ComputingUnknownDependencies) {
// we need to track every dependency that comes in, since we are trying
// to find dependencies that are side effects of build commands
- for (cmNinjaDeps::const_iterator i = deps.begin(); i != deps.end(); ++i) {
- this->CombinedCustomCommandExplicitDependencies.insert(*i);
+ for (std::string const& dep : deps) {
+ this->CombinedCustomCommandExplicitDependencies.insert(dep);
}
}
}
@@ -465,18 +458,17 @@ void cmGlobalNinjaGenerator::WriteDefault(std::ostream& os,
{
cmGlobalNinjaGenerator::WriteComment(os, comment);
os << "default";
- for (cmNinjaDeps::const_iterator i = targets.begin(); i != targets.end();
- ++i) {
- os << " " << *i;
+ for (std::string const& target : targets) {
+ os << " " << target;
}
os << "\n";
}
cmGlobalNinjaGenerator::cmGlobalNinjaGenerator(cmake* cm)
: cmGlobalCommonGenerator(cm)
- , BuildFileStream(CM_NULLPTR)
- , RulesFileStream(CM_NULLPTR)
- , CompileCommandsStream(CM_NULLPTR)
+ , BuildFileStream(nullptr)
+ , RulesFileStream(nullptr)
+ , CompileCommandsStream(nullptr)
, Rules()
, AllDependencies()
, UsingGCCOnWindows(false)
@@ -582,8 +574,8 @@ bool cmGlobalNinjaGenerator::FindMakeProgram(cmMakefile* mf)
command.push_back("--version");
std::string version;
std::string error;
- if (!cmSystemTools::RunSingleCommand(command, &version, &error, CM_NULLPTR,
- CM_NULLPTR,
+ if (!cmSystemTools::RunSingleCommand(command, &version, &error, nullptr,
+ nullptr,
cmSystemTools::OUTPUT_NONE)) {
mf->IssueMessage(cmake::FATAL_ERROR, "Running\n '" +
cmJoin(command, "' '") + "'\n"
@@ -670,12 +662,11 @@ void cmGlobalNinjaGenerator::EnableLanguage(
std::vector<std::string> const& langs, cmMakefile* mf, bool optional)
{
this->cmGlobalGenerator::EnableLanguage(langs, mf, optional);
- for (std::vector<std::string>::const_iterator l = langs.begin();
- l != langs.end(); ++l) {
- if (*l == "NONE") {
+ for (std::string const& l : langs) {
+ if (l == "NONE") {
continue;
}
- this->ResolveLanguageCompiler(*l, mf, optional);
+ this->ResolveLanguageCompiler(l, mf, optional);
}
#ifdef _WIN32
if (strcmp(mf->GetSafeDefinition("CMAKE_C_SIMULATE_ID"), "MSVC") != 0 &&
@@ -741,7 +732,7 @@ void cmGlobalNinjaGenerator::AddRule(
description, comment, depfile, deptype,
rspfile, rspcontent, restat, generator);
- this->RuleCmdLength[name] = (int)command.size();
+ this->RuleCmdLength[name] = static_cast<int>(command.size());
}
bool cmGlobalNinjaGenerator::HasRule(const std::string& name)
@@ -805,7 +796,7 @@ void cmGlobalNinjaGenerator::CloseBuildFileStream()
{
if (this->BuildFileStream) {
delete this->BuildFileStream;
- this->BuildFileStream = CM_NULLPTR;
+ this->BuildFileStream = nullptr;
} else {
cmSystemTools::Error("Build file stream was not open.");
}
@@ -847,7 +838,7 @@ void cmGlobalNinjaGenerator::CloseRulesFileStream()
{
if (this->RulesFileStream) {
delete this->RulesFileStream;
- this->RulesFileStream = CM_NULLPTR;
+ this->RulesFileStream = nullptr;
} else {
cmSystemTools::Error("Rules file stream was not open.");
}
@@ -870,18 +861,24 @@ static void EnsureTrailingSlash(std::string& path)
#endif
}
-std::string cmGlobalNinjaGenerator::ConvertToNinjaPath(
+std::string const& cmGlobalNinjaGenerator::ConvertToNinjaPath(
const std::string& path) const
{
+ auto const f = ConvertToNinjaPathCache.find(path);
+ if (f != ConvertToNinjaPathCache.end()) {
+ return f->second;
+ }
+
cmLocalNinjaGenerator* ng =
static_cast<cmLocalNinjaGenerator*>(this->LocalGenerators[0]);
- std::string convPath = ng->ConvertToRelativePath(
- this->LocalGenerators[0]->GetState()->GetBinaryDirectory(), path);
+ const char* bin_dir = ng->GetState()->GetBinaryDirectory();
+ std::string convPath = ng->ConvertToRelativePath(bin_dir, path);
convPath = this->NinjaOutputPath(convPath);
#ifdef _WIN32
std::replace(convPath.begin(), convPath.end(), '/', '\\');
#endif
- return convPath;
+ return ConvertToNinjaPathCache.emplace(path, std::move(convPath))
+ .first->second;
}
void cmGlobalNinjaGenerator::AddCXXCompileCommand(
@@ -928,7 +925,7 @@ void cmGlobalNinjaGenerator::CloseCompileCommandsStream()
if (this->CompileCommandsStream) {
*this->CompileCommandsStream << "\n]";
delete this->CompileCommandsStream;
- this->CompileCommandsStream = CM_NULLPTR;
+ this->CompileCommandsStream = nullptr;
}
}
@@ -952,15 +949,13 @@ void cmGlobalNinjaGenerator::AddDependencyToAll(const std::string& input)
void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies()
{
- for (std::map<std::string, std::set<std::string> >::iterator i =
- this->AssumedSourceDependencies.begin();
- i != this->AssumedSourceDependencies.end(); ++i) {
+ for (auto const& asd : this->AssumedSourceDependencies) {
cmNinjaDeps deps;
- std::copy(i->second.begin(), i->second.end(), std::back_inserter(deps));
+ std::copy(asd.second.begin(), asd.second.end(), std::back_inserter(deps));
WriteCustomCommandBuild(/*command=*/"", /*description=*/"",
"Assume dependencies for generated source file.",
/*depfile*/ "", /*uses_terminal*/ false,
- /*restat*/ true, cmNinjaDeps(1, i->first), deps);
+ /*restat*/ true, cmNinjaDeps(1, asd.first), deps);
}
}
@@ -1025,22 +1020,20 @@ void cmGlobalNinjaGenerator::AppendTargetDepends(
if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
// These depend only on other CMake-provided targets, e.g. "all".
std::set<std::string> const& utils = target->GetUtilities();
- for (std::set<std::string>::const_iterator i = utils.begin();
- i != utils.end(); ++i) {
+ for (std::string const& util : utils) {
std::string d =
target->GetLocalGenerator()->GetCurrentBinaryDirectory() +
- std::string("/") + *i;
+ std::string("/") + util;
outputs.push_back(this->ConvertToNinjaPath(d));
}
} else {
cmNinjaDeps outs;
cmTargetDependSet const& targetDeps = this->GetTargetDirectDepends(target);
- for (cmTargetDependSet::const_iterator i = targetDeps.begin();
- i != targetDeps.end(); ++i) {
- if ((*i)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+ for (cmTargetDepend const& targetDep : targetDeps) {
+ if (targetDep->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
- this->AppendTargetOutputs(*i, outs, depends);
+ this->AppendTargetOutputs(targetDep, outs, depends);
}
std::sort(outs.begin(), outs.end());
outputs.insert(outputs.end(), outs.begin(), outs.end());
@@ -1050,37 +1043,51 @@ void cmGlobalNinjaGenerator::AppendTargetDepends(
void cmGlobalNinjaGenerator::AppendTargetDependsClosure(
cmGeneratorTarget const* target, cmNinjaDeps& outputs)
{
- TargetDependsClosureMap::iterator i =
- this->TargetDependsClosures.find(target);
- if (i == this->TargetDependsClosures.end()) {
- TargetDependsClosureMap::value_type e(
- target, std::set<cmGeneratorTarget const*>());
- i = this->TargetDependsClosures.insert(e).first;
- this->ComputeTargetDependsClosure(target, i->second);
- }
- std::set<cmGeneratorTarget const*> const& targets = i->second;
- cmNinjaDeps outs;
- for (std::set<cmGeneratorTarget const*>::const_iterator ti = targets.begin();
- ti != targets.end(); ++ti) {
- this->AppendTargetOutputs(*ti, outs);
- }
- std::sort(outs.begin(), outs.end());
+ cmNinjaOuts outs;
+ this->AppendTargetDependsClosure(target, outs, true);
+
outputs.insert(outputs.end(), outs.begin(), outs.end());
}
-void cmGlobalNinjaGenerator::ComputeTargetDependsClosure(
- cmGeneratorTarget const* target, std::set<cmGeneratorTarget const*>& depends)
+void cmGlobalNinjaGenerator::AppendTargetDependsClosure(
+ cmGeneratorTarget const* target, cmNinjaOuts& outputs, bool omit_self)
{
- cmTargetDependSet const& targetDeps = this->GetTargetDirectDepends(target);
- for (cmTargetDependSet::const_iterator i = targetDeps.begin();
- i != targetDeps.end(); ++i) {
- if ((*i)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
- continue;
- }
- if (depends.insert(*i).second) {
- this->ComputeTargetDependsClosure(*i, depends);
+
+ // try to locate the target in the cache
+ auto find = this->TargetDependsClosures.lower_bound(target);
+
+ if (find == this->TargetDependsClosures.end() || find->first != target) {
+ // We now calculate the closure outputs by inspecting the dependent
+ // targets recursively.
+ // For that we have to distinguish between a local result set that is only
+ // relevant for filling the cache entries properly isolated and a global
+ // result set that is relevant for the result of the top level call to
+ // AppendTargetDependsClosure.
+ auto const& targetDeps = this->GetTargetDirectDepends(target);
+ cmNinjaOuts this_outs; // this will be the new cache entry
+
+ for (auto const& dep_target : targetDeps) {
+ if (dep_target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+ continue;
+ }
+
+ // Collect the dependent targets for _this_ target
+ this->AppendTargetDependsClosure(dep_target, this_outs, false);
}
+ find = this->TargetDependsClosures.emplace_hint(find, target,
+ std::move(this_outs));
}
+
+ // now fill the outputs of the final result from the newly generated cache
+ // entry
+ outputs.insert(find->second.begin(), find->second.end());
+
+ // finally generate the outputs of the target itself, if applicable
+ cmNinjaDeps outs;
+ if (!omit_self) {
+ this->AppendTargetOutputs(target, outs);
+ }
+ outputs.insert(outs.begin(), outs.end());
}
void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
@@ -1091,8 +1098,8 @@ void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
this->AppendTargetOutputs(target, outputs);
// Mark the target's outputs as ambiguous to ensure that no other target uses
// the output as an alias.
- for (cmNinjaDeps::iterator i = outputs.begin(); i != outputs.end(); ++i) {
- TargetAliases[*i] = CM_NULLPTR;
+ for (std::string const& output : outputs) {
+ TargetAliases[output] = nullptr;
}
// Insert the alias into the map. If the alias was already present in the
@@ -1100,7 +1107,7 @@ void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
std::pair<TargetAliasMap::iterator, bool> newAlias =
TargetAliases.insert(std::make_pair(buildAlias, target));
if (newAlias.second && newAlias.first->second != target) {
- newAlias.first->second = CM_NULLPTR;
+ newAlias.first->second = nullptr;
}
}
@@ -1109,17 +1116,16 @@ void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os)
cmGlobalNinjaGenerator::WriteDivider(os);
os << "# Target aliases.\n\n";
- for (TargetAliasMap::const_iterator i = TargetAliases.begin();
- i != TargetAliases.end(); ++i) {
+ for (auto const& ta : TargetAliases) {
// Don't write ambiguous aliases.
- if (!i->second) {
+ if (!ta.second) {
continue;
}
cmNinjaDeps deps;
- this->AppendTargetOutputs(i->second, deps);
+ this->AppendTargetOutputs(ta.second, deps);
- this->WritePhonyBuild(os, "", cmNinjaDeps(1, i->first), deps);
+ this->WritePhonyBuild(os, "", cmNinjaDeps(1, ta.first), deps);
}
}
@@ -1129,19 +1135,13 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os)
os << "# Folder targets.\n\n";
std::map<std::string, cmNinjaDeps> targetsPerFolder;
- for (std::vector<cmLocalGenerator*>::const_iterator lgi =
- this->LocalGenerators.begin();
- lgi != this->LocalGenerators.end(); ++lgi) {
- cmLocalGenerator const* lg = *lgi;
+ for (cmLocalGenerator const* lg : this->LocalGenerators) {
const std::string currentBinaryFolder(
lg->GetStateSnapshot().GetDirectory().GetCurrentBinary());
// The directory-level rule should depend on the target-level rules
// for all targets in the directory.
targetsPerFolder[currentBinaryFolder] = cmNinjaDeps();
- for (std::vector<cmGeneratorTarget*>::const_iterator ti =
- lg->GetGeneratorTargets().begin();
- ti != lg->GetGeneratorTargets().end(); ++ti) {
- cmGeneratorTarget const* gt = *ti;
+ for (auto gt : lg->GetGeneratorTargets()) {
cmStateEnums::TargetType const type = gt->GetType();
if ((type == cmStateEnums::EXECUTABLE ||
type == cmStateEnums::STATIC_LIBRARY ||
@@ -1158,11 +1158,9 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os)
// rules of the subdirectories.
std::vector<cmStateSnapshot> const& children =
lg->GetStateSnapshot().GetChildren();
- for (std::vector<cmStateSnapshot>::const_iterator stateIt =
- children.begin();
- stateIt != children.end(); ++stateIt) {
+ for (cmStateSnapshot const& state : children) {
std::string const currentBinaryDir =
- stateIt->GetDirectory().GetCurrentBinary();
+ state.GetDirectory().GetCurrentBinary();
targetsPerFolder[currentBinaryFolder].push_back(
this->ConvertToNinjaPath(currentBinaryDir + "/all"));
@@ -1171,11 +1169,9 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os)
std::string const rootBinaryDir =
this->LocalGenerators[0]->GetBinaryDirectory();
- for (std::map<std::string, cmNinjaDeps>::const_iterator it =
- targetsPerFolder.begin();
- it != targetsPerFolder.end(); ++it) {
+ for (auto const& it : targetsPerFolder) {
cmGlobalNinjaGenerator::WriteDivider(os);
- std::string const& currentBinaryDir = it->first;
+ std::string const& currentBinaryDir = it.first;
// Do not generate a rule for the root binary dir.
if (rootBinaryDir.length() >= currentBinaryDir.length()) {
@@ -1186,7 +1182,7 @@ void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os)
cmNinjaDeps output(1);
output.push_back(this->ConvertToNinjaPath(currentBinaryDir + "/all"));
- this->WritePhonyBuild(os, comment, output, it->second);
+ this->WritePhonyBuild(os, comment, output, it.second);
}
}
@@ -1220,50 +1216,40 @@ void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os)
// get the list of files that cmake itself has generated as a
// product of configuration.
- for (std::vector<cmLocalGenerator*>::const_iterator i =
- this->LocalGenerators.begin();
- i != this->LocalGenerators.end(); ++i) {
+ for (cmLocalGenerator* lg : this->LocalGenerators) {
// get the vector of files created by this makefile and convert them
// to ninja paths, which are all relative in respect to the build directory
const std::vector<std::string>& files =
- (*i)->GetMakefile()->GetOutputFiles();
- typedef std::vector<std::string>::const_iterator vect_it;
- for (vect_it j = files.begin(); j != files.end(); ++j) {
- knownDependencies.insert(this->ConvertToNinjaPath(*j));
+ lg->GetMakefile()->GetOutputFiles();
+ for (std::string const& file : files) {
+ knownDependencies.insert(this->ConvertToNinjaPath(file));
}
// get list files which are implicit dependencies as well and will be phony
// for rebuild manifest
- std::vector<std::string> const& lf = (*i)->GetMakefile()->GetListFiles();
- typedef std::vector<std::string>::const_iterator vect_it;
- for (vect_it j = lf.begin(); j != lf.end(); ++j) {
- knownDependencies.insert(this->ConvertToNinjaPath(*j));
+ std::vector<std::string> const& lf = lg->GetMakefile()->GetListFiles();
+ for (std::string const& j : lf) {
+ knownDependencies.insert(this->ConvertToNinjaPath(j));
}
std::vector<cmGeneratorExpressionEvaluationFile*> const& ef =
- (*i)->GetMakefile()->GetEvaluationFiles();
- for (std::vector<cmGeneratorExpressionEvaluationFile*>::const_iterator li =
- ef.begin();
- li != ef.end(); ++li) {
+ lg->GetMakefile()->GetEvaluationFiles();
+ for (cmGeneratorExpressionEvaluationFile* li : ef) {
// get all the files created by generator expressions and convert them
// to ninja paths
- std::vector<std::string> evaluationFiles = (*li)->GetFiles();
- for (vect_it j = evaluationFiles.begin(); j != evaluationFiles.end();
- ++j) {
- knownDependencies.insert(this->ConvertToNinjaPath(*j));
+ std::vector<std::string> evaluationFiles = li->GetFiles();
+ for (std::string const& evaluationFile : evaluationFiles) {
+ knownDependencies.insert(this->ConvertToNinjaPath(evaluationFile));
}
}
}
knownDependencies.insert(this->CMakeCacheFile);
- for (TargetAliasMap::const_iterator i = this->TargetAliases.begin();
- i != this->TargetAliases.end(); ++i) {
- knownDependencies.insert(this->ConvertToNinjaPath(i->first));
+ for (auto const& ta : this->TargetAliases) {
+ knownDependencies.insert(this->ConvertToNinjaPath(ta.first));
}
// remove all source files we know will exist.
- typedef std::map<std::string, std::set<std::string> >::const_iterator map_it;
- for (map_it i = this->AssumedSourceDependencies.begin();
- i != this->AssumedSourceDependencies.end(); ++i) {
- knownDependencies.insert(this->ConvertToNinjaPath(i->first));
+ for (auto const& i : this->AssumedSourceDependencies) {
+ knownDependencies.insert(this->ConvertToNinjaPath(i.first));
}
// now we difference with CombinedCustomCommandExplicitDependencies to find
@@ -1285,20 +1271,18 @@ void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os)
bool const inSourceBuild =
(rootBuildDirectory == this->GetCMakeInstance()->GetHomeDirectory());
std::vector<std::string> warnExplicitDepends;
- for (std::vector<std::string>::const_iterator i =
- unknownExplicitDepends.begin();
- i != unknownExplicitDepends.end(); ++i) {
+ for (std::string const& i : unknownExplicitDepends) {
// verify the file is in the build directory
std::string const absDepPath =
- cmSystemTools::CollapseFullPath(*i, rootBuildDirectory.c_str());
+ cmSystemTools::CollapseFullPath(i, rootBuildDirectory.c_str());
bool const inBuildDir =
cmSystemTools::IsSubDirectory(absDepPath, rootBuildDirectory);
if (inBuildDir) {
- cmNinjaDeps deps(1, *i);
+ cmNinjaDeps deps(1, i);
this->WritePhonyBuild(os, "", deps, cmNinjaDeps());
if (this->PolicyCMP0058 == cmPolicies::WARN && !inSourceBuild &&
warnExplicitDepends.size() < 10) {
- warnExplicitDepends.push_back(*i);
+ warnExplicitDepends.push_back(i);
}
}
}
@@ -1373,13 +1357,11 @@ void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os)
/*generator=*/true);
cmNinjaDeps implicitDeps;
- for (std::vector<cmLocalGenerator*>::const_iterator i =
- this->LocalGenerators.begin();
- i != this->LocalGenerators.end(); ++i) {
- std::vector<std::string> const& lf = (*i)->GetMakefile()->GetListFiles();
- for (std::vector<std::string>::const_iterator fi = lf.begin();
- fi != lf.end(); ++fi) {
- implicitDeps.push_back(this->ConvertToNinjaPath(*fi));
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ std::vector<std::string> const& lf =
+ localGen->GetMakefile()->GetListFiles();
+ for (std::string const& fi : lf) {
+ implicitDeps.push_back(this->ConvertToNinjaPath(fi));
}
}
implicitDeps.push_back(this->CMakeCacheFile);
@@ -1636,9 +1618,8 @@ int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
Json::Value const& tdi_include_dirs = tdi["include-dirs"];
if (tdi_include_dirs.isArray()) {
- for (Json::Value::const_iterator i = tdi_include_dirs.begin();
- i != tdi_include_dirs.end(); ++i) {
- includes.push_back(i->asString());
+ for (auto const& tdi_include_dir : tdi_include_dirs) {
+ includes.push_back(tdi_include_dir.asString());
}
}
}
@@ -1659,9 +1640,8 @@ int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
{
cmGeneratedFileStream depfile(arg_dep.c_str());
depfile << cmSystemTools::ConvertToUnixOutputPath(arg_pp) << ":";
- for (std::set<std::string>::iterator i = info.Includes.begin();
- i != info.Includes.end(); ++i) {
- depfile << " \\\n " << cmSystemTools::ConvertToUnixOutputPath(*i);
+ for (std::string const& include : info.Includes) {
+ depfile << " \\\n " << cmSystemTools::ConvertToUnixOutputPath(include);
}
depfile << "\n";
}
@@ -1670,16 +1650,14 @@ int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
ddi["object"] = arg_obj;
Json::Value& ddi_provides = ddi["provides"] = Json::arrayValue;
- for (std::set<std::string>::iterator i = info.Provides.begin();
- i != info.Provides.end(); ++i) {
- ddi_provides.append(*i);
+ for (std::string const& provide : info.Provides) {
+ ddi_provides.append(provide);
}
Json::Value& ddi_requires = ddi["requires"] = Json::arrayValue;
- for (std::set<std::string>::iterator i = info.Requires.begin();
- i != info.Requires.end(); ++i) {
+ for (std::string const& r : info.Requires) {
// Require modules not provided in the same source.
- if (!info.Provides.count(*i)) {
- ddi_requires.append(*i);
+ if (!info.Provides.count(r)) {
+ ddi_requires.append(r);
}
}
@@ -1714,24 +1692,24 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile(
snapshot.GetDirectory().SetCurrentBinary(dir_cur_bld);
snapshot.GetDirectory().SetRelativePathTopSource(dir_top_src.c_str());
snapshot.GetDirectory().SetRelativePathTopBinary(dir_top_bld.c_str());
- CM_AUTO_PTR<cmMakefile> mfd(new cmMakefile(this, snapshot));
- CM_AUTO_PTR<cmLocalNinjaGenerator> lgd(static_cast<cmLocalNinjaGenerator*>(
- this->CreateLocalGenerator(mfd.get())));
+ auto mfd = cm::make_unique<cmMakefile>(this, snapshot);
+ std::unique_ptr<cmLocalNinjaGenerator> lgd(
+ static_cast<cmLocalNinjaGenerator*>(
+ this->CreateLocalGenerator(mfd.get())));
this->Makefiles.push_back(mfd.release());
this->LocalGenerators.push_back(lgd.release());
}
std::vector<cmFortranObjectInfo> objects;
- for (std::vector<std::string>::const_iterator ddii = arg_ddis.begin();
- ddii != arg_ddis.end(); ++ddii) {
+ for (std::string const& arg_ddi : arg_ddis) {
// Load the ddi file and compute the module file paths it provides.
Json::Value ddio;
Json::Value const& ddi = ddio;
- cmsys::ifstream ddif(ddii->c_str(), std::ios::in | std::ios::binary);
+ cmsys::ifstream ddif(arg_ddi.c_str(), std::ios::in | std::ios::binary);
Json::Reader reader;
if (!reader.parse(ddif, ddio, false)) {
cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ",
- ddii->c_str(),
+ arg_ddi.c_str(),
reader.getFormattedErrorMessages().c_str());
return false;
}
@@ -1740,16 +1718,14 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile(
info.Object = ddi["object"].asString();
Json::Value const& ddi_provides = ddi["provides"];
if (ddi_provides.isArray()) {
- for (Json::Value::const_iterator i = ddi_provides.begin();
- i != ddi_provides.end(); ++i) {
- info.Provides.push_back(i->asString());
+ for (auto const& ddi_provide : ddi_provides) {
+ info.Provides.push_back(ddi_provide.asString());
}
}
Json::Value const& ddi_requires = ddi["requires"];
if (ddi_requires.isArray()) {
- for (Json::Value::const_iterator i = ddi_requires.begin();
- i != ddi_requires.end(); ++i) {
- info.Requires.push_back(i->asString());
+ for (auto const& ddi_require : ddi_requires) {
+ info.Requires.push_back(ddi_require.asString());
}
}
objects.push_back(info);
@@ -1759,16 +1735,14 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile(
std::map<std::string, std::string> mod_files;
// Populate the module map with those provided by linked targets first.
- for (std::vector<std::string>::const_iterator di =
- linked_target_dirs.begin();
- di != linked_target_dirs.end(); ++di) {
- std::string const ltmn = *di + "/FortranModules.json";
+ for (std::string const& linked_target_dir : linked_target_dirs) {
+ std::string const ltmn = linked_target_dir + "/FortranModules.json";
Json::Value ltm;
cmsys::ifstream ltmf(ltmn.c_str(), std::ios::in | std::ios::binary);
Json::Reader reader;
if (ltmf && !reader.parse(ltmf, ltm, false)) {
cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ",
- di->c_str(),
+ linked_target_dir.c_str(),
reader.getFormattedErrorMessages().c_str());
return false;
}
@@ -1783,21 +1757,18 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile(
// We do this after loading the modules provided by linked targets
// in case we have one of the same name that must be preferred.
Json::Value tm = Json::objectValue;
- for (std::vector<cmFortranObjectInfo>::iterator oi = objects.begin();
- oi != objects.end(); ++oi) {
- for (std::vector<std::string>::iterator i = oi->Provides.begin();
- i != oi->Provides.end(); ++i) {
- std::string const mod = module_dir + *i + ".mod";
- mod_files[*i] = mod;
- tm[*i] = mod;
+ for (cmFortranObjectInfo const& object : objects) {
+ for (std::string const& p : object.Provides) {
+ std::string const mod = module_dir + p + ".mod";
+ mod_files[p] = mod;
+ tm[p] = mod;
}
}
cmGeneratedFileStream ddf(arg_dd.c_str());
ddf << "ninja_dyndep_version = 1.0\n";
- for (std::vector<cmFortranObjectInfo>::iterator oi = objects.begin();
- oi != objects.end(); ++oi) {
+ for (cmFortranObjectInfo const& object : objects) {
std::string const ddComment;
std::string const ddRule = "dyndep";
cmNinjaDeps ddOutputs;
@@ -1807,19 +1778,17 @@ bool cmGlobalNinjaGenerator::WriteDyndepFile(
cmNinjaDeps ddOrderOnlyDeps;
cmNinjaVars ddVars;
- ddOutputs.push_back(oi->Object);
- for (std::vector<std::string>::iterator i = oi->Provides.begin();
- i != oi->Provides.end(); ++i) {
- ddImplicitOuts.push_back(this->ConvertToNinjaPath(mod_files[*i]));
+ ddOutputs.push_back(object.Object);
+ for (std::string const& p : object.Provides) {
+ ddImplicitOuts.push_back(this->ConvertToNinjaPath(mod_files[p]));
}
- for (std::vector<std::string>::iterator i = oi->Requires.begin();
- i != oi->Requires.end(); ++i) {
- std::map<std::string, std::string>::iterator m = mod_files.find(*i);
+ for (std::string const& r : object.Requires) {
+ std::map<std::string, std::string>::iterator m = mod_files.find(r);
if (m != mod_files.end()) {
ddImplicitDeps.push_back(this->ConvertToNinjaPath(m->second));
}
}
- if (!oi->Provides.empty()) {
+ if (!object.Provides.empty()) {
ddVars["restat"] = "1";
}
@@ -1846,9 +1815,7 @@ int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
std::string arg_dd;
std::string arg_tdi;
std::vector<std::string> arg_ddis;
- for (std::vector<std::string>::const_iterator a = arg_full.begin();
- a != arg_full.end(); ++a) {
- std::string const& arg = *a;
+ for (std::string const& arg : arg_full) {
if (cmHasLiteralPrefix(arg, "--tdi=")) {
arg_tdi = arg.substr(6);
} else if (cmHasLiteralPrefix(arg, "--dd=")) {
@@ -1895,16 +1862,15 @@ int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
std::vector<std::string> linked_target_dirs;
Json::Value const& tdi_linked_target_dirs = tdi["linked-target-dirs"];
if (tdi_linked_target_dirs.isArray()) {
- for (Json::Value::const_iterator i = tdi_linked_target_dirs.begin();
- i != tdi_linked_target_dirs.end(); ++i) {
- linked_target_dirs.push_back(i->asString());
+ for (auto const& tdi_linked_target_dir : tdi_linked_target_dirs) {
+ linked_target_dirs.push_back(tdi_linked_target_dir.asString());
}
}
cmake cm(cmake::RoleInternal);
cm.SetHomeDirectory(dir_top_src);
cm.SetHomeOutputDirectory(dir_top_bld);
- CM_AUTO_PTR<cmGlobalNinjaGenerator> ggd(
+ std::unique_ptr<cmGlobalNinjaGenerator> ggd(
static_cast<cmGlobalNinjaGenerator*>(cm.CreateGlobalGenerator("Ninja")));
if (!ggd.get() ||
!ggd->WriteDyndepFile(dir_top_src, dir_top_bld, dir_cur_src, dir_cur_bld,
diff --git a/Source/cmGlobalNinjaGenerator.h b/Source/cmGlobalNinjaGenerator.h
index b0008f74a..7f80d0806 100644
--- a/Source/cmGlobalNinjaGenerator.h
+++ b/Source/cmGlobalNinjaGenerator.h
@@ -3,12 +3,13 @@
#ifndef cmGlobalNinjaGenerator_h
#define cmGlobalNinjaGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <map>
#include <set>
#include <string>
+#include <unordered_map>
#include <utility>
#include <vector>
@@ -78,7 +79,7 @@ public:
cmLinkLineComputer* CreateLinkLineComputer(
cmOutputConverter* outputConverter,
- cmStateDirectory const& stateDir) const CM_OVERRIDE;
+ cmStateDirectory const& stateDir) const override;
/**
* Write the given @a comment to the output stream @a os. It
@@ -98,7 +99,7 @@ public:
*/
static bool SupportsPlatform() { return false; }
- bool IsIPOSupported() const CM_OVERRIDE { return true; }
+ bool IsIPOSupported() const override { return true; }
/**
* Write a build statement to @a os with the @a comment using
@@ -114,7 +115,7 @@ public:
const cmNinjaDeps& orderOnlyDeps,
const cmNinjaVars& variables,
const std::string& rspfile = std::string(),
- int cmdLineLimit = 0, bool* usedResponseFile = CM_NULLPTR);
+ int cmdLineLimit = 0, bool* usedResponseFile = nullptr);
/**
* Helper to write a build statement with the special 'phony' rule.
@@ -183,11 +184,11 @@ public:
return new cmGlobalGeneratorSimpleFactory<cmGlobalNinjaGenerator>();
}
- ~cmGlobalNinjaGenerator() CM_OVERRIDE {}
+ ~cmGlobalNinjaGenerator() override {}
- cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) CM_OVERRIDE;
+ cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) override;
- std::string GetName() const CM_OVERRIDE
+ std::string GetName() const override
{
return cmGlobalNinjaGenerator::GetActualName();
}
@@ -195,12 +196,12 @@ public:
static std::string GetActualName() { return "Ninja"; }
/** Get encoding used by generator for ninja files */
- codecvt::Encoding GetMakefileEncoding() const CM_OVERRIDE;
+ codecvt::Encoding GetMakefileEncoding() const override;
static void GetDocumentation(cmDocumentationEntry& entry);
void EnableLanguage(std::vector<std::string> const& languages,
- cmMakefile* mf, bool optional) CM_OVERRIDE;
+ cmMakefile* mf, bool optional) override;
void GenerateBuildCommand(std::vector<std::string>& makeCommand,
const std::string& makeProgram,
@@ -209,34 +210,31 @@ public:
const std::string& targetName,
const std::string& config, bool fast, bool verbose,
std::vector<std::string> const& makeOptions =
- std::vector<std::string>()) CM_OVERRIDE;
+ std::vector<std::string>()) override;
// Setup target names
- const char* GetAllTargetName() const CM_OVERRIDE { return "all"; }
- const char* GetInstallTargetName() const CM_OVERRIDE { return "install"; }
- const char* GetInstallLocalTargetName() const CM_OVERRIDE
+ const char* GetAllTargetName() const override { return "all"; }
+ const char* GetInstallTargetName() const override { return "install"; }
+ const char* GetInstallLocalTargetName() const override
{
return "install/local";
}
- const char* GetInstallStripTargetName() const CM_OVERRIDE
+ const char* GetInstallStripTargetName() const override
{
return "install/strip";
}
- const char* GetTestTargetName() const CM_OVERRIDE { return "test"; }
- const char* GetPackageTargetName() const CM_OVERRIDE { return "package"; }
- const char* GetPackageSourceTargetName() const CM_OVERRIDE
+ const char* GetTestTargetName() const override { return "test"; }
+ const char* GetPackageTargetName() const override { return "package"; }
+ const char* GetPackageSourceTargetName() const override
{
return "package_source";
}
- const char* GetEditCacheTargetName() const CM_OVERRIDE
- {
- return "edit_cache";
- }
- const char* GetRebuildCacheTargetName() const CM_OVERRIDE
+ const char* GetEditCacheTargetName() const override { return "edit_cache"; }
+ const char* GetRebuildCacheTargetName() const override
{
return "rebuild_cache";
}
- const char* GetCleanTargetName() const CM_OVERRIDE { return "clean"; }
+ const char* GetCleanTargetName() const override { return "clean"; }
cmGeneratedFileStream* GetBuildFileStream() const
{
@@ -248,7 +246,7 @@ public:
return this->RulesFileStream;
}
- std::string ConvertToNinjaPath(const std::string& path) const;
+ std::string const& ConvertToNinjaPath(const std::string& path) const;
struct MapToNinjaPathImpl
{
@@ -323,6 +321,8 @@ public:
cmNinjaTargetDepends depends = DependOnTargetArtifact);
void AppendTargetDependsClosure(cmGeneratorTarget const* target,
cmNinjaDeps& outputs);
+ void AppendTargetDependsClosure(cmGeneratorTarget const* target,
+ cmNinjaOuts& outputs, bool omit_self);
void AddDependencyToAll(cmGeneratorTarget* target);
void AddDependencyToAll(const std::string& input);
@@ -340,7 +340,7 @@ public:
void AddTargetAlias(const std::string& alias, cmGeneratorTarget* target);
- void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const CM_OVERRIDE;
+ void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const override;
// Ninja generator uses 'deps' and 'msvc_deps_prefix' introduced in 1.3
static std::string RequiredNinjaVersion() { return "1.3"; }
@@ -363,16 +363,16 @@ public:
std::vector<std::string> const& linked_target_dirs);
protected:
- void Generate() CM_OVERRIDE;
+ void Generate() override;
- bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const CM_OVERRIDE { return true; }
+ bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const override { return true; }
private:
- std::string GetEditCacheCommand() const CM_OVERRIDE;
- bool FindMakeProgram(cmMakefile* mf) CM_OVERRIDE;
+ std::string GetEditCacheCommand() const override;
+ bool FindMakeProgram(cmMakefile* mf) override;
void CheckNinjaFeatures();
bool CheckLanguages(std::vector<std::string> const& languages,
- cmMakefile* mf) const CM_OVERRIDE;
+ cmMakefile* mf) const override;
bool CheckFortran(cmMakefile* mf) const;
void OpenBuildFileStream();
@@ -446,15 +446,15 @@ private:
std::set<std::string> CombinedBuildOutputs;
/// The mapping from source file to assumed dependencies.
- std::map<std::string, std::set<std::string> > AssumedSourceDependencies;
+ std::map<std::string, std::set<std::string>> AssumedSourceDependencies;
typedef std::map<std::string, cmGeneratorTarget*> TargetAliasMap;
TargetAliasMap TargetAliases;
- typedef std::map<cmGeneratorTarget const*,
- std::set<cmGeneratorTarget const*> >
- TargetDependsClosureMap;
- TargetDependsClosureMap TargetDependsClosures;
+ std::map<cmGeneratorTarget const*, cmNinjaOuts> TargetDependsClosures;
+
+ /// the local cache for calls to ConvertToNinjaPath
+ mutable std::unordered_map<std::string, std::string> ConvertToNinjaPathCache;
std::string NinjaCommand;
std::string NinjaVersion;
diff --git a/Source/cmGlobalUnixMakefileGenerator3.cxx b/Source/cmGlobalUnixMakefileGenerator3.cxx
index 23b3718dc..be4012680 100644
--- a/Source/cmGlobalUnixMakefileGenerator3.cxx
+++ b/Source/cmGlobalUnixMakefileGenerator3.cxx
@@ -38,7 +38,7 @@ cmGlobalUnixMakefileGenerator3::cmGlobalUnixMakefileGenerator3(cmake* cm)
#else
this->UseLinkScript = true;
#endif
- this->CommandDatabase = CM_NULLPTR;
+ this->CommandDatabase = nullptr;
this->IncludeDirective = "include";
this->DefineWindowsNULL = false;
@@ -50,12 +50,11 @@ void cmGlobalUnixMakefileGenerator3::EnableLanguage(
std::vector<std::string> const& languages, cmMakefile* mf, bool optional)
{
this->cmGlobalGenerator::EnableLanguage(languages, mf, optional);
- for (std::vector<std::string>::const_iterator l = languages.begin();
- l != languages.end(); ++l) {
- if (*l == "NONE") {
+ for (std::string const& language : languages) {
+ if (language == "NONE") {
continue;
}
- this->ResolveLanguageCompiler(*l, mf, optional);
+ this->ResolveLanguageCompiler(language, mf, optional);
}
}
@@ -130,9 +129,8 @@ void cmGlobalUnixMakefileGenerator3::Generate()
// initialize progress
unsigned long total = 0;
- for (ProgressMapType::const_iterator pmi = this->ProgressMap.begin();
- pmi != this->ProgressMap.end(); ++pmi) {
- total += pmi->second.NumberOfActions;
+ for (auto const& pmi : this->ProgressMap) {
+ total += pmi.second.NumberOfActions;
}
// write each target's progress.make this loop is done twice. Bascially the
@@ -143,12 +141,10 @@ void cmGlobalUnixMakefileGenerator3::Generate()
// well. This is because the all targets require more information that is
// computed in the first loop.
unsigned long current = 0;
- for (ProgressMapType::iterator pmi = this->ProgressMap.begin();
- pmi != this->ProgressMap.end(); ++pmi) {
- pmi->second.WriteProgressVariables(total, current);
+ for (auto& pmi : this->ProgressMap) {
+ pmi.second.WriteProgressVariables(total, current);
}
- for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
- cmLocalGenerator* lg = this->LocalGenerators[i];
+ for (cmLocalGenerator* lg : this->LocalGenerators) {
std::string markFileName = lg->GetCurrentBinaryDirectory();
markFileName += "/";
markFileName += cmake::GetCMakeFilesDirectory();
@@ -161,10 +157,10 @@ void cmGlobalUnixMakefileGenerator3::Generate()
this->WriteMainMakefile2();
this->WriteMainCMakefile();
- if (this->CommandDatabase != CM_NULLPTR) {
+ if (this->CommandDatabase != nullptr) {
*this->CommandDatabase << std::endl << "]";
delete this->CommandDatabase;
- this->CommandDatabase = CM_NULLPTR;
+ this->CommandDatabase = nullptr;
}
}
@@ -172,7 +168,7 @@ void cmGlobalUnixMakefileGenerator3::AddCXXCompileCommand(
const std::string& sourceFile, const std::string& workingDirectory,
const std::string& compileCommand)
{
- if (this->CommandDatabase == CM_NULLPTR) {
+ if (this->CommandDatabase == nullptr) {
std::string commandDatabaseName =
std::string(this->GetCMakeInstance()->GetHomeOutputDirectory()) +
"/compile_commands.json";
@@ -234,7 +230,7 @@ void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2()
// The all and preinstall rules might never have any dependencies
// added to them.
- if (this->EmptyRuleHackDepends != "") {
+ if (!this->EmptyRuleHackDepends.empty()) {
depends.push_back(this->EmptyRuleHackDepends);
}
@@ -250,9 +246,8 @@ void cmGlobalUnixMakefileGenerator3::WriteMainMakefile2()
lg->WriteSpecialTargetsTop(makefileStream);
// write the target convenience rules
- unsigned int i;
- for (i = 0; i < this->LocalGenerators.size(); ++i) {
- lg = static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[i]);
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ lg = static_cast<cmLocalUnixMakefileGenerator3*>(localGen);
this->WriteConvenienceRules2(makefileStream, lg);
}
@@ -292,8 +287,8 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile()
// for each cmMakefile get its list of dependencies
std::vector<std::string> lfiles;
- for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
- lg = static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[i]);
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ lg = static_cast<cmLocalUnixMakefileGenerator3*>(localGen);
// Get the list of files contributing to this generation step.
lfiles.insert(lfiles.end(), lg->GetMakefile()->GetListFiles().begin(),
@@ -316,9 +311,8 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile()
<< "# The top level Makefile was generated from the following files:\n"
<< "set(CMAKE_MAKEFILE_DEPENDS\n"
<< " \"CMakeCache.txt\"\n";
- for (std::vector<std::string>::const_iterator i = lfiles.begin();
- i != lfiles.end(); ++i) {
- cmakefileStream << " \"" << lg->ConvertToRelativePath(currentBinDir, *i)
+ for (std::string const& f : lfiles) {
+ cmakefileStream << " \"" << lg->ConvertToRelativePath(currentBinDir, f)
<< "\"\n";
}
cmakefileStream << " )\n\n";
@@ -346,17 +340,15 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefile()
<< "set(CMAKE_MAKEFILE_PRODUCTS\n";
const std::vector<std::string>& outfiles =
lg->GetMakefile()->GetOutputFiles();
- for (std::vector<std::string>::const_iterator k = outfiles.begin();
- k != outfiles.end(); ++k) {
- cmakefileStream << " \"" << lg->ConvertToRelativePath(binDir, *k)
+ for (std::string const& outfile : outfiles) {
+ cmakefileStream << " \"" << lg->ConvertToRelativePath(binDir, outfile)
<< "\"\n";
}
// add in all the directory information files
std::string tmpStr;
- for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
- lg =
- static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[i]);
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ lg = static_cast<cmLocalUnixMakefileGenerator3*>(localGen);
tmpStr = lg->GetCurrentBinaryDirectory();
tmpStr += cmake::GetCMakeFilesDirectory();
tmpStr += "/CMakeDirectoryInformation.cmake";
@@ -379,19 +371,18 @@ void cmGlobalUnixMakefileGenerator3::WriteMainCMakefileLanguageRules(
// now list all the target info files
cmakefileStream << "# Dependency information for all targets:\n";
cmakefileStream << "set(CMAKE_DEPEND_INFO_FILES\n";
- for (unsigned int i = 0; i < lGenerators.size(); ++i) {
- lg = static_cast<cmLocalUnixMakefileGenerator3*>(lGenerators[i]);
+ for (cmLocalGenerator* lGenerator : lGenerators) {
+ lg = static_cast<cmLocalUnixMakefileGenerator3*>(lGenerator);
// for all of out targets
- std::vector<cmGeneratorTarget*> tgts = lg->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
- l != tgts.end(); l++) {
- if (((*l)->GetType() == cmStateEnums::EXECUTABLE) ||
- ((*l)->GetType() == cmStateEnums::STATIC_LIBRARY) ||
- ((*l)->GetType() == cmStateEnums::SHARED_LIBRARY) ||
- ((*l)->GetType() == cmStateEnums::MODULE_LIBRARY) ||
- ((*l)->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
- ((*l)->GetType() == cmStateEnums::UTILITY)) {
- cmGeneratorTarget* gt = *l;
+ const std::vector<cmGeneratorTarget*>& tgts = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* tgt : tgts) {
+ if ((tgt->GetType() == cmStateEnums::EXECUTABLE) ||
+ (tgt->GetType() == cmStateEnums::STATIC_LIBRARY) ||
+ (tgt->GetType() == cmStateEnums::SHARED_LIBRARY) ||
+ (tgt->GetType() == cmStateEnums::MODULE_LIBRARY) ||
+ (tgt->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
+ (tgt->GetType() == cmStateEnums::UTILITY)) {
+ cmGeneratorTarget* gt = tgt;
std::string tname = lg->GetRelativeTargetDirectory(gt);
tname += "/DependInfo.cmake";
cmSystemTools::ConvertToUnixSlashes(tname);
@@ -414,10 +405,8 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2(
// The directory-level rule should depend on the target-level rules
// for all targets in the directory.
std::vector<std::string> depends;
- std::vector<cmGeneratorTarget*> targets = lg->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator l = targets.begin();
- l != targets.end(); ++l) {
- cmGeneratorTarget* gtarget = *l;
+ const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* gtarget : targets) {
int type = gtarget->GetType();
if ((type == cmStateEnums::EXECUTABLE) ||
(type == cmStateEnums::STATIC_LIBRARY) ||
@@ -440,9 +429,8 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2(
// The directory-level rule should depend on the directory-level
// rules of the subdirectories.
std::vector<cmStateSnapshot> children = lg->GetStateSnapshot().GetChildren();
- for (std::vector<cmStateSnapshot>::const_iterator ci = children.begin();
- ci != children.end(); ++ci) {
- std::string subdir = ci->GetDirectory().GetCurrentBinary();
+ for (cmStateSnapshot const& c : children) {
+ std::string subdir = c.GetDirectory().GetCurrentBinary();
subdir += "/";
subdir += pass;
depends.push_back(subdir);
@@ -450,7 +438,7 @@ void cmGlobalUnixMakefileGenerator3::WriteDirectoryRule2(
// Work-around for makes that drop rules that have no dependencies
// or commands.
- if (depends.empty() && this->EmptyRuleHackDepends != "") {
+ if (depends.empty() && !this->EmptyRuleHackDepends.empty()) {
depends.push_back(this->EmptyRuleHackDepends);
}
@@ -542,15 +530,12 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules(
depends.push_back("cmake_check_build_system");
// write the target convenience rules
- unsigned int i;
- cmLocalUnixMakefileGenerator3* lg;
- for (i = 0; i < this->LocalGenerators.size(); ++i) {
- lg = static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[i]);
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ cmLocalUnixMakefileGenerator3* lg =
+ static_cast<cmLocalUnixMakefileGenerator3*>(localGen);
// for each target Generate the rule files for each target.
- std::vector<cmGeneratorTarget*> targets = lg->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
- t != targets.end(); ++t) {
- cmGeneratorTarget* gtarget = *t;
+ const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* gtarget : targets) {
// Don't emit the same rule twice (e.g. two targets with the same
// simple name)
int type = gtarget->GetType();
@@ -629,10 +614,8 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2(
depends.push_back("cmake_check_build_system");
// for each target Generate the rule files for each target.
- std::vector<cmGeneratorTarget*> targets = lg->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
- t != targets.end(); ++t) {
- cmGeneratorTarget* gtarget = *t;
+ const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* gtarget : targets) {
int type = gtarget->GetType();
std::string name = gtarget->GetName();
if (!name.empty() && ((type == cmStateEnums::EXECUTABLE) ||
@@ -680,11 +663,10 @@ void cmGlobalUnixMakefileGenerator3::WriteConvenienceRules2(
{
std::ostringstream progressArg;
const char* sep = "";
- std::vector<unsigned long>& progFiles =
+ std::vector<unsigned long> const& progFiles =
this->ProgressMap[gtarget].Marks;
- for (std::vector<unsigned long>::iterator i = progFiles.begin();
- i != progFiles.end(); ++i) {
- progressArg << sep << *i;
+ for (unsigned long progFile : progFiles) {
+ progressArg << sep << progFile;
sep = ",";
}
progress.Arg = progressArg.str();
@@ -803,15 +785,9 @@ void cmGlobalUnixMakefileGenerator3::InitializeProgressMarks()
{
this->DirectoryTargetsMap.clear();
// Loop over all targets in all local generators.
- for (std::vector<cmLocalGenerator*>::const_iterator lgi =
- this->LocalGenerators.begin();
- lgi != this->LocalGenerators.end(); ++lgi) {
- cmLocalGenerator* lg = *lgi;
- std::vector<cmGeneratorTarget*> targets = lg->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::const_iterator t = targets.begin();
- t != targets.end(); ++t) {
- cmGeneratorTarget* gt = *t;
-
+ for (cmLocalGenerator* lg : this->LocalGenerators) {
+ const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* gt : targets) {
cmLocalGenerator* tlg = gt->GetLocalGenerator();
if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
@@ -835,9 +811,8 @@ void cmGlobalUnixMakefileGenerator3::InitializeProgressMarks()
// target may still be included if it is a dependency of a
// non-excluded target.
TargetDependSet const& tgtdeps = this->GetTargetDirectDepends(gt);
- for (TargetDependSet::const_iterator ti = tgtdeps.begin();
- ti != tgtdeps.end(); ++ti) {
- targetSet.insert(*ti);
+ for (cmTargetDepend const& tgtdep : tgtdeps) {
+ targetSet.insert(tgtdep);
}
}
}
@@ -851,12 +826,11 @@ size_t cmGlobalUnixMakefileGenerator3::CountProgressMarksInTarget(
if (emitted.insert(target).second) {
count = this->ProgressMap[target].Marks.size();
TargetDependSet const& depends = this->GetTargetDirectDepends(target);
- for (TargetDependSet::const_iterator di = depends.begin();
- di != depends.end(); ++di) {
- if ((*di)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+ for (cmTargetDepend const& depend : depends) {
+ if (depend->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
- count += this->CountProgressMarksInTarget(*di, emitted);
+ count += this->CountProgressMarksInTarget(depend, emitted);
}
}
return count;
@@ -869,9 +843,8 @@ size_t cmGlobalUnixMakefileGenerator3::CountProgressMarksInAll(
std::set<cmGeneratorTarget const*> emitted;
std::set<cmGeneratorTarget const*> const& targets =
this->DirectoryTargetsMap[lg->GetStateSnapshot()];
- for (std::set<cmGeneratorTarget const*>::const_iterator t = targets.begin();
- t != targets.end(); ++t) {
- count += this->CountProgressMarksInTarget(*t, emitted);
+ for (cmGeneratorTarget const* target : targets) {
+ count += this->CountProgressMarksInTarget(target, emitted);
}
return count;
}
@@ -910,10 +883,9 @@ void cmGlobalUnixMakefileGenerator3::AppendGlobalTargetDepends(
std::vector<std::string>& depends, cmGeneratorTarget* target)
{
TargetDependSet const& depends_set = this->GetTargetDirectDepends(target);
- for (TargetDependSet::const_iterator i = depends_set.begin();
- i != depends_set.end(); ++i) {
+ for (cmTargetDepend const& i : depends_set) {
// Create the target-level dependency.
- cmGeneratorTarget const* dep = *i;
+ cmGeneratorTarget const* dep = i;
if (dep->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
@@ -943,19 +915,16 @@ void cmGlobalUnixMakefileGenerator3::WriteHelpRule(
std::set<std::string> emittedTargets;
// for each local generator
- unsigned int i;
- cmLocalUnixMakefileGenerator3* lg2;
- for (i = 0; i < this->LocalGenerators.size(); ++i) {
- lg2 =
- static_cast<cmLocalUnixMakefileGenerator3*>(this->LocalGenerators[i]);
+ for (cmLocalGenerator* localGen : this->LocalGenerators) {
+ cmLocalUnixMakefileGenerator3* lg2 =
+ static_cast<cmLocalUnixMakefileGenerator3*>(localGen);
// for the passed in makefile or if this is the top Makefile wripte out
// the targets
if (lg2 == lg || lg->IsRootMakefile()) {
// for each target Generate the rule files for each target.
- std::vector<cmGeneratorTarget*> targets = lg2->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
- t != targets.end(); ++t) {
- cmGeneratorTarget* target = *t;
+ const std::vector<cmGeneratorTarget*>& targets =
+ lg2->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
cmStateEnums::TargetType type = target->GetType();
if ((type == cmStateEnums::EXECUTABLE) ||
(type == cmStateEnums::STATIC_LIBRARY) ||
@@ -974,11 +943,9 @@ void cmGlobalUnixMakefileGenerator3::WriteHelpRule(
}
}
}
- std::vector<std::string> const& localHelp = lg->GetLocalHelp();
- for (std::vector<std::string>::const_iterator o = localHelp.begin();
- o != localHelp.end(); ++o) {
+ for (std::string const& o : lg->GetLocalHelp()) {
path = "... ";
- path += *o;
+ path += o;
lg->AppendEcho(commands, path);
}
lg->WriteMakeRule(ruleFileStream, "Help Target", "help", no_depends,
@@ -993,10 +960,9 @@ bool cmGlobalUnixMakefileGenerator3::NeedRequiresStep(
target->GetLanguages(
languages,
target->Target->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE"));
- for (std::set<std::string>::const_iterator l = languages.begin();
- l != languages.end(); ++l) {
+ for (std::string const& l : languages) {
std::string var = "CMAKE_NEEDS_REQUIRES_STEP_";
- var += *l;
+ var += l;
var += "_FLAG";
if (target->Target->GetMakefile()->GetDefinition(var)) {
return true;
diff --git a/Source/cmGlobalUnixMakefileGenerator3.h b/Source/cmGlobalUnixMakefileGenerator3.h
index a656102fb..d601f8845 100644
--- a/Source/cmGlobalUnixMakefileGenerator3.h
+++ b/Source/cmGlobalUnixMakefileGenerator3.h
@@ -3,7 +3,7 @@
#ifndef cmGlobalUnixMakefileGenerator3_h
#define cmGlobalUnixMakefileGenerator3_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <map>
@@ -68,7 +68,7 @@ public:
}
///! Get the name for the generator.
- std::string GetName() const CM_OVERRIDE
+ std::string GetName() const override
{
return cmGlobalUnixMakefileGenerator3::GetActualName();
}
@@ -89,23 +89,23 @@ public:
/** Get the documentation entry for this generator. */
static void GetDocumentation(cmDocumentationEntry& entry);
- cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) CM_OVERRIDE;
+ cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) override;
/**
* Try to determine system information such as shared library
* extension, pthreads, byte order etc.
*/
void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*,
- bool optional) CM_OVERRIDE;
+ bool optional) override;
- void Configure() CM_OVERRIDE;
+ void Configure() override;
/**
* Generate the all required files for building this project/tree. This
* basically creates a series of LocalGenerators for each directory and
* requests that they Generate.
*/
- void Generate() CM_OVERRIDE;
+ void Generate() override;
void WriteMainCMakefileLanguageRules(cmGeneratedFileStream& cmakefileStream,
std::vector<cmLocalGenerator*>&);
@@ -134,7 +134,7 @@ public:
const std::string& targetName,
const std::string& config, bool fast, bool verbose,
std::vector<std::string> const& makeOptions =
- std::vector<std::string>()) CM_OVERRIDE;
+ std::vector<std::string>()) override;
/** Record per-target progress information. */
void RecordTargetProgress(cmMakefileTargetGenerator* tg);
@@ -149,9 +149,9 @@ public:
/** Does the make tool tolerate .DELETE_ON_ERROR? */
virtual bool AllowDeleteOnError() const { return true; }
- bool IsIPOSupported() const CM_OVERRIDE { return true; }
+ bool IsIPOSupported() const override { return true; }
- void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const CM_OVERRIDE;
+ void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const override;
std::string IncludeDirective;
bool DefineWindowsNULL;
@@ -178,37 +178,31 @@ protected:
bool NeedRequiresStep(cmGeneratorTarget const*);
// Target name hooks for superclass.
- const char* GetAllTargetName() const CM_OVERRIDE { return "all"; }
- const char* GetInstallTargetName() const CM_OVERRIDE { return "install"; }
- const char* GetInstallLocalTargetName() const CM_OVERRIDE
+ const char* GetAllTargetName() const override { return "all"; }
+ const char* GetInstallTargetName() const override { return "install"; }
+ const char* GetInstallLocalTargetName() const override
{
return "install/local";
}
- const char* GetInstallStripTargetName() const CM_OVERRIDE
+ const char* GetInstallStripTargetName() const override
{
return "install/strip";
}
- const char* GetPreinstallTargetName() const CM_OVERRIDE
- {
- return "preinstall";
- }
- const char* GetTestTargetName() const CM_OVERRIDE { return "test"; }
- const char* GetPackageTargetName() const CM_OVERRIDE { return "package"; }
- const char* GetPackageSourceTargetName() const CM_OVERRIDE
+ const char* GetPreinstallTargetName() const override { return "preinstall"; }
+ const char* GetTestTargetName() const override { return "test"; }
+ const char* GetPackageTargetName() const override { return "package"; }
+ const char* GetPackageSourceTargetName() const override
{
return "package_source";
}
- const char* GetEditCacheTargetName() const CM_OVERRIDE
- {
- return "edit_cache";
- }
- const char* GetRebuildCacheTargetName() const CM_OVERRIDE
+ const char* GetEditCacheTargetName() const override { return "edit_cache"; }
+ const char* GetRebuildCacheTargetName() const override
{
return "rebuild_cache";
}
- const char* GetCleanTargetName() const CM_OVERRIDE { return "clean"; }
+ const char* GetCleanTargetName() const override { return "clean"; }
- bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const CM_OVERRIDE { return true; }
+ bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const override { return true; }
// Some make programs (Borland) do not keep a rule if there are no
// dependencies or commands. This is a problem for creating rules
@@ -247,13 +241,13 @@ protected:
cmGeneratedFileStream* CommandDatabase;
private:
- const char* GetBuildIgnoreErrorsFlag() const CM_OVERRIDE { return "-i"; }
- std::string GetEditCacheCommand() const CM_OVERRIDE;
+ const char* GetBuildIgnoreErrorsFlag() const override { return "-i"; }
+ std::string GetEditCacheCommand() const override;
std::map<cmStateSnapshot, std::set<cmGeneratorTarget const*>,
cmStateSnapshot::StrictWeakOrder>
DirectoryTargetsMap;
- void InitializeProgressMarks() CM_OVERRIDE;
+ void InitializeProgressMarks() override;
};
#endif
diff --git a/Source/cmGlobalVisualStudio10Generator.cxx b/Source/cmGlobalVisualStudio10Generator.cxx
index 4fff11a9f..8c9e4616e 100644
--- a/Source/cmGlobalVisualStudio10Generator.cxx
+++ b/Source/cmGlobalVisualStudio10Generator.cxx
@@ -51,7 +51,7 @@ class cmGlobalVisualStudio10Generator::Factory
{
public:
cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
- cmake* cm) const CM_OVERRIDE
+ cmake* cm) const override
{
std::string genName;
const char* p = cmVS10GenName(name, genName);
@@ -73,22 +73,22 @@ public:
return 0;
}
- void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
+ void GetDocumentation(cmDocumentationEntry& entry) const override
{
entry.Name = std::string(vs10generatorName) + " [arch]";
entry.Brief = "Generates Visual Studio 2010 project files. "
"Optional [arch] can be \"Win64\" or \"IA64\".";
}
- void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
+ void GetGenerators(std::vector<std::string>& names) const override
{
names.push_back(vs10generatorName);
names.push_back(vs10generatorName + std::string(" IA64"));
names.push_back(vs10generatorName + std::string(" Win64"));
}
- bool SupportsToolset() const CM_OVERRIDE { return true; }
- bool SupportsPlatform() const CM_OVERRIDE { return true; }
+ bool SupportsToolset() const override { return true; }
+ bool SupportsPlatform() const override { return true; }
};
cmGlobalGeneratorFactory* cmGlobalVisualStudio10Generator::NewFactory()
@@ -407,14 +407,14 @@ bool cmGlobalVisualStudio10Generator::InitializeWindowsStore(cmMakefile* mf)
bool cmGlobalVisualStudio10Generator::SelectWindowsPhoneToolset(
std::string& toolset) const
{
- toolset = "";
+ toolset.clear();
return false;
}
bool cmGlobalVisualStudio10Generator::SelectWindowsStoreToolset(
std::string& toolset) const
{
- toolset = "";
+ toolset.clear();
return false;
}
@@ -495,7 +495,7 @@ const char* cmGlobalVisualStudio10Generator::GetPlatformToolset() const
{
std::string const& toolset = this->GetPlatformToolsetString();
if (toolset.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
return toolset.c_str();
}
@@ -519,7 +519,7 @@ cmGlobalVisualStudio10Generator::GetPlatformToolsetHostArchitecture() const
if (!this->GeneratorToolsetHostArchitecture.empty()) {
return this->GeneratorToolsetHostArchitecture.c_str();
}
- return CM_NULLPTR;
+ return nullptr;
}
const char* cmGlobalVisualStudio10Generator::GetPlatformToolsetCuda() const
@@ -527,7 +527,7 @@ const char* cmGlobalVisualStudio10Generator::GetPlatformToolsetCuda() const
if (!this->GeneratorToolsetCuda.empty()) {
return this->GeneratorToolsetCuda.c_str();
}
- return CM_NULLPTR;
+ return nullptr;
}
std::string const&
@@ -695,7 +695,12 @@ bool cmGlobalVisualStudio10Generator::FindVCTargetsPath(cmMakefile* mf)
xw.Content(this->WindowsTargetPlatformVersion);
xw.EndElement(); // WindowsTargetPlatformVersion
}
- if (this->GetPlatformName() == "ARM") {
+ if (this->GetPlatformName() == "ARM64") {
+ xw.StartElement("WindowsSDKDesktopARM64Support");
+ xw.Content("true");
+ xw.EndElement(); // WindowsSDK64DesktopARMSupport
+ }
+ else if (this->GetPlatformName() == "ARM") {
xw.StartElement("WindowsSDKDesktopARMSupport");
xw.Content("true");
xw.EndElement(); // WindowsSDKDesktopARMSupport
@@ -971,7 +976,7 @@ cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetClFlagTable() const
cmIDEFlagTable const* table = this->ToolsetOptions.GetClFlagTable(
this->GetPlatformName(), this->GetPlatformToolsetString());
- return (table != CM_NULLPTR) ? table : this->DefaultClFlagTable;
+ return (table != nullptr) ? table : this->DefaultClFlagTable;
}
cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetCSharpFlagTable()
@@ -980,7 +985,7 @@ cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetCSharpFlagTable()
cmIDEFlagTable const* table = this->ToolsetOptions.GetCSharpFlagTable(
this->GetPlatformName(), this->GetPlatformToolsetString());
- return (table != CM_NULLPTR) ? table : this->DefaultCSharpFlagTable;
+ return (table != nullptr) ? table : this->DefaultCSharpFlagTable;
}
cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetRcFlagTable() const
@@ -988,7 +993,7 @@ cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetRcFlagTable() const
cmIDEFlagTable const* table = this->ToolsetOptions.GetRcFlagTable(
this->GetPlatformName(), this->GetPlatformToolsetString());
- return (table != CM_NULLPTR) ? table : this->DefaultRcFlagTable;
+ return (table != nullptr) ? table : this->DefaultRcFlagTable;
}
cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetLibFlagTable() const
@@ -996,7 +1001,7 @@ cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetLibFlagTable() const
cmIDEFlagTable const* table = this->ToolsetOptions.GetLibFlagTable(
this->GetPlatformName(), this->GetPlatformToolsetString());
- return (table != CM_NULLPTR) ? table : this->DefaultLibFlagTable;
+ return (table != nullptr) ? table : this->DefaultLibFlagTable;
}
cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetLinkFlagTable() const
@@ -1004,7 +1009,7 @@ cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetLinkFlagTable() const
cmIDEFlagTable const* table = this->ToolsetOptions.GetLinkFlagTable(
this->GetPlatformName(), this->GetPlatformToolsetString());
- return (table != CM_NULLPTR) ? table : this->DefaultLinkFlagTable;
+ return (table != nullptr) ? table : this->DefaultLinkFlagTable;
}
cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetCudaFlagTable() const
@@ -1023,7 +1028,7 @@ cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetMasmFlagTable() const
cmIDEFlagTable const* table = this->ToolsetOptions.GetMasmFlagTable(
this->GetPlatformName(), this->GetPlatformToolsetString());
- return (table != CM_NULLPTR) ? table : this->DefaultMasmFlagTable;
+ return (table != nullptr) ? table : this->DefaultMasmFlagTable;
}
cmIDEFlagTable const* cmGlobalVisualStudio10Generator::GetNasmFlagTable() const
diff --git a/Source/cmGlobalVisualStudio10Generator.h b/Source/cmGlobalVisualStudio10Generator.h
index 4a5c2454b..5f80c7342 100644
--- a/Source/cmGlobalVisualStudio10Generator.h
+++ b/Source/cmGlobalVisualStudio10Generator.h
@@ -98,7 +98,7 @@ public:
virtual const char* GetToolsVersion() { return "4.0"; }
- bool FindMakeProgram(cmMakefile* mf) CM_OVERRIDE;
+ bool FindMakeProgram(cmMakefile* mf) override;
static std::string GetInstalledNsightTegraVersion();
diff --git a/Source/cmGlobalVisualStudio11Generator.cxx b/Source/cmGlobalVisualStudio11Generator.cxx
index d37d4b095..cb3b0477f 100644
--- a/Source/cmGlobalVisualStudio11Generator.cxx
+++ b/Source/cmGlobalVisualStudio11Generator.cxx
@@ -35,7 +35,7 @@ class cmGlobalVisualStudio11Generator::Factory
{
public:
cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
- cmake* cm) const CM_OVERRIDE
+ cmake* cm) const override
{
std::string genName;
const char* p = cmVS11GenName(name, genName);
@@ -68,14 +68,14 @@ public:
return ret;
}
- void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
+ void GetDocumentation(cmDocumentationEntry& entry) const override
{
entry.Name = std::string(vs11generatorName) + " [arch]";
entry.Brief = "Generates Visual Studio 2012 project files. "
"Optional [arch] can be \"Win64\" or \"ARM\".";
}
- void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
+ void GetGenerators(std::vector<std::string>& names) const override
{
names.push_back(vs11generatorName);
names.push_back(vs11generatorName + std::string(" ARM"));
@@ -89,8 +89,8 @@ public:
}
}
- bool SupportsToolset() const CM_OVERRIDE { return true; }
- bool SupportsPlatform() const CM_OVERRIDE { return true; }
+ bool SupportsToolset() const override { return true; }
+ bool SupportsPlatform() const override { return true; }
};
cmGlobalGeneratorFactory* cmGlobalVisualStudio11Generator::NewFactory()
diff --git a/Source/cmGlobalVisualStudio11Generator.h b/Source/cmGlobalVisualStudio11Generator.h
index b4b327d8a..8b75aadbf 100644
--- a/Source/cmGlobalVisualStudio11Generator.h
+++ b/Source/cmGlobalVisualStudio11Generator.h
@@ -3,7 +3,7 @@
#ifndef cmGlobalVisualStudio11Generator_h
#define cmGlobalVisualStudio11Generator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <set>
diff --git a/Source/cmGlobalVisualStudio12Generator.cxx b/Source/cmGlobalVisualStudio12Generator.cxx
index de62ff0ac..a9c605cad 100644
--- a/Source/cmGlobalVisualStudio12Generator.cxx
+++ b/Source/cmGlobalVisualStudio12Generator.cxx
@@ -35,7 +35,7 @@ class cmGlobalVisualStudio12Generator::Factory
{
public:
cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
- cmake* cm) const CM_OVERRIDE
+ cmake* cm) const override
{
std::string genName;
const char* p = cmVS12GenName(name, genName);
@@ -57,22 +57,22 @@ public:
return 0;
}
- void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
+ void GetDocumentation(cmDocumentationEntry& entry) const override
{
entry.Name = std::string(vs12generatorName) + " [arch]";
entry.Brief = "Generates Visual Studio 2013 project files. "
"Optional [arch] can be \"Win64\" or \"ARM\".";
}
- void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
+ void GetGenerators(std::vector<std::string>& names) const override
{
names.push_back(vs12generatorName);
names.push_back(vs12generatorName + std::string(" ARM"));
names.push_back(vs12generatorName + std::string(" Win64"));
}
- bool SupportsToolset() const CM_OVERRIDE { return true; }
- bool SupportsPlatform() const CM_OVERRIDE { return true; }
+ bool SupportsToolset() const override { return true; }
+ bool SupportsPlatform() const override { return true; }
};
cmGlobalGeneratorFactory* cmGlobalVisualStudio12Generator::NewFactory()
diff --git a/Source/cmGlobalVisualStudio12Generator.h b/Source/cmGlobalVisualStudio12Generator.h
index ebc95bb63..5ba21a662 100644
--- a/Source/cmGlobalVisualStudio12Generator.h
+++ b/Source/cmGlobalVisualStudio12Generator.h
@@ -3,7 +3,7 @@
#ifndef cmGlobalVisualStudio12Generator_h
#define cmGlobalVisualStudio12Generator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <string>
@@ -32,7 +32,7 @@ public:
virtual const char* GetToolsVersion() { return "12.0"; }
protected:
bool ProcessGeneratorToolsetField(std::string const& key,
- std::string const& value) CM_OVERRIDE;
+ std::string const& value) override;
virtual bool InitializeWindowsPhone(cmMakefile* mf);
virtual bool InitializeWindowsStore(cmMakefile* mf);
diff --git a/Source/cmGlobalVisualStudio14Generator.cxx b/Source/cmGlobalVisualStudio14Generator.cxx
index c8cf02cdd..97d531378 100644
--- a/Source/cmGlobalVisualStudio14Generator.cxx
+++ b/Source/cmGlobalVisualStudio14Generator.cxx
@@ -35,7 +35,7 @@ class cmGlobalVisualStudio14Generator::Factory
{
public:
cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
- cmake* cm) const CM_OVERRIDE
+ cmake* cm) const override
{
std::string genName;
const char* p = cmVS14GenName(name, genName);
@@ -57,22 +57,22 @@ public:
return 0;
}
- void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
+ void GetDocumentation(cmDocumentationEntry& entry) const override
{
entry.Name = std::string(vs14generatorName) + " [arch]";
entry.Brief = "Generates Visual Studio 2015 project files. "
"Optional [arch] can be \"Win64\" or \"ARM\".";
}
- void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
+ void GetGenerators(std::vector<std::string>& names) const override
{
names.push_back(vs14generatorName);
names.push_back(vs14generatorName + std::string(" ARM"));
names.push_back(vs14generatorName + std::string(" Win64"));
}
- bool SupportsToolset() const CM_OVERRIDE { return true; }
- bool SupportsPlatform() const CM_OVERRIDE { return true; }
+ bool SupportsToolset() const override { return true; }
+ bool SupportsPlatform() const override { return true; }
};
cmGlobalGeneratorFactory* cmGlobalVisualStudio14Generator::NewFactory()
@@ -151,6 +151,13 @@ bool cmGlobalVisualStudio14Generator::SelectWindows10SDK(cmMakefile* mf,
mf->IssueMessage(cmake::FATAL_ERROR, e.str());
return false;
}
+ if (!cmSystemTools::VersionCompareEqual(this->WindowsTargetPlatformVersion,
+ this->SystemVersion)) {
+ std::ostringstream e;
+ e << "Selecting Windows SDK version " << this->WindowsTargetPlatformVersion
+ << " to target Windows " << this->SystemVersion << ".";
+ mf->DisplayStatus(e.str().c_str(), -1);
+ }
mf->AddDefinition("CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION",
this->WindowsTargetPlatformVersion.c_str());
return true;
diff --git a/Source/cmGlobalVisualStudio14Generator.h b/Source/cmGlobalVisualStudio14Generator.h
index 0ce9a5641..425fb227f 100644
--- a/Source/cmGlobalVisualStudio14Generator.h
+++ b/Source/cmGlobalVisualStudio14Generator.h
@@ -3,7 +3,7 @@
#ifndef cmGlobalVisualStudio14Generator_h
#define cmGlobalVisualStudio14Generator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <string>
diff --git a/Source/cmGlobalVisualStudio15Generator.cxx b/Source/cmGlobalVisualStudio15Generator.cxx
index ce1ba007f..d2bf7cca6 100644
--- a/Source/cmGlobalVisualStudio15Generator.cxx
+++ b/Source/cmGlobalVisualStudio15Generator.cxx
@@ -69,8 +69,8 @@ public:
names.push_back(vs15generatorName + std::string(" Win64"));
}
- bool SupportsToolset() const CM_OVERRIDE { return true; }
- bool SupportsPlatform() const CM_OVERRIDE { return true; }
+ bool SupportsToolset() const override { return true; }
+ bool SupportsPlatform() const override { return true; }
};
cmGlobalGeneratorFactory* cmGlobalVisualStudio15Generator::NewFactory()
diff --git a/Source/cmGlobalVisualStudio15Generator.h b/Source/cmGlobalVisualStudio15Generator.h
index 4be88f44f..e93488243 100644
--- a/Source/cmGlobalVisualStudio15Generator.h
+++ b/Source/cmGlobalVisualStudio15Generator.h
@@ -3,7 +3,7 @@
#ifndef cmGlobalVisualStudio15Generator_h
#define cmGlobalVisualStudio15Generator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <string>
@@ -28,7 +28,7 @@ public:
virtual const char* GetToolsVersion() { return "15.0"; }
protected:
- bool InitializeWindows(cmMakefile* mf) CM_OVERRIDE;
+ bool InitializeWindows(cmMakefile* mf) override;
virtual bool SelectWindowsStoreToolset(std::string& toolset) const;
virtual const char* GetIDEVersion() { return "15.0"; }
@@ -44,8 +44,8 @@ protected:
// Check for a Win 8 SDK known to the registry or VS installer tool.
bool IsWin81SDKInstalled() const;
- std::string FindMSBuildCommand() CM_OVERRIDE;
- std::string FindDevEnvCommand() CM_OVERRIDE;
+ std::string FindMSBuildCommand() override;
+ std::string FindDevEnvCommand() override;
private:
class Factory;
diff --git a/Source/cmGlobalVisualStudio7Generator.cxx b/Source/cmGlobalVisualStudio7Generator.cxx
index b155f5b55..a14b5f753 100644
--- a/Source/cmGlobalVisualStudio7Generator.cxx
+++ b/Source/cmGlobalVisualStudio7Generator.cxx
@@ -334,7 +334,7 @@ void cmGlobalVisualStudio7Generator::OutputSLNFile(
// output the SLN file
void cmGlobalVisualStudio7Generator::OutputSLNFile()
{
- std::map<std::string, std::vector<cmLocalGenerator*> >::iterator it;
+ std::map<std::string, std::vector<cmLocalGenerator*>>::iterator it;
for (it = this->ProjectMap.begin(); it != this->ProjectMap.end(); ++it) {
this->OutputSLNFile(it->second[0], it->second);
}
@@ -403,7 +403,7 @@ void cmGlobalVisualStudio7Generator::WriteTargetsToSolution(
std::string dir = lg->GetCurrentBinaryDirectory();
dir = root->ConvertToRelativePath(rootBinaryDir, dir.c_str());
if (dir == ".") {
- dir = ""; // msbuild cannot handle ".\" prefix
+ dir.clear(); // msbuild cannot handle ".\" prefix
}
this->WriteProject(fout, vcprojName, dir.c_str(), target);
written = true;
@@ -418,7 +418,7 @@ void cmGlobalVisualStudio7Generator::WriteTargetsToSolution(
std::vector<cmsys::String> tokens =
cmSystemTools::SplitString(targetFolder, '/', false);
- std::string cumulativePath = "";
+ std::string cumulativePath;
for (std::vector<cmsys::String>::iterator iter = tokens.begin();
iter != tokens.end(); ++iter) {
@@ -467,7 +467,7 @@ void cmGlobalVisualStudio7Generator::WriteFolders(std::ostream& fout)
const char* prefix = "CMAKE_FOLDER_GUID_";
const std::string::size_type skip_prefix = strlen(prefix);
std::string guidProjectTypeFolder = "2150E333-8FDC-42A3-9474-1A3956D46DE8";
- for (std::map<std::string, std::set<std::string> >::iterator iter =
+ for (std::map<std::string, std::set<std::string>>::iterator iter =
VisualStudioFolders.begin();
iter != VisualStudioFolders.end(); ++iter) {
std::string fullName = iter->first;
@@ -487,7 +487,7 @@ void cmGlobalVisualStudio7Generator::WriteFolders(std::ostream& fout)
void cmGlobalVisualStudio7Generator::WriteFoldersContent(std::ostream& fout)
{
- for (std::map<std::string, std::set<std::string> >::iterator iter =
+ for (std::map<std::string, std::set<std::string>>::iterator iter =
VisualStudioFolders.begin();
iter != VisualStudioFolders.end(); ++iter) {
std::string key(iter->first);
@@ -708,7 +708,7 @@ std::set<std::string> cmGlobalVisualStudio7Generator::IsPartOfDefaultBuild(
const char* propertyValue =
target->Target->GetMakefile()->GetDefinition(propertyName);
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
+ std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(propertyValue);
if (cmSystemTools::IsOn(
cge->Evaluate(target->GetLocalGenerator(), *i))) {
diff --git a/Source/cmGlobalVisualStudio7Generator.h b/Source/cmGlobalVisualStudio7Generator.h
index 32a8d6056..c5aced44f 100644
--- a/Source/cmGlobalVisualStudio7Generator.h
+++ b/Source/cmGlobalVisualStudio7Generator.h
@@ -91,7 +91,7 @@ public:
const char* GetIntelProjectVersion();
- bool FindMakeProgram(cmMakefile* mf) CM_OVERRIDE;
+ bool FindMakeProgram(cmMakefile* mf) override;
/** Is the Microsoft Assembler enabled? */
bool IsMasmEnabled() const { return this->MasmEnabled; }
@@ -156,7 +156,7 @@ protected:
virtual void WriteFolders(std::ostream& fout);
virtual void WriteFoldersContent(std::ostream& fout);
- std::map<std::string, std::set<std::string> > VisualStudioFolders;
+ std::map<std::string, std::set<std::string>> VisualStudioFolders;
// Set during OutputSLNFile with the name of the current project.
// There is one SLN file per project.
diff --git a/Source/cmGlobalVisualStudio8Generator.cxx b/Source/cmGlobalVisualStudio8Generator.cxx
index f06a8a1c6..cc1d1a27b 100644
--- a/Source/cmGlobalVisualStudio8Generator.cxx
+++ b/Source/cmGlobalVisualStudio8Generator.cxx
@@ -17,7 +17,7 @@ class cmGlobalVisualStudio8Generator::Factory : public cmGlobalGeneratorFactory
{
public:
cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
- cmake* cm) const CM_OVERRIDE
+ cmake* cm) const override
{
if (strncmp(name.c_str(), vs8generatorName,
sizeof(vs8generatorName) - 1) != 0) {
@@ -51,14 +51,14 @@ public:
return ret;
}
- void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
+ void GetDocumentation(cmDocumentationEntry& entry) const override
{
entry.Name = std::string(vs8generatorName) + " [arch]";
entry.Brief = "Deprecated. Generates Visual Studio 2005 project files. "
"Optional [arch] can be \"Win64\".";
}
- void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
+ void GetGenerators(std::vector<std::string>& names) const override
{
names.push_back(vs8generatorName);
names.push_back(vs8generatorName + std::string(" Win64"));
@@ -73,8 +73,8 @@ public:
}
}
- bool SupportsToolset() const CM_OVERRIDE { return false; }
- bool SupportsPlatform() const CM_OVERRIDE { return true; }
+ bool SupportsToolset() const override { return false; }
+ bool SupportsPlatform() const override { return true; }
};
cmGlobalGeneratorFactory* cmGlobalVisualStudio8Generator::NewFactory()
@@ -301,7 +301,7 @@ bool cmGlobalVisualStudio8Generator::AddCheckTarget()
// file as the main dependency because it would get
// overwritten by the CreateVCProjBuildRule.
// (this could be avoided with per-target source files)
- std::string no_main_dependency = "";
+ std::string no_main_dependency;
std::vector<std::string> no_byproducts;
if (cmSourceFile* file = mf->AddCustomCommandToOutput(
stamps, no_byproducts, listFiles, no_main_dependency, commandLines,
@@ -320,10 +320,10 @@ void cmGlobalVisualStudio8Generator::AddExtraIDETargets()
cmGlobalVisualStudio7Generator::AddExtraIDETargets();
if (this->AddCheckTarget()) {
for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
- std::vector<cmGeneratorTarget*> tgts =
+ const std::vector<cmGeneratorTarget*>& tgts =
this->LocalGenerators[i]->GetGeneratorTargets();
// All targets depend on the build-system check target.
- for (std::vector<cmGeneratorTarget*>::iterator ti = tgts.begin();
+ for (std::vector<cmGeneratorTarget*>::const_iterator ti = tgts.begin();
ti != tgts.end(); ++ti) {
if ((*ti)->GetName() != CMAKE_CHECK_BUILD_SYSTEM_TARGET) {
(*ti)->Target->AddUtility(CMAKE_CHECK_BUILD_SYSTEM_TARGET);
diff --git a/Source/cmGlobalVisualStudio9Generator.cxx b/Source/cmGlobalVisualStudio9Generator.cxx
index b1634e2ca..0abb3488e 100644
--- a/Source/cmGlobalVisualStudio9Generator.cxx
+++ b/Source/cmGlobalVisualStudio9Generator.cxx
@@ -14,7 +14,7 @@ class cmGlobalVisualStudio9Generator::Factory : public cmGlobalGeneratorFactory
{
public:
cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
- cmake* cm) const CM_OVERRIDE
+ cmake* cm) const override
{
if (strncmp(name.c_str(), vs9generatorName,
sizeof(vs9generatorName) - 1) != 0) {
@@ -52,14 +52,14 @@ public:
return ret;
}
- void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
+ void GetDocumentation(cmDocumentationEntry& entry) const override
{
entry.Name = std::string(vs9generatorName) + " [arch]";
entry.Brief = "Generates Visual Studio 2008 project files. "
"Optional [arch] can be \"Win64\" or \"IA64\".";
}
- void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
+ void GetGenerators(std::vector<std::string>& names) const override
{
names.push_back(vs9generatorName);
names.push_back(vs9generatorName + std::string(" Win64"));
@@ -75,8 +75,8 @@ public:
}
}
- bool SupportsToolset() const CM_OVERRIDE { return false; }
- bool SupportsPlatform() const CM_OVERRIDE { return true; }
+ bool SupportsToolset() const override { return false; }
+ bool SupportsPlatform() const override { return true; }
};
cmGlobalGeneratorFactory* cmGlobalVisualStudio9Generator::NewFactory()
diff --git a/Source/cmGlobalVisualStudioGenerator.cxx b/Source/cmGlobalVisualStudioGenerator.cxx
index bbff48eb6..0651536a9 100644
--- a/Source/cmGlobalVisualStudioGenerator.cxx
+++ b/Source/cmGlobalVisualStudioGenerator.cxx
@@ -58,7 +58,7 @@ void cmGlobalVisualStudioGenerator::AddExtraIDETargets()
const char* no_working_dir = 0;
std::vector<std::string> no_depends;
cmCustomCommandLines no_commands;
- std::map<std::string, std::vector<cmLocalGenerator*> >::iterator it;
+ std::map<std::string, std::vector<cmLocalGenerator*>>::iterator it;
for (it = this->ProjectMap.begin(); it != this->ProjectMap.end(); ++it) {
std::vector<cmLocalGenerator*>& gen = it->second;
// add the ALL_BUILD to the first local generator of each project
@@ -82,8 +82,10 @@ void cmGlobalVisualStudioGenerator::AddExtraIDETargets()
// Now make all targets depend on the ALL_BUILD target
for (std::vector<cmLocalGenerator*>::iterator i = gen.begin();
i != gen.end(); ++i) {
- std::vector<cmGeneratorTarget*> targets = (*i)->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
+ const std::vector<cmGeneratorTarget*>& targets =
+ (*i)->GetGeneratorTargets();
+ for (std::vector<cmGeneratorTarget*>::const_iterator t =
+ targets.begin();
t != targets.end(); ++t) {
cmGeneratorTarget* tgt = *t;
if (tgt->GetType() == cmStateEnums::GLOBAL_TARGET ||
@@ -148,7 +150,7 @@ void cmGlobalVisualStudioGenerator::ConfigureCMakeVisualStudioMacros()
{
std::string dir = this->GetUserMacrosDirectory();
- if (dir != "") {
+ if (!dir.empty()) {
std::string src = cmSystemTools::GetCMakeRoot();
src += "/Templates/" CMAKE_VSMACROS_FILENAME;
@@ -188,7 +190,7 @@ void cmGlobalVisualStudioGenerator::CallVisualStudioMacro(
// - the CMake vsmacros file is registered
// - there were .sln/.vcproj files changed during generation
//
- if (dir != "") {
+ if (!dir.empty()) {
std::string macrosFile = dir + "/CMakeMacros/" CMAKE_VSMACROS_FILENAME;
std::string nextSubkeyName;
if (cmSystemTools::FileExists(macrosFile.c_str()) &&
@@ -293,13 +295,15 @@ bool cmGlobalVisualStudioGenerator::ComputeTargetDepends()
if (!this->cmGlobalGenerator::ComputeTargetDepends()) {
return false;
}
- std::map<std::string, std::vector<cmLocalGenerator*> >::iterator it;
+ std::map<std::string, std::vector<cmLocalGenerator*>>::iterator it;
for (it = this->ProjectMap.begin(); it != this->ProjectMap.end(); ++it) {
std::vector<cmLocalGenerator*>& gen = it->second;
for (std::vector<cmLocalGenerator*>::iterator i = gen.begin();
i != gen.end(); ++i) {
- std::vector<cmGeneratorTarget*> targets = (*i)->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator ti = targets.begin();
+ const std::vector<cmGeneratorTarget*>& targets =
+ (*i)->GetGeneratorTargets();
+ for (std::vector<cmGeneratorTarget*>::const_iterator ti =
+ targets.begin();
ti != targets.end(); ++ti) {
this->ComputeVSTargetDepends(*ti);
}
diff --git a/Source/cmGlobalVisualStudioGenerator.h b/Source/cmGlobalVisualStudioGenerator.h
index 3c43ccdd2..62bfd3bdb 100644
--- a/Source/cmGlobalVisualStudioGenerator.h
+++ b/Source/cmGlobalVisualStudioGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmGlobalVisualStudioGenerator_h
#define cmGlobalVisualStudioGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <map>
@@ -118,7 +118,7 @@ public:
};
class OrderedTargetDependSet;
- bool FindMakeProgram(cmMakefile*) CM_OVERRIDE;
+ bool FindMakeProgram(cmMakefile*) override;
virtual std::string ExpandCFGIntDir(const std::string& str,
const std::string& config) const;
diff --git a/Source/cmGlobalWatcomWMakeGenerator.h b/Source/cmGlobalWatcomWMakeGenerator.h
index b2d6d5d71..e8b3a73c9 100644
--- a/Source/cmGlobalWatcomWMakeGenerator.h
+++ b/Source/cmGlobalWatcomWMakeGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmGlobalWatcomWMakeGenerator_h
#define cmGlobalWatcomWMakeGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmGlobalGeneratorFactory.h"
#include "cmGlobalUnixMakefileGenerator3.h"
@@ -29,7 +29,7 @@ public:
return new cmGlobalGeneratorSimpleFactory<cmGlobalWatcomWMakeGenerator>();
}
///! Get the name for the generator.
- std::string GetName() const CM_OVERRIDE
+ std::string GetName() const override
{
return cmGlobalWatcomWMakeGenerator::GetActualName();
}
@@ -43,10 +43,10 @@ public:
* extension, pthreads, byte order etc.
*/
void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*,
- bool optional) CM_OVERRIDE;
+ bool optional) override;
- bool AllowNotParallel() const CM_OVERRIDE { return false; }
- bool AllowDeleteOnError() const CM_OVERRIDE { return false; }
+ bool AllowNotParallel() const override { return false; }
+ bool AllowDeleteOnError() const override { return false; }
};
#endif
diff --git a/Source/cmGlobalXCodeGenerator.cxx b/Source/cmGlobalXCodeGenerator.cxx
index 903796123..c79ee475c 100644
--- a/Source/cmGlobalXCodeGenerator.cxx
+++ b/Source/cmGlobalXCodeGenerator.cxx
@@ -5,10 +5,12 @@
#include "cmsys/RegularExpression.hxx"
#include <assert.h>
#include <iomanip>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
#include <string.h>
+#include "cmAlgorithms.h"
#include "cmComputeLinkInformation.h"
#include "cmCustomCommandGenerator.h"
#include "cmDocumentationEntry.h"
@@ -29,7 +31,6 @@
#include "cmXCode21Object.h"
#include "cmXCodeObject.h"
#include "cmXCodeScheme.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
struct cmLinkImplementation;
@@ -46,8 +47,11 @@ public:
: Version("1.5")
{
}
- void StartElement(const std::string&, const char**) { this->Data = ""; }
- void EndElement(const std::string& name)
+ void StartElement(const std::string&, const char**) override
+ {
+ this->Data = "";
+ }
+ void EndElement(const std::string& name) override
{
if (name == "key") {
this->Key = this->Data;
@@ -57,7 +61,7 @@ public:
}
}
}
- void CharacterDataHandler(const char* data, int length)
+ void CharacterDataHandler(const char* data, int length) override
{
this->Data.append(data, length);
}
@@ -79,7 +83,7 @@ class cmGlobalXCodeGenerator::BuildObjectListOrString
public:
BuildObjectListOrString(cmGlobalXCodeGenerator* gen, bool buildObjectList)
: Generator(gen)
- , Group(0)
+ , Group(nullptr)
, Empty(true)
{
if (buildObjectList) {
@@ -107,9 +111,8 @@ public:
{
if (this->Group) {
return this->Group;
- } else {
- return this->Generator->CreateString(this->String);
}
+ return this->Generator->CreateString(this->String);
}
};
@@ -117,20 +120,20 @@ class cmGlobalXCodeGenerator::Factory : public cmGlobalGeneratorFactory
{
public:
cmGlobalGenerator* CreateGlobalGenerator(const std::string& name,
- cmake* cm) const CM_OVERRIDE;
+ cmake* cm) const override;
- void GetDocumentation(cmDocumentationEntry& entry) const CM_OVERRIDE
+ void GetDocumentation(cmDocumentationEntry& entry) const override
{
cmGlobalXCodeGenerator::GetDocumentation(entry);
}
- void GetGenerators(std::vector<std::string>& names) const CM_OVERRIDE
+ void GetGenerators(std::vector<std::string>& names) const override
{
names.push_back(cmGlobalXCodeGenerator::GetActualName());
}
- bool SupportsToolset() const CM_OVERRIDE { return true; }
- bool SupportsPlatform() const CM_OVERRIDE { return false; }
+ bool SupportsToolset() const override { return true; }
+ bool SupportsPlatform() const override { return false; }
};
cmGlobalXCodeGenerator::cmGlobalXCodeGenerator(
@@ -140,10 +143,10 @@ cmGlobalXCodeGenerator::cmGlobalXCodeGenerator(
this->VersionString = version_string;
this->XcodeVersion = version_number;
- this->RootObject = 0;
- this->MainGroupChildren = 0;
- this->CurrentMakefile = 0;
- this->CurrentLocalGenerator = 0;
+ this->RootObject = nullptr;
+ this->MainGroupChildren = nullptr;
+ this->CurrentMakefile = nullptr;
+ this->CurrentLocalGenerator = nullptr;
this->XcodeBuildCommandInitialized = false;
this->ObjectDirArchDefault = "$(CURRENT_ARCH)";
@@ -160,16 +163,18 @@ cmGlobalGeneratorFactory* cmGlobalXCodeGenerator::NewFactory()
cmGlobalGenerator* cmGlobalXCodeGenerator::Factory::CreateGlobalGenerator(
const std::string& name, cmake* cm) const
{
- if (name != GetActualName())
- return 0;
+ if (name != GetActualName()) {
+ return nullptr;
+ }
#if defined(CMAKE_BUILD_WITH_CMAKE)
cmXcodeVersionParser parser;
std::string versionFile;
{
std::string out;
std::string::size_type pos;
- if (cmSystemTools::RunSingleCommand("xcode-select --print-path", &out, 0,
- 0, 0, cmSystemTools::OUTPUT_NONE) &&
+ if (cmSystemTools::RunSingleCommand("xcode-select --print-path", &out,
+ nullptr, nullptr, nullptr,
+ cmSystemTools::OUTPUT_NONE) &&
(pos = out.find(".app/"), pos != std::string::npos)) {
versionFile = out.substr(0, pos + 5) + "Contents/version.plist";
}
@@ -193,11 +198,11 @@ cmGlobalGenerator* cmGlobalXCodeGenerator::Factory::CreateGlobalGenerator(
if (version_number < 30) {
cm->IssueMessage(cmake::FATAL_ERROR,
"Xcode " + version_string + " not supported.");
- return CM_NULLPTR;
+ return nullptr;
}
- CM_AUTO_PTR<cmGlobalXCodeGenerator> gg(
- new cmGlobalXCodeGenerator(cm, version_string, version_number));
+ auto gg = cm::make_unique<cmGlobalXCodeGenerator>(cm, version_string,
+ version_number);
return gg.release();
#else
std::cerr << "CMake should be built with cmake to use Xcode, "
@@ -235,10 +240,9 @@ std::string cmGlobalXCodeGenerator::FindXcodeBuildCommand()
makeProgram = "xcodebuild";
}
return makeProgram;
- } else {
- // Use cmakexbuild wrapper to suppress environment dump from output.
- return cmSystemTools::GetCMakeCommand() + "xbuild";
}
+ // Use cmakexbuild wrapper to suppress environment dump from output.
+ return cmSystemTools::GetCMakeCommand() + "xbuild";
}
bool cmGlobalXCodeGenerator::SetGeneratorToolset(std::string const& ts,
@@ -330,7 +334,7 @@ cmLocalGenerator* cmGlobalXCodeGenerator::CreateLocalGenerator(cmMakefile* mf)
void cmGlobalXCodeGenerator::AddExtraIDETargets()
{
- std::map<std::string, std::vector<cmLocalGenerator*> >::iterator it;
+ std::map<std::string, std::vector<cmLocalGenerator*>>::iterator it;
// make sure extra targets are added before calling
// the parent generate which will call trace depends
for (it = this->ProjectMap.begin(); it != this->ProjectMap.end(); ++it) {
@@ -347,7 +351,7 @@ void cmGlobalXCodeGenerator::Generate()
if (cmSystemTools::GetErrorOccuredFlag()) {
return;
}
- std::map<std::string, std::vector<cmLocalGenerator*> >::iterator it;
+ std::map<std::string, std::vector<cmLocalGenerator*>>::iterator it;
for (it = this->ProjectMap.begin(); it != this->ProjectMap.end(); ++it) {
cmLocalGenerator* root = it->second[0];
this->SetGenerationRoot(root);
@@ -391,7 +395,7 @@ void cmGlobalXCodeGenerator::AddExtraTargets(
cmMakefile* mf = root->GetMakefile();
// Add ALL_BUILD
- const char* no_working_directory = 0;
+ const char* no_working_directory = nullptr;
std::vector<std::string> no_depends;
cmTarget* allbuild =
mf->AddUtilityCommand("ALL_BUILD", true, no_depends, no_working_directory,
@@ -433,18 +437,13 @@ void cmGlobalXCodeGenerator::AddExtraTargets(
// now make the allbuild depend on all the non-utility targets
// in the project
- for (std::vector<cmLocalGenerator*>::iterator i = gens.begin();
- i != gens.end(); ++i) {
- cmLocalGenerator* lg = *i;
- if (this->IsExcluded(root, *i)) {
+ for (auto& gen : gens) {
+ if (this->IsExcluded(root, gen)) {
continue;
}
- std::vector<cmGeneratorTarget*> tgts = lg->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
- l != tgts.end(); l++) {
- cmGeneratorTarget* target = *l;
-
+ const std::vector<cmGeneratorTarget*>& tgts = gen->GetGeneratorTargets();
+ for (auto target : tgts) {
if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
continue;
}
@@ -470,7 +469,7 @@ void cmGlobalXCodeGenerator::AddExtraTargets(
cmCustomCommandLines commandLines;
commandLines.push_back(makeHelper);
std::vector<std::string> no_byproducts;
- lg->GetMakefile()->AddCustomCommandToTarget(
+ gen->GetMakefile()->AddCustomCommandToTarget(
target->GetName(), no_byproducts, no_depends, commandLines,
cmTarget::POST_BUILD, "Depend check for xcode", dir.c_str(), true,
false, "", false, cmMakefile::AcceptObjectLibraryCommands);
@@ -482,7 +481,7 @@ void cmGlobalXCodeGenerator::AddExtraTargets(
}
// Refer to the build configuration file for easy editing.
- listfile = lg->GetCurrentSourceDirectory();
+ listfile = gen->GetCurrentSourceDirectory();
listfile += "/";
listfile += "CMakeLists.txt";
target->AddSource(listfile);
@@ -494,9 +493,8 @@ void cmGlobalXCodeGenerator::CreateReRunCMakeFile(
cmLocalGenerator* root, std::vector<cmLocalGenerator*> const& gens)
{
std::vector<std::string> lfiles;
- for (std::vector<cmLocalGenerator*>::const_iterator gi = gens.begin();
- gi != gens.end(); ++gi) {
- std::vector<std::string> const& lf = (*gi)->GetMakefile()->GetListFiles();
+ for (auto gen : gens) {
+ std::vector<std::string> const& lf = gen->GetMakefile()->GetListFiles();
lfiles.insert(lfiles.end(), lf.begin(), lf.end());
}
@@ -556,8 +554,8 @@ void cmGlobalXCodeGenerator::SortXCodeObjects()
void cmGlobalXCodeGenerator::ClearXCodeObjects()
{
this->TargetDoneSet.clear();
- for (unsigned int i = 0; i < this->XCodeObjects.size(); ++i) {
- delete this->XCodeObjects[i];
+ for (auto& obj : this->XCodeObjects) {
+ delete obj;
}
this->XCodeObjects.clear();
this->XCodeObjectIDs.clear();
@@ -571,7 +569,7 @@ void cmGlobalXCodeGenerator::ClearXCodeObjects()
void cmGlobalXCodeGenerator::addObject(cmXCodeObject* obj)
{
if (obj->GetType() == cmXCodeObject::OBJECT) {
- std::string id = obj->GetId();
+ const std::string& id = obj->GetId();
// If this is a duplicate id, it's an error:
//
@@ -668,8 +666,10 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeSourceFile(
if (const char* cflags = sf->GetProperty("COMPILE_FLAGS")) {
cmGeneratorExpression ge;
std::string configName = "NO-PER-CONFIG-SUPPORT-IN-XCODE";
- CM_AUTO_PTR<cmCompiledGeneratorExpression> compiledExpr = ge.Parse(cflags);
- const char* processed = compiledExpr->Evaluate(lg, configName);
+ std::unique_ptr<cmCompiledGeneratorExpression> compiledExpr =
+ ge.Parse(cflags);
+ const char* processed =
+ compiledExpr->Evaluate(lg, configName, false, gtgt);
if (compiledExpr->GetHadContextSensitiveCondition()) {
std::ostringstream e;
/* clang-format off */
@@ -925,18 +925,16 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
cmLocalGenerator* gen, std::vector<cmXCodeObject*>& targets)
{
this->SetCurrentLocalGenerator(gen);
- std::vector<cmGeneratorTarget*> tgts =
+ const std::vector<cmGeneratorTarget*>& tgts =
this->CurrentLocalGenerator->GetGeneratorTargets();
typedef std::map<std::string, cmGeneratorTarget*, cmCompareTargets>
cmSortedTargets;
cmSortedTargets sortedTargets;
- for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
- l != tgts.end(); l++) {
- sortedTargets[(*l)->GetName()] = *l;
+ for (auto tgt : tgts) {
+ sortedTargets[tgt->GetName()] = tgt;
}
- for (cmSortedTargets::iterator l = sortedTargets.begin();
- l != sortedTargets.end(); l++) {
- cmGeneratorTarget* gtgt = l->second;
+ for (auto& sortedTarget : sortedTargets) {
+ cmGeneratorTarget* gtgt = sortedTarget.second;
std::string targetName = gtgt->GetName();
@@ -1018,7 +1016,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
}
std::string const& obj = (*oi)->GetFullPath();
cmXCodeObject* xsf =
- this->CreateXCodeSourceFileFromPath(obj, gtgt, "", 0);
+ this->CreateXCodeSourceFileFromPath(obj, gtgt, "", nullptr);
externalObjFiles.push_back(xsf);
}
}
@@ -1028,10 +1026,10 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
bool isBundleTarget = gtgt->GetPropertyAsBool("MACOSX_BUNDLE");
bool isCFBundleTarget = gtgt->IsCFBundleOnApple();
- cmXCodeObject* buildFiles = 0;
+ cmXCodeObject* buildFiles = nullptr;
// create source build phase
- cmXCodeObject* sourceBuildPhase = 0;
+ cmXCodeObject* sourceBuildPhase = nullptr;
if (!sourceFiles.empty()) {
sourceBuildPhase =
this->CreateObject(cmXCodeObject::PBXSourcesBuildPhase);
@@ -1039,9 +1037,8 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
sourceBuildPhase->AddAttribute("buildActionMask",
this->CreateString("2147483647"));
buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
- for (std::vector<cmXCodeObject*>::iterator i = sourceFiles.begin();
- i != sourceFiles.end(); ++i) {
- buildFiles->AddObject(*i);
+ for (auto& sourceFile : sourceFiles) {
+ buildFiles->AddObject(sourceFile);
}
sourceBuildPhase->AddAttribute("files", buildFiles);
sourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
@@ -1049,7 +1046,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
}
// create header build phase - only for framework targets
- cmXCodeObject* headerBuildPhase = 0;
+ cmXCodeObject* headerBuildPhase = nullptr;
if (!headerFiles.empty() && isFrameworkTarget) {
headerBuildPhase =
this->CreateObject(cmXCodeObject::PBXHeadersBuildPhase);
@@ -1057,9 +1054,8 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
headerBuildPhase->AddAttribute("buildActionMask",
this->CreateString("2147483647"));
buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
- for (std::vector<cmXCodeObject*>::iterator i = headerFiles.begin();
- i != headerFiles.end(); ++i) {
- buildFiles->AddObject(*i);
+ for (auto& headerFile : headerFiles) {
+ buildFiles->AddObject(headerFile);
}
headerBuildPhase->AddAttribute("files", buildFiles);
headerBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
@@ -1067,7 +1063,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
}
// create resource build phase - only for framework or bundle targets
- cmXCodeObject* resourceBuildPhase = 0;
+ cmXCodeObject* resourceBuildPhase = nullptr;
if (!resourceFiles.empty() &&
(isFrameworkTarget || isBundleTarget || isCFBundleTarget)) {
resourceBuildPhase =
@@ -1076,9 +1072,8 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
resourceBuildPhase->AddAttribute("buildActionMask",
this->CreateString("2147483647"));
buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
- for (std::vector<cmXCodeObject*>::iterator i = resourceFiles.begin();
- i != resourceFiles.end(); ++i) {
- buildFiles->AddObject(*i);
+ for (auto& resourceFile : resourceFiles) {
+ buildFiles->AddObject(resourceFile);
}
resourceBuildPhase->AddAttribute("files", buildFiles);
resourceBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
@@ -1089,7 +1084,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
// framework or bundle targets
std::vector<cmXCodeObject*> contentBuildPhases;
if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
- typedef std::map<std::string, std::vector<cmSourceFile*> >
+ typedef std::map<std::string, std::vector<cmSourceFile*>>
mapOfVectorOfSourceFiles;
mapOfVectorOfSourceFiles bundleFiles;
for (std::vector<cmSourceFile*>::const_iterator i = classes.begin();
@@ -1140,7 +1135,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
// create vector of "resource content file" build phases - only for
// framework or bundle targets
if (isFrameworkTarget || isBundleTarget || isCFBundleTarget) {
- typedef std::map<std::string, std::vector<cmSourceFile*> >
+ typedef std::map<std::string, std::vector<cmSourceFile*>>
mapOfVectorOfSourceFiles;
mapOfVectorOfSourceFiles bundleFiles;
for (std::vector<cmSourceFile*>::const_iterator i = classes.begin();
@@ -1177,7 +1172,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
}
// create framework build phase
- cmXCodeObject* frameworkBuildPhase = 0;
+ cmXCodeObject* frameworkBuildPhase = nullptr;
if (!externalObjFiles.empty()) {
frameworkBuildPhase =
this->CreateObject(cmXCodeObject::PBXFrameworksBuildPhase);
@@ -1186,9 +1181,8 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
this->CreateString("2147483647"));
buildFiles = this->CreateObject(cmXCodeObject::OBJECT_LIST);
frameworkBuildPhase->AddAttribute("files", buildFiles);
- for (std::vector<cmXCodeObject*>::iterator i = externalObjFiles.begin();
- i != externalObjFiles.end(); ++i) {
- buildFiles->AddObject(*i);
+ for (auto& externalObjFile : externalObjFiles) {
+ buildFiles->AddObject(externalObjFile);
}
frameworkBuildPhase->AddAttribute("runOnlyForDeploymentPostprocessing",
this->CreateString("0"));
@@ -1209,14 +1203,13 @@ bool cmGlobalXCodeGenerator::CreateXCodeTargets(
void cmGlobalXCodeGenerator::ForceLinkerLanguages()
{
- for (unsigned int i = 0; i < this->LocalGenerators.size(); ++i) {
- std::vector<cmGeneratorTarget*> tgts =
- this->LocalGenerators[i]->GetGeneratorTargets();
+ for (auto& localGenerator : this->LocalGenerators) {
+ const std::vector<cmGeneratorTarget*>& tgts =
+ localGenerator->GetGeneratorTargets();
// All targets depend on the build-system check target.
- for (std::vector<cmGeneratorTarget*>::const_iterator ti = tgts.begin();
- ti != tgts.end(); ++ti) {
+ for (auto tgt : tgts) {
// This makes sure all targets link using the proper language.
- this->ForceLinkerLanguage(*ti);
+ this->ForceLinkerLanguage(tgt);
}
}
}
@@ -1237,9 +1230,8 @@ void cmGlobalXCodeGenerator::ForceLinkerLanguage(cmGeneratorTarget* gtgt)
// If the language is compiled as a source trust Xcode to link with it.
cmLinkImplementation const* impl = gtgt->GetLinkImplementation("NOCONFIG");
- for (std::vector<std::string>::const_iterator li = impl->Languages.begin();
- li != impl->Languages.end(); ++li) {
- if (*li == llang) {
+ for (auto const& Language : impl->Languages) {
+ if (Language == llang) {
return;
}
}
@@ -1277,8 +1269,8 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateBuildPhase(
const char* name, const char* name2, cmGeneratorTarget* target,
const std::vector<cmCustomCommand>& commands)
{
- if (commands.size() == 0 && strcmp(name, "CMake ReRun") != 0) {
- return 0;
+ if (commands.empty() && strcmp(name, "CMake ReRun") != 0) {
+ return nullptr;
}
cmXCodeObject* buildPhase =
this->CreateObject(cmXCodeObject::PBXShellScriptBuildPhase);
@@ -1465,7 +1457,7 @@ void cmGlobalXCodeGenerator::FilterConfigurationAttribute(
return;
}
- std::string::size_type endVariant = attribute.find("]", beginVariant + 9);
+ std::string::size_type endVariant = attribute.find(']', beginVariant + 9);
if (endVariant == std::string::npos) {
// There is no terminating bracket.
return;
@@ -1541,16 +1533,15 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
makefileStream << "all: ";
std::map<const cmCustomCommand*, std::string> tname;
int count = 0;
- for (std::vector<cmCustomCommand>::const_iterator i = commands.begin();
- i != commands.end(); ++i) {
- cmCustomCommandGenerator ccg(*i, configName, this->CurrentLocalGenerator);
+ for (auto const& command : commands) {
+ cmCustomCommandGenerator ccg(command, configName,
+ this->CurrentLocalGenerator);
if (ccg.GetNumberOfCommands() > 0) {
const std::vector<std::string>& outputs = ccg.GetOutputs();
if (!outputs.empty()) {
- for (std::vector<std::string>::const_iterator o = outputs.begin();
- o != outputs.end(); ++o) {
+ for (auto const& output : outputs) {
makefileStream << "\\\n\t"
- << this->ConvertToRelativeForMake(o->c_str());
+ << this->ConvertToRelativeForMake(output.c_str());
}
} else {
std::ostringstream str;
@@ -1561,18 +1552,18 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
}
}
makefileStream << "\n\n";
- for (std::vector<cmCustomCommand>::const_iterator i = commands.begin();
- i != commands.end(); ++i) {
- cmCustomCommandGenerator ccg(*i, configName, this->CurrentLocalGenerator);
+ for (auto const& command : commands) {
+ cmCustomCommandGenerator ccg(command, configName,
+ this->CurrentLocalGenerator);
if (ccg.GetNumberOfCommands() > 0) {
makefileStream << "\n";
const std::vector<std::string>& outputs = ccg.GetOutputs();
if (!outputs.empty()) {
// There is at least one output, start the rule for it
const char* sep = "";
- for (std::vector<std::string>::const_iterator oi = outputs.begin();
- oi != outputs.end(); ++oi) {
- makefileStream << sep << this->ConvertToRelativeForMake(oi->c_str());
+ for (auto const& output : outputs) {
+ makefileStream << sep
+ << this->ConvertToRelativeForMake(output.c_str());
sep = " ";
}
makefileStream << ": ";
@@ -1580,11 +1571,9 @@ void cmGlobalXCodeGenerator::CreateCustomRulesMakefile(
// There are no outputs. Use the generated force rule name.
makefileStream << tname[&ccg.GetCC()] << ": ";
}
- for (std::vector<std::string>::const_iterator d =
- ccg.GetDepends().begin();
- d != ccg.GetDepends().end(); ++d) {
+ for (auto const& d : ccg.GetDepends()) {
std::string dep;
- if (this->CurrentLocalGenerator->GetRealDependency(*d, configName,
+ if (this->CurrentLocalGenerator->GetRealDependency(d, configName,
dep)) {
makefileStream << "\\\n"
<< this->ConvertToRelativeForMake(dep.c_str());
@@ -1639,9 +1628,7 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
std::set<std::string> languages;
gtgt->GetLanguages(languages, configName);
std::map<std::string, std::string> cflags;
- for (std::set<std::string>::iterator li = languages.begin();
- li != languages.end(); ++li) {
- std::string const& lang = *li;
+ for (auto const& lang : languages) {
std::string& flags = cflags[lang];
// Add language-specific flags.
@@ -1737,9 +1724,8 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
} else {
cmXCodeObject* archObjects =
this->CreateObject(cmXCodeObject::OBJECT_LIST);
- for (std::vector<std::string>::iterator i = archs.begin();
- i != archs.end(); i++) {
- archObjects->AddObject(this->CreateString(*i));
+ for (auto& arch : archs) {
+ archObjects->AddObject(this->CreateString(arch));
}
buildSettings->AddAttribute("ARCHS", archObjects);
}
@@ -1754,8 +1740,8 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
const char* version = gtgt->GetProperty("VERSION");
const char* soversion = gtgt->GetProperty("SOVERSION");
if (!gtgt->HasSOName(configName) || gtgt->IsFrameworkOnApple()) {
- version = 0;
- soversion = 0;
+ version = nullptr;
+ soversion = nullptr;
}
if (version && !soversion) {
soversion = version;
@@ -1964,10 +1950,9 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
std::set<std::string> emitted;
emitted.insert("/System/Library/Frameworks");
- for (std::vector<std::string>::iterator i = includes.begin();
- i != includes.end(); ++i) {
- if (this->NameResolvesToFramework(*i)) {
- std::string frameworkDir = *i;
+ for (auto& include : includes) {
+ if (this->NameResolvesToFramework(include)) {
+ std::string frameworkDir = include;
frameworkDir += "/../";
frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
if (emitted.insert(frameworkDir).second) {
@@ -1980,9 +1965,9 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
}
}
} else {
- std::string incpath = this->XCodeEscapePath(*i);
+ std::string incpath = this->XCodeEscapePath(include);
if (emitSystemIncludes &&
- gtgt->IsSystemIncludeDirectory(*i, configName)) {
+ gtgt->IsSystemIncludeDirectory(include, configName)) {
sysdirs.Add(incpath);
} else {
dirs.Add(incpath);
@@ -1992,12 +1977,11 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
// Add framework search paths needed for linking.
if (cmComputeLinkInformation* cli = gtgt->GetLinkInformation(configName)) {
std::vector<std::string> const& fwDirs = cli->GetFrameworkPaths();
- for (std::vector<std::string>::const_iterator fdi = fwDirs.begin();
- fdi != fwDirs.end(); ++fdi) {
- if (emitted.insert(*fdi).second) {
- std::string incpath = this->XCodeEscapePath(*fdi);
+ for (auto const& fwDir : fwDirs) {
+ if (emitted.insert(fwDir).second) {
+ std::string incpath = this->XCodeEscapePath(fwDir);
if (emitSystemIncludes &&
- gtgt->IsSystemIncludeDirectory(*fdi, configName)) {
+ gtgt->IsSystemIncludeDirectory(fwDir, configName)) {
sysfdirs.Add(incpath);
} else {
fdirs.Add(incpath);
@@ -2025,27 +2009,25 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
// system include directory awareness. We need to also keep on setting
// HEADER_SEARCH_PATHS to work around a missing compile options flag for
// GNU assembly files (#16449)
- for (std::set<std::string>::iterator li = languages.begin();
- li != languages.end(); ++li) {
+ for (auto const& language : languages) {
std::string includeFlags = this->CurrentLocalGenerator->GetIncludeFlags(
- includes, gtgt, *li, true, false, configName);
+ includes, gtgt, language, true, false, configName);
if (!includeFlags.empty()) {
- cflags[*li] += " " + includeFlags;
+ cflags[language] += " " + includeFlags;
}
}
}
bool same_gflags = true;
std::map<std::string, std::string> gflags;
- std::string const* last_gflag = 0;
+ std::string const* last_gflag = nullptr;
std::string optLevel = "0";
// Minimal map of flags to build settings.
- for (std::set<std::string>::iterator li = languages.begin();
- li != languages.end(); ++li) {
- std::string& flags = cflags[*li];
- std::string& gflag = gflags[*li];
+ for (auto const& language : languages) {
+ std::string& flags = cflags[language];
+ std::string& gflag = gflags[language];
std::string oflag =
this->ExtractFlagRegex("(^| )(-Ofast|-Os|-O[0-9]*)( |$)", 2, flags);
if (oflag.size() == 2) {
@@ -2070,10 +2052,9 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
if (!same_gflags) {
// We can't set the Xcode flag differently depending on the language,
// so put them back in this case.
- for (std::set<std::string>::iterator li = languages.begin();
- li != languages.end(); ++li) {
- cflags[*li] += " ";
- cflags[*li] += gflags[*li];
+ for (auto const& language : languages) {
+ cflags[language] += " ";
+ cflags[language] += gflags[language];
}
debugStr = "NO";
} else if (last_gflag && (last_gflag->empty() || *last_gflag == "-g0")) {
@@ -2090,25 +2071,24 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
this->CreateString("NO"));
buildSettings->AddAttribute("GCC_INLINES_ARE_PRIVATE_EXTERN",
this->CreateString("NO"));
- for (std::set<std::string>::iterator li = languages.begin();
- li != languages.end(); ++li) {
- std::string flags = cflags[*li] + " " + defFlags;
- if (*li == "CXX") {
+ for (auto const& language : languages) {
+ std::string flags = cflags[language] + " " + defFlags;
+ if (language == "CXX") {
buildSettings->AddAttribute("OTHER_CPLUSPLUSFLAGS",
this->CreateString(flags));
- } else if (*li == "Fortran") {
+ } else if (language == "Fortran") {
buildSettings->AddAttribute("IFORT_OTHER_FLAGS",
this->CreateString(flags));
- } else if (*li == "C") {
+ } else if (language == "C") {
buildSettings->AddAttribute("OTHER_CFLAGS", this->CreateString(flags));
- } else if (*li == "Swift") {
+ } else if (language == "Swift") {
buildSettings->AddAttribute("OTHER_SWIFT_FLAGS",
this->CreateString(flags));
}
}
// Add Fortran source format attribute if property is set.
- const char* format = 0;
+ const char* format = nullptr;
const char* tgtfmt = gtgt->GetProperty("Fortran_FORMAT");
switch (cmOutputConverter::GetFortranFormat(tgtfmt)) {
case cmOutputConverter::FortranFormatFixed:
@@ -2225,15 +2205,14 @@ void cmGlobalXCodeGenerator::CreateBuildSettings(cmGeneratorTarget* gtgt,
// Convert "XCODE_ATTRIBUTE_*" properties directly.
{
std::vector<std::string> const& props = gtgt->GetPropertyKeys();
- for (std::vector<std::string>::const_iterator i = props.begin();
- i != props.end(); ++i) {
- if (i->find("XCODE_ATTRIBUTE_") == 0) {
- std::string attribute = i->substr(16);
+ for (auto const& prop : props) {
+ if (prop.find("XCODE_ATTRIBUTE_") == 0) {
+ std::string attribute = prop.substr(16);
this->FilterConfigurationAttribute(configName, attribute);
if (!attribute.empty()) {
cmGeneratorExpression ge;
std::string processed =
- ge.Parse(gtgt->GetProperty(*i))
+ ge.Parse(gtgt->GetProperty(prop))
->Evaluate(this->CurrentLocalGenerator, configName);
buildSettings->AddAttribute(attribute,
this->CreateString(processed));
@@ -2268,8 +2247,8 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
target->SetComment(gtgt->GetName());
cmXCodeObject* buildPhases = this->CreateObject(cmXCodeObject::OBJECT_LIST);
std::vector<cmXCodeObject*> emptyContentVector;
- this->CreateCustomCommands(buildPhases, 0, 0, 0, emptyContentVector, 0,
- gtgt);
+ this->CreateCustomCommands(buildPhases, nullptr, nullptr, nullptr,
+ emptyContentVector, nullptr, gtgt);
target->AddAttribute("buildPhases", buildPhases);
this->AddConfigurations(target, gtgt);
cmXCodeObject* dependencies = this->CreateObject(cmXCodeObject::OBJECT_LIST);
@@ -2283,7 +2262,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateUtilityTarget(
if (gtgt->GetType() == cmStateEnums::UTILITY) {
std::vector<cmSourceFile*> sources;
if (!gtgt->GetConfigCommonSourceFiles(sources)) {
- return 0;
+ return nullptr;
}
for (std::vector<cmSourceFile*>::const_iterator i = sources.begin();
@@ -2321,15 +2300,15 @@ std::string cmGlobalXCodeGenerator::AddConfigurations(cmXCodeObject* target,
configlist->SetComment(comment);
target->AddAttribute("buildConfigurationList",
this->CreateObjectReference(configlist));
- for (unsigned int i = 0; i < configVector.size(); ++i) {
+ for (auto const& i : configVector) {
cmXCodeObject* config =
this->CreateObject(cmXCodeObject::XCBuildConfiguration);
buildConfigurations->AddObject(config);
cmXCodeObject* buildSettings =
this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
- this->CreateBuildSettings(gtgt, buildSettings, configVector[i]);
- config->AddAttribute("name", this->CreateString(configVector[i]));
- config->SetComment(configVector[i]);
+ this->CreateBuildSettings(gtgt, buildSettings, i);
+ config->AddAttribute("name", this->CreateString(i));
+ config->SetComment(i);
config->AddAttribute("buildSettings", buildSettings);
}
if (!configVector.empty()) {
@@ -2349,9 +2328,8 @@ const char* cmGlobalXCodeGenerator::GetTargetLinkFlagsVar(
(target->GetType() == cmStateEnums::STATIC_LIBRARY ||
target->GetType() == cmStateEnums::OBJECT_LIBRARY)) {
return "OTHER_LIBTOOLFLAGS";
- } else {
- return "OTHER_LDFLAGS";
}
+ return "OTHER_LDFLAGS";
}
const char* cmGlobalXCodeGenerator::GetTargetFileType(
@@ -2368,12 +2346,13 @@ const char* cmGlobalXCodeGenerator::GetTargetFileType(
return (target->GetPropertyAsBool("FRAMEWORK") ? "wrapper.framework"
: "archive.ar");
case cmStateEnums::MODULE_LIBRARY:
- if (target->IsXCTestOnApple())
+ if (target->IsXCTestOnApple()) {
return "wrapper.cfbundle";
- else if (target->IsCFBundleOnApple())
+ }
+ if (target->IsCFBundleOnApple()) {
return "wrapper.plug-in";
- else
- return "compiled.mach-o.executable";
+ }
+ return "compiled.mach-o.executable";
case cmStateEnums::SHARED_LIBRARY:
return (target->GetPropertyAsBool("FRAMEWORK")
? "wrapper.framework"
@@ -2383,7 +2362,7 @@ const char* cmGlobalXCodeGenerator::GetTargetFileType(
default:
break;
}
- return 0;
+ return nullptr;
}
const char* cmGlobalXCodeGenerator::GetTargetProductType(
@@ -2401,12 +2380,13 @@ const char* cmGlobalXCodeGenerator::GetTargetProductType(
? "com.apple.product-type.framework"
: "com.apple.product-type.library.static");
case cmStateEnums::MODULE_LIBRARY:
- if (target->IsXCTestOnApple())
+ if (target->IsXCTestOnApple()) {
return "com.apple.product-type.bundle.unit-test";
- else if (target->IsCFBundleOnApple())
+ } else if (target->IsCFBundleOnApple()) {
return "com.apple.product-type.bundle";
- else
+ } else {
return "com.apple.product-type.tool";
+ }
case cmStateEnums::SHARED_LIBRARY:
return (target->GetPropertyAsBool("FRAMEWORK")
? "com.apple.product-type.framework"
@@ -2418,14 +2398,14 @@ const char* cmGlobalXCodeGenerator::GetTargetProductType(
default:
break;
}
- return 0;
+ return nullptr;
}
cmXCodeObject* cmGlobalXCodeGenerator::CreateXCodeTarget(
cmGeneratorTarget* gtgt, cmXCodeObject* buildPhases)
{
if (gtgt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
- return 0;
+ return nullptr;
}
cmXCodeObject* target = this->CreateObject(cmXCodeObject::PBXNativeTarget);
target->AddAttribute("buildPhases", buildPhases);
@@ -2469,13 +2449,13 @@ cmXCodeObject* cmGlobalXCodeGenerator::FindXCodeTarget(
cmGeneratorTarget const* t)
{
if (!t) {
- return 0;
+ return nullptr;
}
std::map<cmGeneratorTarget const*, cmXCodeObject*>::const_iterator const i =
this->XCodeObjectMap.find(t);
if (i == this->XCodeObjectMap.end()) {
- return 0;
+ return nullptr;
}
return i->second;
}
@@ -2560,15 +2540,14 @@ void cmGlobalXCodeGenerator::AppendBuildSettingAttribute(
std::vector<cmXCodeObject*> list = buildConfigs->GetObjectList();
// each configuration and the target itself has a buildSettings in it
// list.push_back(target);
- for (std::vector<cmXCodeObject*>::iterator i = list.begin(); i != list.end();
- ++i) {
+ for (auto& i : list) {
if (!configName.empty()) {
- if ((*i)->GetObject("name")->GetString() == configName) {
- cmXCodeObject* settings = (*i)->GetObject("buildSettings");
+ if (i->GetObject("name")->GetString() == configName) {
+ cmXCodeObject* settings = i->GetObject("buildSettings");
this->AppendOrAddBuildSetting(settings, attribute, value);
}
} else {
- cmXCodeObject* settings = (*i)->GetObject("buildSettings");
+ cmXCodeObject* settings = i->GetObject("buildSettings");
this->AppendOrAddBuildSetting(settings, attribute, value);
}
}
@@ -2587,20 +2566,15 @@ void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
// Add dependencies on other CMake targets.
TargetDependSet const& deps = this->GetTargetDirectDepends(gt);
- for (TargetDependSet::const_iterator i = deps.begin(); i != deps.end();
- ++i) {
- if (cmXCodeObject* dptarget = this->FindXCodeTarget(*i)) {
+ for (auto dep : deps) {
+ if (cmXCodeObject* dptarget = this->FindXCodeTarget(dep)) {
this->AddDependTarget(target, dptarget);
}
}
// Loop over configuration types and set per-configuration info.
- for (std::vector<std::string>::iterator i =
- this->CurrentConfigurationTypes.begin();
- i != this->CurrentConfigurationTypes.end(); ++i) {
+ for (auto const& configName : this->CurrentConfigurationTypes) {
// Get the current configuration name.
- std::string configName = *i;
-
if (this->XcodeVersion >= 50) {
// Add object library contents as link flags.
std::string linkObjs;
@@ -2636,9 +2610,8 @@ void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
// Add dependencies directly on library files.
{
std::vector<std::string> const& libDeps = cli.GetDepends();
- for (std::vector<std::string>::const_iterator j = libDeps.begin();
- j != libDeps.end(); ++j) {
- target->AddDependLibrary(configName, *j);
+ for (auto const& libDep : libDeps) {
+ target->AddDependLibrary(configName, libDep);
}
}
@@ -2646,16 +2619,15 @@ void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
{
std::vector<std::string> const& libDirs = cli.GetDirectories();
std::string linkDirs;
- for (std::vector<std::string>::const_iterator libDir = libDirs.begin();
- libDir != libDirs.end(); ++libDir) {
- if (libDir->size() && *libDir != "/usr/lib") {
+ for (auto const& libDir : libDirs) {
+ if (!libDir.empty() && libDir != "/usr/lib") {
// Now add the same one but append
// $(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) to it:
linkDirs += " ";
linkDirs += this->XCodeEscapePath(
- *libDir + "/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)");
+ libDir + "/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)");
linkDirs += " ";
- linkDirs += this->XCodeEscapePath(*libDir);
+ linkDirs += this->XCodeEscapePath(libDir);
}
}
this->AppendBuildSettingAttribute(target, "LIBRARY_SEARCH_PATHS",
@@ -2668,18 +2640,18 @@ void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
const char* sep = "";
typedef cmComputeLinkInformation::ItemVector ItemVector;
ItemVector const& libNames = cli.GetItems();
- for (ItemVector::const_iterator li = libNames.begin();
- li != libNames.end(); ++li) {
+ for (auto const& libName : libNames) {
linkLibs += sep;
sep = " ";
- if (li->IsPath) {
- linkLibs += this->XCodeEscapePath(li->Value);
- } else if (!li->Target ||
- li->Target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
- linkLibs += li->Value;
+ if (libName.IsPath) {
+ linkLibs += this->XCodeEscapePath(libName.Value);
+ } else if (!libName.Target ||
+ libName.Target->GetType() !=
+ cmStateEnums::INTERFACE_LIBRARY) {
+ linkLibs += libName.Value;
}
- if (li->Target && !li->Target->IsImported()) {
- target->AddDependTarget(configName, li->Target->GetName());
+ if (libName.Target && !libName.Target->IsImported()) {
+ target->AddDependTarget(configName, libName.Target->GetName());
}
}
this->AppendBuildSettingAttribute(
@@ -2691,15 +2663,12 @@ void cmGlobalXCodeGenerator::AddDependAndLinkInformation(cmXCodeObject* target)
bool cmGlobalXCodeGenerator::CreateGroups(
std::vector<cmLocalGenerator*>& generators)
{
- for (std::vector<cmLocalGenerator*>::iterator i = generators.begin();
- i != generators.end(); ++i) {
- cmMakefile* mf = (*i)->GetMakefile();
+ for (auto& generator : generators) {
+ cmMakefile* mf = generator->GetMakefile();
std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups();
- std::vector<cmGeneratorTarget*> tgts = (*i)->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
- l != tgts.end(); l++) {
- cmGeneratorTarget* gtgt = *l;
-
+ const std::vector<cmGeneratorTarget*>& tgts =
+ generator->GetGeneratorTargets();
+ for (auto gtgt : tgts) {
// Same skipping logic here as in CreateXCodeTargets so that we do not
// end up with (empty anyhow) ALL_BUILD and XCODE_DEPEND_HELPER source
// groups:
@@ -2723,10 +2692,8 @@ bool cmGlobalXCodeGenerator::CreateGroups(
gtgt->GetAllConfigSources();
// Put cmSourceFile instances in proper groups:
- for (std::vector<cmGeneratorTarget::AllConfigSource>::const_iterator si =
- sources.begin();
- si != sources.end(); ++si) {
- cmSourceFile const* sf = si->Source;
+ for (auto const& si : sources) {
+ cmSourceFile const* sf = si.Source;
if (this->XcodeVersion >= 50 && !sf->GetObjectLibrary().empty()) {
// Object library files go on the link line instead.
continue;
@@ -2745,19 +2712,21 @@ bool cmGlobalXCodeGenerator::CreateGroups(
}
cmXCodeObject* cmGlobalXCodeGenerator::CreatePBXGroup(cmXCodeObject* parent,
- std::string name)
+ const std::string& name)
{
- cmXCodeObject* parentChildren = NULL;
- if (parent)
+ cmXCodeObject* parentChildren = nullptr;
+ if (parent) {
parentChildren = parent->GetObject("children");
+ }
cmXCodeObject* group = this->CreateObject(cmXCodeObject::PBXGroup);
cmXCodeObject* groupChildren =
this->CreateObject(cmXCodeObject::OBJECT_LIST);
group->AddAttribute("name", this->CreateString(name));
group->AddAttribute("children", groupChildren);
group->AddAttribute("sourceTree", this->CreateString("<group>"));
- if (parentChildren)
+ if (parentChildren) {
parentChildren->AddObject(group);
+ }
return group;
}
@@ -2781,7 +2750,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
}
it = this->TargetGroup.find(target);
- cmXCodeObject* tgroup = 0;
+ cmXCodeObject* tgroup = nullptr;
if (it != this->TargetGroup.end()) {
tgroup = it->second;
} else {
@@ -2811,7 +2780,7 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
// If it's the default source group (empty name) then put the source file
// directly in the tgroup...
//
- if (std::string(sg->GetFullName()) == "") {
+ if (std::string(sg->GetFullName()).empty()) {
this->GroupNameMap[s] = tgroup;
return tgroup;
}
@@ -2822,13 +2791,13 @@ cmXCodeObject* cmGlobalXCodeGenerator::CreateOrGetPBXGroup(
cmSystemTools::tokenize(sg->GetFullName(), "\\");
std::string curr_folder = target;
curr_folder += "/";
- for (std::vector<std::string>::size_type i = 0; i < folders.size(); i++) {
- curr_folder += folders[i];
+ for (auto const& folder : folders) {
+ curr_folder += folder;
std::map<std::string, cmXCodeObject*>::iterator i_folder =
this->GroupNameMap.find(curr_folder);
// Create new folder
if (i_folder == this->GroupNameMap.end()) {
- cmXCodeObject* group = this->CreatePBXGroup(tgroup, folders[i]);
+ cmXCodeObject* group = this->CreatePBXGroup(tgroup, folder);
this->GroupNameMap[curr_folder] = group;
tgroup = group;
} else {
@@ -2847,15 +2816,15 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
{
this->ClearXCodeObjects();
- this->RootObject = 0;
- this->MainGroupChildren = 0;
+ this->RootObject = nullptr;
+ this->MainGroupChildren = nullptr;
cmXCodeObject* group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
group->AddAttribute("COPY_PHASE_STRIP", this->CreateString("NO"));
cmXCodeObject* listObjs = this->CreateObject(cmXCodeObject::OBJECT_LIST);
- for (unsigned int i = 0; i < this->CurrentConfigurationTypes.size(); ++i) {
+ for (auto& CurrentConfigurationType : this->CurrentConfigurationTypes) {
cmXCodeObject* buildStyle =
this->CreateObject(cmXCodeObject::PBXBuildStyle);
- const char* name = this->CurrentConfigurationTypes[i].c_str();
+ const char* name = CurrentConfigurationType.c_str();
buildStyle->AddAttribute("name", this->CreateString(name));
buildStyle->SetComment(name);
cmXCodeObject* sgroup = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
@@ -2888,7 +2857,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
std::string project_id = "PROJECT_";
project_id += root->GetProjectName();
this->RootObject->SetId(
- this->GetOrCreateId(project_id.c_str(), this->RootObject->GetId()));
+ this->GetOrCreateId(project_id, this->RootObject->GetId()));
group = this->CreateObject(cmXCodeObject::ATTRIBUTE_GROUP);
this->RootObject->AddAttribute("mainGroup",
@@ -2904,15 +2873,16 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
v << std::setfill('0') << std::setw(4) << XcodeVersion * 10;
group->AddAttribute("LastUpgradeCheck", this->CreateString(v.str()));
this->RootObject->AddAttribute("attributes", group);
- if (this->XcodeVersion >= 32)
+ if (this->XcodeVersion >= 32) {
this->RootObject->AddAttribute("compatibilityVersion",
this->CreateString("Xcode 3.2"));
- else if (this->XcodeVersion >= 31)
+ } else if (this->XcodeVersion >= 31) {
this->RootObject->AddAttribute("compatibilityVersion",
this->CreateString("Xcode 3.1"));
- else
+ } else {
this->RootObject->AddAttribute("compatibilityVersion",
this->CreateString("Xcode 3.0"));
+ }
// Point Xcode at the top of the source tree.
{
std::string pdir =
@@ -2924,7 +2894,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
this->CreateObject(cmXCodeObject::XCConfigurationList);
cmXCodeObject* buildConfigurations =
this->CreateObject(cmXCodeObject::OBJECT_LIST);
- typedef std::vector<std::pair<std::string, cmXCodeObject*> > Configs;
+ typedef std::vector<std::pair<std::string, cmXCodeObject*>> Configs;
Configs configs;
const char* defaultConfigName = "Debug";
for (unsigned int i = 0; i < this->CurrentConfigurationTypes.size(); ++i) {
@@ -2937,8 +2907,8 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
config->AddAttribute("name", this->CreateString(name));
configs.push_back(std::make_pair(name, config));
}
- for (Configs::iterator c = configs.begin(); c != configs.end(); ++c) {
- buildConfigurations->AddObject(c->second);
+ for (auto& config : configs) {
+ buildConfigurations->AddObject(config.second);
}
configlist->AddAttribute("buildConfigurations", buildConfigurations);
@@ -2996,7 +2966,7 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
symroot += "/build";
buildSettings->AddAttribute("SYMROOT", this->CreateString(symroot));
- for (Configs::iterator i = configs.begin(); i != configs.end(); ++i) {
+ for (auto& config : configs) {
cmXCodeObject* buildSettingsForCfg = this->CreateFlatClone(buildSettings);
// Put this last so it can override existing settings
@@ -3006,43 +2976,38 @@ bool cmGlobalXCodeGenerator::CreateXCodeObjects(
d != vars.end(); ++d) {
if (d->find("CMAKE_XCODE_ATTRIBUTE_") == 0) {
std::string attribute = d->substr(22);
- this->FilterConfigurationAttribute(i->first, attribute);
+ this->FilterConfigurationAttribute(config.first, attribute);
if (!attribute.empty()) {
cmGeneratorExpression ge;
std::string processed =
ge.Parse(this->CurrentMakefile->GetDefinition(*d))
- ->Evaluate(this->CurrentLocalGenerator, i->first);
+ ->Evaluate(this->CurrentLocalGenerator, config.first);
buildSettingsForCfg->AddAttribute(attribute,
this->CreateString(processed));
}
}
}
// store per-config buildSettings into configuration object
- i->second->AddAttribute("buildSettings", buildSettingsForCfg);
+ config.second->AddAttribute("buildSettings", buildSettingsForCfg);
}
this->RootObject->AddAttribute("buildConfigurationList",
this->CreateObjectReference(configlist));
std::vector<cmXCodeObject*> targets;
- for (std::vector<cmLocalGenerator*>::iterator i = generators.begin();
- i != generators.end(); ++i) {
- if (!this->CreateXCodeTargets(*i, targets)) {
+ for (auto& generator : generators) {
+ if (!this->CreateXCodeTargets(generator, targets)) {
return false;
}
}
// loop over all targets and add link and depend info
- for (std::vector<cmXCodeObject*>::iterator i = targets.begin();
- i != targets.end(); ++i) {
- cmXCodeObject* t = *i;
+ for (auto t : targets) {
this->AddDependAndLinkInformation(t);
}
this->CreateXCodeDependHackTarget(targets);
// now add all targets to the root object
cmXCodeObject* allTargets = this->CreateObject(cmXCodeObject::OBJECT_LIST);
- for (std::vector<cmXCodeObject*>::iterator i = targets.begin();
- i != targets.end(); ++i) {
- cmXCodeObject* t = *i;
+ for (auto t : targets) {
allTargets->AddObject(t);
cmXCodeObject* productRef = t->GetObject("productReference");
if (productRef) {
@@ -3135,9 +3100,7 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget(
this->CurrentConfigurationTypes.begin();
ct != this->CurrentConfigurationTypes.end(); ++ct) {
std::string configName = *ct;
- for (std::vector<cmXCodeObject*>::iterator i = targets.begin();
- i != targets.end(); ++i) {
- cmXCodeObject* target = *i;
+ for (auto target : targets) {
cmGeneratorTarget* gt = target->GetTarget();
if (gt->GetType() == cmStateEnums::EXECUTABLE ||
@@ -3162,9 +3125,8 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget(
target->GetDependTargets().find(*ct);
if (y != target->GetDependTargets().end()) {
std::vector<std::string> const& deptgts = y->second;
- for (std::vector<std::string>::const_iterator d = deptgts.begin();
- d != deptgts.end(); ++d) {
- makefileStream << this->PostBuildMakeTarget(*d, *ct) << ": "
+ for (auto const& deptgt : deptgts) {
+ makefileStream << this->PostBuildMakeTarget(deptgt, *ct) << ": "
<< trel << "\n";
}
}
@@ -3186,9 +3148,8 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget(
target->GetDependLibraries().find(*ct);
if (x != target->GetDependLibraries().end()) {
std::vector<std::string> const& deplibs = x->second;
- for (std::vector<std::string>::const_iterator d = deplibs.begin();
- d != deplibs.end(); ++d) {
- std::string file = this->ConvertToRelativeForMake(d->c_str());
+ for (auto const& deplib : deplibs) {
+ std::string file = this->ConvertToRelativeForMake(deplib.c_str());
makefileStream << "\\\n\t" << file;
dummyRules.insert(file);
}
@@ -3220,11 +3181,9 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget(
if (this->Architectures.size() > 1) {
std::string universal = this->GetObjectsNormalDirectory(
this->CurrentProject, configName, gt);
- for (std::vector<std::string>::iterator arch =
- this->Architectures.begin();
- arch != this->Architectures.end(); ++arch) {
+ for (auto& architecture : this->Architectures) {
std::string universalFile = universal;
- universalFile += *arch;
+ universalFile += architecture;
universalFile += "/";
universalFile += gt->GetFullName(configName);
makefileStream << "\t/bin/rm -f "
@@ -3241,22 +3200,20 @@ void cmGlobalXCodeGenerator::CreateXCodeDependHackTarget(
makefileStream << "\n\n"
<< "# For each target create a dummy rule"
<< "so the target does not have to exist\n";
- for (std::set<std::string>::const_iterator it = dummyRules.begin();
- it != dummyRules.end(); ++it) {
- makefileStream << *it << ":\n";
+ for (auto const& dummyRule : dummyRules) {
+ makefileStream << dummyRule << ":\n";
}
}
void cmGlobalXCodeGenerator::OutputXCodeProject(
cmLocalGenerator* root, std::vector<cmLocalGenerator*>& generators)
{
- if (generators.size() == 0) {
+ if (generators.empty()) {
return;
}
// Skip local generators that are excluded from this project.
- for (std::vector<cmLocalGenerator*>::iterator g = generators.begin();
- g != generators.end(); ++g) {
- if (this->IsExcluded(root, *g)) {
+ for (auto& generator : generators) {
+ if (this->IsExcluded(root, generator)) {
continue;
}
}
@@ -3298,6 +3255,31 @@ void cmGlobalXCodeGenerator::OutputXCodeProject(
void cmGlobalXCodeGenerator::OutputXCodeSharedSchemes(
const std::string& xcProjDir)
{
+ // collect all tests for the targets
+ std::map<std::string, cmXCodeScheme::TestObjects> testables;
+
+ for (std::vector<cmXCodeObject*>::const_iterator i =
+ this->XCodeObjects.begin();
+ i != this->XCodeObjects.end(); ++i) {
+ cmXCodeObject* obj = *i;
+ if (obj->GetType() != cmXCodeObject::OBJECT ||
+ obj->GetIsA() != cmXCodeObject::PBXNativeTarget) {
+ continue;
+ }
+
+ if (!obj->GetTarget()->IsXCTestOnApple()) {
+ continue;
+ }
+
+ const char* testee = obj->GetTarget()->GetProperty("XCTEST_TESTEE");
+ if (!testee) {
+ continue;
+ }
+
+ testables[testee].push_back(obj);
+ }
+
+ // generate scheme
for (std::vector<cmXCodeObject*>::const_iterator i =
this->XCodeObjects.begin();
i != this->XCodeObjects.end(); ++i) {
@@ -3305,8 +3287,9 @@ void cmGlobalXCodeGenerator::OutputXCodeSharedSchemes(
if (obj->GetType() == cmXCodeObject::OBJECT &&
(obj->GetIsA() == cmXCodeObject::PBXNativeTarget ||
obj->GetIsA() == cmXCodeObject::PBXAggregateTarget)) {
- cmXCodeScheme schm(obj, this->CurrentConfigurationTypes,
- this->XcodeVersion);
+ const std::string& targetName = obj->GetTarget()->GetName();
+ cmXCodeScheme schm(obj, testables[targetName],
+ this->CurrentConfigurationTypes, this->XcodeVersion);
schm.WriteXCodeSharedScheme(xcProjDir,
this->RelativeToSource(xcProjDir.c_str()));
}
@@ -3358,12 +3341,13 @@ void cmGlobalXCodeGenerator::WriteXCodePBXProj(std::ostream& fout,
cmXCodeObject::Indent(1, fout);
fout << "};\n";
cmXCodeObject::Indent(1, fout);
- if (this->XcodeVersion >= 32)
+ if (this->XcodeVersion >= 32) {
fout << "objectVersion = 46;\n";
- else if (this->XcodeVersion >= 31)
+ } else if (this->XcodeVersion >= 31) {
fout << "objectVersion = 45;\n";
- else
+ } else {
fout << "objectVersion = 44;\n";
+ }
cmXCode21Object::PrintList(this->XCodeObjects, fout);
cmXCodeObject::Indent(1, fout);
fout << "rootObject = " << this->RootObject->GetId()
@@ -3483,11 +3467,10 @@ void cmGlobalXCodeGenerator::AppendDefines(
{
// GCC_PREPROCESSOR_DEFINITIONS is a space-separated list of definitions.
std::string def;
- for (std::vector<std::string>::const_iterator di = defines.begin();
- di != defines.end(); ++di) {
+ for (auto const& define : defines) {
// Start with -D if requested.
def = dflag ? "-D" : "";
- def += *di;
+ def += define;
// Append the flag with needed escapes.
std::string tmp;
@@ -3572,7 +3555,7 @@ bool cmGlobalXCodeGenerator::HasKnownObjectFileLocation(
std::string* reason) const
{
if (this->ObjectDirArch.find('$') != std::string::npos) {
- if (reason != CM_NULLPTR) {
+ if (reason != nullptr) {
*reason = " under Xcode with multiple architectures";
}
return false;
diff --git a/Source/cmGlobalXCodeGenerator.h b/Source/cmGlobalXCodeGenerator.h
index e69793bcc..e9ca91ce4 100644
--- a/Source/cmGlobalXCodeGenerator.h
+++ b/Source/cmGlobalXCodeGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmGlobalXCodeGenerator_h
#define cmGlobalXCodeGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <map>
@@ -37,7 +37,7 @@ public:
static cmGlobalGeneratorFactory* NewFactory();
///! Get the name for the generator.
- std::string GetName() const CM_OVERRIDE
+ std::string GetName() const override
{
return cmGlobalXCodeGenerator::GetActualName();
}
@@ -47,14 +47,14 @@ public:
static void GetDocumentation(cmDocumentationEntry& entry);
///! Create a local generator appropriate to this Global Generator
- cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) CM_OVERRIDE;
+ cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) override;
/**
* Try to determine system information such as shared library
* extension, pthreads, byte order etc.
*/
void EnableLanguage(std::vector<std::string> const& languages, cmMakefile*,
- bool optional) CM_OVERRIDE;
+ bool optional) override;
/**
* Try running cmake and building a file. This is used for dynalically
* loaded commands, not as part of the usual build process.
@@ -66,47 +66,48 @@ public:
const std::string& targetName,
const std::string& config, bool fast, bool verbose,
std::vector<std::string> const& makeOptions =
- std::vector<std::string>()) CM_OVERRIDE;
+ std::vector<std::string>()) override;
/** Append the subdirectory for the given configuration. */
void AppendDirectoryForConfig(const std::string& prefix,
const std::string& config,
const std::string& suffix,
- std::string& dir) CM_OVERRIDE;
+ std::string& dir) override;
- bool FindMakeProgram(cmMakefile*) CM_OVERRIDE;
+ bool FindMakeProgram(cmMakefile*) override;
///! What is the configurations directory variable called?
- const char* GetCMakeCFGIntDir() const CM_OVERRIDE;
+ const char* GetCMakeCFGIntDir() const override;
///! expand CFGIntDir
std::string ExpandCFGIntDir(const std::string& str,
- const std::string& config) const CM_OVERRIDE;
+ const std::string& config) const override;
void SetCurrentLocalGenerator(cmLocalGenerator*);
/** Return true if the generated build tree may contain multiple builds.
i.e. "Can I build Debug and Release in the same tree?" */
- bool IsMultiConfig() const CM_OVERRIDE;
+ bool IsMultiConfig() const override;
- bool HasKnownObjectFileLocation(std::string* reason) const CM_OVERRIDE;
+ bool HasKnownObjectFileLocation(std::string* reason) const override;
- bool IsIPOSupported() const CM_OVERRIDE { return true; }
+ bool IsIPOSupported() const override { return true; }
- bool UseEffectivePlatformName(cmMakefile* mf) const CM_OVERRIDE;
+ bool UseEffectivePlatformName(cmMakefile* mf) const override;
- bool ShouldStripResourcePath(cmMakefile*) const CM_OVERRIDE;
+ bool ShouldStripResourcePath(cmMakefile*) const override;
- bool SetGeneratorToolset(std::string const& ts, cmMakefile* mf) CM_OVERRIDE;
+ bool SetGeneratorToolset(std::string const& ts, cmMakefile* mf) override;
void AppendFlag(std::string& flags, std::string const& flag);
protected:
- void AddExtraIDETargets() CM_OVERRIDE;
- void Generate() CM_OVERRIDE;
+ void AddExtraIDETargets() override;
+ void Generate() override;
private:
cmXCodeObject* CreateOrGetPBXGroup(cmGeneratorTarget* gtgt,
cmSourceGroup* sg);
- cmXCodeObject* CreatePBXGroup(cmXCodeObject* parent, std::string name);
+ cmXCodeObject* CreatePBXGroup(cmXCodeObject* parent,
+ const std::string& name);
bool CreateGroups(std::vector<cmLocalGenerator*>& generators);
std::string XCodeEscapePath(const std::string& p);
std::string RelativeToSource(const char* p);
@@ -144,7 +145,7 @@ private:
cmXCodeObject* CreateFlatClone(cmXCodeObject*);
cmXCodeObject* CreateXCodeTarget(cmGeneratorTarget* gtgt,
cmXCodeObject* buildPhases);
- void ForceLinkerLanguages() CM_OVERRIDE;
+ void ForceLinkerLanguages() override;
void ForceLinkerLanguage(cmGeneratorTarget* gtgt);
const char* GetTargetLinkFlagsVar(const cmGeneratorTarget* target) const;
const char* GetTargetFileType(cmGeneratorTarget* target);
@@ -219,11 +220,11 @@ private:
std::vector<std::string> const& defines,
bool dflag = false);
- void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const CM_OVERRIDE;
+ void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const override;
protected:
- const char* GetInstallTargetName() const CM_OVERRIDE { return "install"; }
- const char* GetPackageTargetName() const CM_OVERRIDE { return "package"; }
+ const char* GetInstallTargetName() const override { return "install"; }
+ const char* GetPackageTargetName() const override { return "package"; }
unsigned int XcodeVersion;
std::string VersionString;
@@ -238,7 +239,7 @@ private:
bool XcodeBuildCommandInitialized;
void PrintCompilerAdvice(std::ostream&, std::string const&,
- const char*) const CM_OVERRIDE
+ const char*) const override
{
}
diff --git a/Source/cmGraphVizWriter.cxx b/Source/cmGraphVizWriter.cxx
index 7e953cef1..dd2993d70 100644
--- a/Source/cmGraphVizWriter.cxx
+++ b/Source/cmGraphVizWriter.cxx
@@ -2,8 +2,9 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmGraphVizWriter.h"
-#include "cmConfigure.h"
+#include <cstddef>
#include <iostream>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <utility>
@@ -15,10 +16,20 @@
#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
-static const char* getShapeForTarget(const cmGeneratorTarget* target)
+namespace {
+enum LinkLibraryScopeType
+{
+ LLT_SCOPE_PUBLIC,
+ LLT_SCOPE_PRIVATE,
+ LLT_SCOPE_INTERFACE
+};
+
+const char* const GRAPHVIZ_PRIVATE_EDEGE_STYLE = "dashed";
+const char* const GRAPHVIZ_INTERFACE_EDEGE_STYLE = "dotted";
+
+const char* getShapeForTarget(const cmGeneratorTarget* target)
{
if (!target) {
return "ellipse";
@@ -40,6 +51,76 @@ static const char* getShapeForTarget(const cmGeneratorTarget* target)
return "box";
}
+std::map<std::string, LinkLibraryScopeType> getScopedLinkLibrariesFromTarget(
+ cmTarget* Target)
+{
+ char sep = ';';
+ std::map<std::string, LinkLibraryScopeType> tokens;
+ size_t start = 0, end = 0;
+
+ const char* pInterfaceLinkLibraries =
+ Target->GetProperty("INTERFACE_LINK_LIBRARIES");
+ const char* pLinkLibraries = Target->GetProperty("LINK_LIBRARIES");
+
+ if (!pInterfaceLinkLibraries && !pLinkLibraries) {
+ return tokens; // target is not linked against any other libraries
+ }
+
+ // make sure we don't touch a null-ptr
+ auto interfaceLinkLibraries =
+ std::string(pInterfaceLinkLibraries ? pInterfaceLinkLibraries : "");
+ auto linkLibraries = std::string(pLinkLibraries ? pLinkLibraries : "");
+
+ // first extract interfaceLinkLibraries
+ while (start < interfaceLinkLibraries.length()) {
+
+ if ((end = interfaceLinkLibraries.find(sep, start)) == std::string::npos) {
+ end = interfaceLinkLibraries.length();
+ }
+
+ std::string element = interfaceLinkLibraries.substr(start, end - start);
+ if (std::string::npos == element.find("$<LINK_ONLY:", 0)) {
+ // we assume first, that this library is an interface library.
+ // if we find it again in the linklibraries property, we promote it to an
+ // public library.
+ tokens[element] = LLT_SCOPE_INTERFACE;
+ } else {
+ // this is an private linked static library.
+ // we take care of this case in the second iterator.
+ }
+ start = end + 1;
+ }
+
+ // second extract linkLibraries
+ start = 0;
+ while (start < linkLibraries.length()) {
+
+ if ((end = linkLibraries.find(sep, start)) == std::string::npos) {
+ end = linkLibraries.length();
+ }
+
+ std::string element = linkLibraries.substr(start, end - start);
+
+ if (tokens.find(element) == tokens.end()) {
+ // this library is not found in interfaceLinkLibraries but in
+ // linkLibraries.
+ // this results in a private linked library.
+ tokens[element] = LLT_SCOPE_PRIVATE;
+ } else if (LLT_SCOPE_INTERFACE == tokens[element]) {
+ // this library is found in interfaceLinkLibraries and linkLibraries.
+ // this results in a public linked library.
+ tokens[element] = LLT_SCOPE_PUBLIC;
+ } else {
+ // private and public linked libraries should not be changed anymore.
+ }
+
+ start = end + 1;
+ }
+
+ return tokens;
+}
+}
+
cmGraphVizWriter::cmGraphVizWriter(
const std::vector<cmLocalGenerator*>& localGenerators)
: GraphType("digraph")
@@ -66,8 +147,8 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName,
cm.SetHomeOutputDirectory("");
cm.GetCurrentSnapshot().SetDefaultDefinitions();
cmGlobalGenerator ggi(&cm);
- CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&ggi, cm.GetCurrentSnapshot()));
- CM_AUTO_PTR<cmLocalGenerator> lg(ggi.CreateLocalGenerator(mf.get()));
+ cmMakefile mf(&ggi, cm.GetCurrentSnapshot());
+ std::unique_ptr<cmLocalGenerator> lg(ggi.CreateLocalGenerator(&mf));
const char* inFileName = settingsFileName;
@@ -78,7 +159,7 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName,
}
}
- if (!mf->ReadListFile(inFileName)) {
+ if (!mf.ReadListFile(inFileName)) {
cmSystemTools::Error("Problem opening GraphViz options file: ",
inFileName);
return;
@@ -88,7 +169,7 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName,
#define __set_if_set(var, cmakeDefinition) \
{ \
- const char* value = mf->GetDefinition(cmakeDefinition); \
+ const char* value = mf.GetDefinition(cmakeDefinition); \
if (value) { \
(var) = value; \
} \
@@ -101,9 +182,9 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName,
#define __set_bool_if_set(var, cmakeDefinition) \
{ \
- const char* value = mf->GetDefinition(cmakeDefinition); \
+ const char* value = mf.GetDefinition(cmakeDefinition); \
if (value) { \
- (var) = mf->IsOn(cmakeDefinition); \
+ (var) = mf.IsOn(cmakeDefinition); \
} \
}
@@ -123,10 +204,7 @@ void cmGraphVizWriter::ReadSettings(const char* settingsFileName,
std::vector<std::string> ignoreTargetsRegExVector;
cmSystemTools::ExpandListArgument(ignoreTargetsRegexes,
ignoreTargetsRegExVector);
- for (std::vector<std::string>::const_iterator itvIt =
- ignoreTargetsRegExVector.begin();
- itvIt != ignoreTargetsRegExVector.end(); ++itvIt) {
- std::string currentRegexString(*itvIt);
+ for (std::string const& currentRegexString : ignoreTargetsRegExVector) {
cmsys::RegularExpression currentRegex;
if (!currentRegex.compile(currentRegexString.c_str())) {
std::cerr << "Could not compile bad regex \"" << currentRegexString
@@ -147,20 +225,18 @@ void cmGraphVizWriter::WriteTargetDependersFiles(const char* fileName)
this->CollectTargetsAndLibs();
- for (std::map<std::string, const cmGeneratorTarget*>::const_iterator ptrIt =
- this->TargetPtrs.begin();
- ptrIt != this->TargetPtrs.end(); ++ptrIt) {
- if (ptrIt->second == CM_NULLPTR) {
+ for (auto const& ptr : this->TargetPtrs) {
+ if (ptr.second == nullptr) {
continue;
}
- if (!this->GenerateForTargetType(ptrIt->second->GetType())) {
+ if (!this->GenerateForTargetType(ptr.second->GetType())) {
continue;
}
std::string currentFilename = fileName;
currentFilename += ".";
- currentFilename += ptrIt->first;
+ currentFilename += ptr.first;
currentFilename += ".dependers";
cmGeneratedFileStream str(currentFilename.c_str());
@@ -174,7 +250,7 @@ void cmGraphVizWriter::WriteTargetDependersFiles(const char* fileName)
std::cout << "Writing " << currentFilename << "..." << std::endl;
this->WriteHeader(str);
- this->WriteDependerConnections(ptrIt->first, insertedNodes,
+ this->WriteDependerConnections(ptr.first, insertedNodes,
insertedConnections, str);
this->WriteFooter(str);
@@ -191,14 +267,12 @@ void cmGraphVizWriter::WritePerTargetFiles(const char* fileName)
this->CollectTargetsAndLibs();
- for (std::map<std::string, const cmGeneratorTarget*>::const_iterator ptrIt =
- this->TargetPtrs.begin();
- ptrIt != this->TargetPtrs.end(); ++ptrIt) {
- if (ptrIt->second == CM_NULLPTR) {
+ for (auto const& ptr : this->TargetPtrs) {
+ if (ptr.second == nullptr) {
continue;
}
- if (!this->GenerateForTargetType(ptrIt->second->GetType())) {
+ if (!this->GenerateForTargetType(ptr.second->GetType())) {
continue;
}
@@ -207,7 +281,7 @@ void cmGraphVizWriter::WritePerTargetFiles(const char* fileName)
std::string currentFilename = fileName;
currentFilename += ".";
- currentFilename += ptrIt->first;
+ currentFilename += ptr.first;
cmGeneratedFileStream str(currentFilename.c_str());
if (!str) {
return;
@@ -216,8 +290,7 @@ void cmGraphVizWriter::WritePerTargetFiles(const char* fileName)
std::cout << "Writing " << currentFilename << "..." << std::endl;
this->WriteHeader(str);
- this->WriteConnections(ptrIt->first, insertedNodes, insertedConnections,
- str);
+ this->WriteConnections(ptr.first, insertedNodes, insertedConnections, str);
this->WriteFooter(str);
}
}
@@ -237,19 +310,16 @@ void cmGraphVizWriter::WriteGlobalFile(const char* fileName)
std::set<std::string> insertedConnections;
std::set<std::string> insertedNodes;
- for (std::map<std::string, const cmGeneratorTarget*>::const_iterator ptrIt =
- this->TargetPtrs.begin();
- ptrIt != this->TargetPtrs.end(); ++ptrIt) {
- if (ptrIt->second == CM_NULLPTR) {
+ for (auto const& ptr : this->TargetPtrs) {
+ if (ptr.second == nullptr) {
continue;
}
- if (!this->GenerateForTargetType(ptrIt->second->GetType())) {
+ if (!this->GenerateForTargetType(ptr.second->GetType())) {
continue;
}
- this->WriteConnections(ptrIt->first, insertedNodes, insertedConnections,
- str);
+ this->WriteConnections(ptr.first, insertedNodes, insertedConnections, str);
}
this->WriteFooter(str);
}
@@ -279,19 +349,17 @@ void cmGraphVizWriter::WriteConnections(
this->WriteNode(targetName, targetPtrIt->second, insertedNodes, str);
- if (targetPtrIt->second == CM_NULLPTR) // it's an external library
+ if (targetPtrIt->second == nullptr) // it's an external library
{
return;
}
std::string myNodeName = this->TargetNamesNodes.find(targetName)->second;
+ std::map<std::string, LinkLibraryScopeType> ll =
+ getScopedLinkLibrariesFromTarget(targetPtrIt->second->Target);
- const cmTarget::LinkLibraryVectorType* ll =
- &(targetPtrIt->second->Target->GetOriginalLinkLibraries());
-
- for (cmTarget::LinkLibraryVectorType::const_iterator llit = ll->begin();
- llit != ll->end(); ++llit) {
- const char* libName = llit->first.c_str();
+ for (auto const& llit : ll) {
+ const char* libName = llit.first.c_str();
std::map<std::string, std::string>::const_iterator libNameIt =
this->TargetNamesNodes.find(libName);
@@ -310,6 +378,18 @@ void cmGraphVizWriter::WriteConnections(
insertedNodes, str);
str << " \"" << myNodeName << "\" -> \"" << libNameIt->second << "\"";
+
+ switch (llit.second) {
+ case LLT_SCOPE_PRIVATE:
+ str << "[style = " << GRAPHVIZ_PRIVATE_EDEGE_STYLE << "]";
+ break;
+ case LLT_SCOPE_INTERFACE:
+ str << "[style = " << GRAPHVIZ_INTERFACE_EDEGE_STYLE << "]";
+ break;
+ default:
+ break;
+ }
+
str << " // " << targetName << " -> " << libName << std::endl;
this->WriteConnections(libName, insertedNodes, insertedConnections, str);
}
@@ -330,7 +410,7 @@ void cmGraphVizWriter::WriteDependerConnections(
this->WriteNode(targetName, targetPtrIt->second, insertedNodes, str);
- if (targetPtrIt->second == CM_NULLPTR) // it's an external library
+ if (targetPtrIt->second == nullptr) // it's an external library
{
return;
}
@@ -338,29 +418,26 @@ void cmGraphVizWriter::WriteDependerConnections(
std::string myNodeName = this->TargetNamesNodes.find(targetName)->second;
// now search who links against me
- for (std::map<std::string, const cmGeneratorTarget*>::const_iterator
- dependerIt = this->TargetPtrs.begin();
- dependerIt != this->TargetPtrs.end(); ++dependerIt) {
- if (dependerIt->second == CM_NULLPTR) {
+ for (auto const& tptr : this->TargetPtrs) {
+ if (tptr.second == nullptr) {
continue;
}
- if (!this->GenerateForTargetType(dependerIt->second->GetType())) {
+ if (!this->GenerateForTargetType(tptr.second->GetType())) {
continue;
}
// Now we have a target, check whether it links against targetName.
// If so, draw a connection, and then continue with dependers on that one.
const cmTarget::LinkLibraryVectorType* ll =
- &(dependerIt->second->Target->GetOriginalLinkLibraries());
+ &(tptr.second->Target->GetOriginalLinkLibraries());
- for (cmTarget::LinkLibraryVectorType::const_iterator llit = ll->begin();
- llit != ll->end(); ++llit) {
- std::string libName = llit->first;
+ for (auto const& llit : *ll) {
+ std::string libName = llit.first;
if (libName == targetName) {
// So this target links against targetName.
std::map<std::string, std::string>::const_iterator dependerNodeNameIt =
- this->TargetNamesNodes.find(dependerIt->first);
+ this->TargetNamesNodes.find(tptr.first);
if (dependerNodeNameIt != this->TargetNamesNodes.end()) {
std::string connectionName = dependerNodeNameIt->second;
@@ -370,14 +447,12 @@ void cmGraphVizWriter::WriteDependerConnections(
if (insertedConnections.find(connectionName) ==
insertedConnections.end()) {
insertedConnections.insert(connectionName);
- this->WriteNode(dependerIt->first, dependerIt->second,
- insertedNodes, str);
+ this->WriteNode(tptr.first, tptr.second, insertedNodes, str);
str << " \"" << dependerNodeNameIt->second << "\" -> \""
<< myNodeName << "\"";
- str << " // " << targetName << " -> " << dependerIt->first
- << std::endl;
- this->WriteDependerConnections(dependerIt->first, insertedNodes,
+ str << " // " << targetName << " -> " << tptr.first << std::endl;
+ this->WriteDependerConnections(tptr.first, insertedNodes,
insertedConnections, str);
}
}
@@ -417,13 +492,10 @@ int cmGraphVizWriter::CollectAllTargets()
{
int cnt = 0;
// First pass get the list of all cmake targets
- for (std::vector<cmLocalGenerator*>::const_iterator lit =
- this->LocalGenerators.begin();
- lit != this->LocalGenerators.end(); ++lit) {
- std::vector<cmGeneratorTarget*> targets = (*lit)->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::const_iterator it = targets.begin();
- it != targets.end(); ++it) {
- const char* realTargetName = (*it)->GetName().c_str();
+ for (cmLocalGenerator* lg : this->LocalGenerators) {
+ const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
+ const char* realTargetName = target->GetName().c_str();
if (this->IgnoreThisTarget(realTargetName)) {
// Skip ignored targets
continue;
@@ -432,7 +504,7 @@ int cmGraphVizWriter::CollectAllTargets()
std::ostringstream ostr;
ostr << this->GraphNodePrefix << cnt++;
this->TargetNamesNodes[realTargetName] = ostr.str();
- this->TargetPtrs[realTargetName] = *it;
+ this->TargetPtrs[realTargetName] = target;
}
}
@@ -442,22 +514,18 @@ int cmGraphVizWriter::CollectAllTargets()
int cmGraphVizWriter::CollectAllExternalLibs(int cnt)
{
// Ok, now find all the stuff we link to that is not in cmake
- for (std::vector<cmLocalGenerator*>::const_iterator lit =
- this->LocalGenerators.begin();
- lit != this->LocalGenerators.end(); ++lit) {
- std::vector<cmGeneratorTarget*> targets = (*lit)->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::const_iterator it = targets.begin();
- it != targets.end(); ++it) {
- const char* realTargetName = (*it)->GetName().c_str();
+ for (cmLocalGenerator* lg : this->LocalGenerators) {
+ const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
+ const char* realTargetName = target->GetName().c_str();
if (this->IgnoreThisTarget(realTargetName)) {
// Skip ignored targets
continue;
}
const cmTarget::LinkLibraryVectorType* ll =
- &((*it)->Target->GetOriginalLinkLibraries());
- for (cmTarget::LinkLibraryVectorType::const_iterator llit = ll->begin();
- llit != ll->end(); ++llit) {
- const char* libName = llit->first.c_str();
+ &(target->Target->GetOriginalLinkLibraries());
+ for (auto const& llit : *ll) {
+ const char* libName = llit.first.c_str();
if (this->IgnoreThisTarget(libName)) {
// Skip ignored targets
continue;
@@ -469,7 +537,7 @@ int cmGraphVizWriter::CollectAllExternalLibs(int cnt)
std::ostringstream ostr;
ostr << this->GraphNodePrefix << cnt++;
this->TargetNamesNodes[libName] = ostr.str();
- this->TargetPtrs[libName] = CM_NULLPTR;
+ this->TargetPtrs[libName] = nullptr;
// str << " \"" << ostr << "\" [ label=\"" << libName
// << "\" shape=\"ellipse\"];" << std::endl;
}
@@ -481,10 +549,7 @@ int cmGraphVizWriter::CollectAllExternalLibs(int cnt)
bool cmGraphVizWriter::IgnoreThisTarget(const std::string& name)
{
- for (std::vector<cmsys::RegularExpression>::iterator itvIt =
- this->TargetsToIgnoreRegex.begin();
- itvIt != this->TargetsToIgnoreRegex.end(); ++itvIt) {
- cmsys::RegularExpression& regEx = *itvIt;
+ for (cmsys::RegularExpression& regEx : this->TargetsToIgnoreRegex) {
if (regEx.is_valid()) {
if (regEx.find(name)) {
return true;
diff --git a/Source/cmHexFileConverter.cxx b/Source/cmHexFileConverter.cxx
index 78dceb794..8deb8c183 100644
--- a/Source/cmHexFileConverter.cxx
+++ b/Source/cmHexFileConverter.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmHexFileConverter.h"
-#include "cmConfigure.h"
#include <stdio.h>
#include <string.h>
@@ -22,7 +21,7 @@ static bool cm_IsHexChar(char c)
static unsigned int ChompStrlen(const char* line)
{
- if (line == CM_NULLPTR) {
+ if (line == nullptr) {
return 0;
}
unsigned int length = static_cast<unsigned int>(strlen(line));
@@ -139,7 +138,7 @@ cmHexFileConverter::FileType cmHexFileConverter::DetermineFileType(
{
char buf[1024];
FILE* inFile = cmsys::SystemTools::Fopen(inFileName, "rb");
- if (inFile == CM_NULLPTR) {
+ if (inFile == nullptr) {
return Binary;
}
@@ -188,11 +187,11 @@ bool cmHexFileConverter::TryConvert(const char* inFileName,
// try to open the file
FILE* inFile = cmsys::SystemTools::Fopen(inFileName, "rb");
FILE* outFile = cmsys::SystemTools::Fopen(outFileName, "wb");
- if ((inFile == CM_NULLPTR) || (outFile == CM_NULLPTR)) {
- if (inFile != CM_NULLPTR) {
+ if ((inFile == nullptr) || (outFile == nullptr)) {
+ if (inFile != nullptr) {
fclose(inFile);
}
- if (outFile != CM_NULLPTR) {
+ if (outFile != nullptr) {
fclose(outFile);
}
return false;
@@ -201,7 +200,7 @@ bool cmHexFileConverter::TryConvert(const char* inFileName,
// convert them line by line
bool success = false;
char buf[1024];
- while (fgets(buf, 1024, inFile) != CM_NULLPTR) {
+ while (fgets(buf, 1024, inFile) != nullptr) {
if (type == MotorolaSrec) {
success = ConvertMotorolaSrecLine(buf, outFile);
} else if (type == IntelHex) {
diff --git a/Source/cmHexFileConverter.h b/Source/cmHexFileConverter.h
index 1050bc1b4..25278e4a3 100644
--- a/Source/cmHexFileConverter.h
+++ b/Source/cmHexFileConverter.h
@@ -3,6 +3,8 @@
#ifndef cmHexFileConverter_h
#define cmHexFileConverter_h
+#include "cmConfigure.h" // IWYU pragma: keep
+
/** \class cmHexFileConverter
* \brief Can detects Intel Hex and Motorola S-record files and convert them
* to binary files.
diff --git a/Source/cmIDEOptions.h b/Source/cmIDEOptions.h
index 19e96bd44..af0312874 100644
--- a/Source/cmIDEOptions.h
+++ b/Source/cmIDEOptions.h
@@ -3,7 +3,7 @@
#ifndef cmIDEOptions_h
#define cmIDEOptions_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <map>
#include <string>
diff --git a/Source/cmIfCommand.cxx b/Source/cmIfCommand.cxx
index 0972664a2..4926f22d0 100644
--- a/Source/cmIfCommand.cxx
+++ b/Source/cmIfCommand.cxx
@@ -8,17 +8,17 @@
#include "cmMakefile.h"
#include "cmOutputConverter.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
+#include <memory> // IWYU pragma: keep
+
static std::string cmIfCommandError(
std::vector<cmExpandedCommandArgument> const& args)
{
std::string err = "given arguments:\n ";
- for (std::vector<cmExpandedCommandArgument>::const_iterator i = args.begin();
- i != args.end(); ++i) {
+ for (cmExpandedCommandArgument const& i : args) {
err += " ";
- err += cmOutputConverter::EscapeForCMake(i->GetValue());
+ err += cmOutputConverter::EscapeForCMake(i.GetValue());
}
err += "\n";
return err;
@@ -37,7 +37,8 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
// if this is the endif for this if statement, then start executing
if (!this->ScopeDepth) {
// Remove the function blocker for this scope or bail.
- CM_AUTO_PTR<cmFunctionBlocker> fb(mf.RemoveFunctionBlocker(this, lff));
+ std::unique_ptr<cmFunctionBlocker> fb(
+ mf.RemoveFunctionBlocker(this, lff));
if (!fb.get()) {
return false;
}
@@ -45,21 +46,20 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
// execute the functions for the true parts of the if statement
cmExecutionStatus status;
int scopeDepth = 0;
- for (unsigned int c = 0; c < this->Functions.size(); ++c) {
+ for (cmListFileFunction const& func : this->Functions) {
// keep track of scope depth
- if (!cmSystemTools::Strucmp(this->Functions[c].Name.c_str(), "if")) {
+ if (!cmSystemTools::Strucmp(func.Name.c_str(), "if")) {
scopeDepth++;
}
- if (!cmSystemTools::Strucmp(this->Functions[c].Name.c_str(),
- "endif")) {
+ if (!cmSystemTools::Strucmp(func.Name.c_str(), "endif")) {
scopeDepth--;
}
// watch for our state change
if (scopeDepth == 0 &&
- !cmSystemTools::Strucmp(this->Functions[c].Name.c_str(), "else")) {
+ !cmSystemTools::Strucmp(func.Name.c_str(), "else")) {
if (this->ElseSeen) {
- cmListFileBacktrace bt = mf.GetBacktrace(this->Functions[c]);
+ cmListFileBacktrace bt = mf.GetBacktrace(func);
mf.GetCMakeInstance()->IssueMessage(
cmake::FATAL_ERROR,
"A duplicate ELSE command was found inside an IF block.", bt);
@@ -74,13 +74,12 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
// if trace is enabled, print a (trivially) evaluated "else"
// statement
if (!this->IsBlocking && mf.GetCMakeInstance()->GetTrace()) {
- mf.PrintCommandTrace(this->Functions[c]);
+ mf.PrintCommandTrace(func);
}
} else if (scopeDepth == 0 &&
- !cmSystemTools::Strucmp(this->Functions[c].Name.c_str(),
- "elseif")) {
+ !cmSystemTools::Strucmp(func.Name.c_str(), "elseif")) {
if (this->ElseSeen) {
- cmListFileBacktrace bt = mf.GetBacktrace(this->Functions[c]);
+ cmListFileBacktrace bt = mf.GetBacktrace(func);
mf.GetCMakeInstance()->IssueMessage(
cmake::FATAL_ERROR,
"An ELSEIF command was found after an ELSE command.", bt);
@@ -93,23 +92,22 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
} else {
// if trace is enabled, print the evaluated "elseif" statement
if (mf.GetCMakeInstance()->GetTrace()) {
- mf.PrintCommandTrace(this->Functions[c]);
+ mf.PrintCommandTrace(func);
}
std::string errorString;
std::vector<cmExpandedCommandArgument> expandedArguments;
- mf.ExpandArguments(this->Functions[c].Arguments,
- expandedArguments);
+ mf.ExpandArguments(func.Arguments, expandedArguments);
cmake::MessageType messType;
cmListFileContext conditionContext =
cmListFileContext::FromCommandContext(
- this->Functions[c], this->GetStartingContext().FilePath);
+ func, this->GetStartingContext().FilePath);
- cmConditionEvaluator conditionEvaluator(
- mf, conditionContext, mf.GetBacktrace(this->Functions[c]));
+ cmConditionEvaluator conditionEvaluator(mf, conditionContext,
+ mf.GetBacktrace(func));
bool isTrue = conditionEvaluator.IsTrue(expandedArguments,
errorString, messType);
@@ -117,7 +115,7 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
if (!errorString.empty()) {
std::string err = cmIfCommandError(expandedArguments);
err += errorString;
- cmListFileBacktrace bt = mf.GetBacktrace(this->Functions[c]);
+ cmListFileBacktrace bt = mf.GetBacktrace(func);
mf.GetCMakeInstance()->IssueMessage(messType, err, bt);
if (messType == cmake::FATAL_ERROR) {
cmSystemTools::SetFatalErrorOccured();
@@ -135,7 +133,7 @@ bool cmIfFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
// should we execute?
else if (!this->IsBlocking) {
status.Clear();
- mf.ExecuteCommand(this->Functions[c], status);
+ mf.ExecuteCommand(func, status);
if (status.GetReturnInvoked()) {
inStatus.SetReturnInvoked();
return true;
diff --git a/Source/cmIfCommand.h b/Source/cmIfCommand.h
index 5877a7d12..e3d30ddbd 100644
--- a/Source/cmIfCommand.h
+++ b/Source/cmIfCommand.h
@@ -3,7 +3,7 @@
#ifndef cmIfCommand_h
#define cmIfCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -25,10 +25,10 @@ public:
this->ElseSeen = false;
this->ScopeDepth = 0;
}
- ~cmIfFunctionBlocker() CM_OVERRIDE {}
+ ~cmIfFunctionBlocker() override {}
bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf,
- cmExecutionStatus&) CM_OVERRIDE;
- bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) CM_OVERRIDE;
+ cmExecutionStatus&) override;
+ bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) override;
std::vector<cmListFileArgument> Args;
std::vector<cmListFileFunction> Functions;
@@ -45,21 +45,21 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmIfCommand; }
+ cmCommand* Clone() override { return new cmIfCommand; }
/**
* This overrides the default InvokeInitialPass implementation.
* It records the arguments before expansion.
*/
bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
- cmExecutionStatus&) CM_OVERRIDE;
+ cmExecutionStatus&) override;
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const&,
- cmExecutionStatus&) CM_OVERRIDE
+ cmExecutionStatus&) override
{
return false;
}
diff --git a/Source/cmIncludeCommand.cxx b/Source/cmIncludeCommand.cxx
index 12e0c9ab3..cd4d85030 100644
--- a/Source/cmIncludeCommand.cxx
+++ b/Source/cmIncludeCommand.cxx
@@ -78,7 +78,7 @@ bool cmIncludeCommand::InitialPass(std::vector<std::string> const& args,
cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
if (gg->IsExportedTargetsFile(fname_abs)) {
- const char* modal = CM_NULLPTR;
+ const char* modal = nullptr;
std::ostringstream e;
cmake::MessageType messageType = cmake::AUTHOR_WARNING;
diff --git a/Source/cmIncludeCommand.h b/Source/cmIncludeCommand.h
index 16dda0ef5..3b843b206 100644
--- a/Source/cmIncludeCommand.h
+++ b/Source/cmIncludeCommand.h
@@ -3,7 +3,7 @@
#ifndef cmIncludeCommand_h
#define cmIncludeCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmIncludeCommand; }
+ cmCommand* Clone() override { return new cmIncludeCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmIncludeDirectoryCommand.cxx b/Source/cmIncludeDirectoryCommand.cxx
index b81f7cb2d..4c3060797 100644
--- a/Source/cmIncludeDirectoryCommand.cxx
+++ b/Source/cmIncludeDirectoryCommand.cxx
@@ -116,7 +116,7 @@ void cmIncludeDirectoryCommand::NormalizeInclude(std::string& inc)
if ((b != std::string::npos) && (e != std::string::npos)) {
inc.assign(inc, b, 1 + e - b); // copy the remaining substring
} else {
- inc = "";
+ inc.clear();
return;
}
diff --git a/Source/cmIncludeDirectoryCommand.h b/Source/cmIncludeDirectoryCommand.h
index 12de698cb..01d98dbc0 100644
--- a/Source/cmIncludeDirectoryCommand.h
+++ b/Source/cmIncludeDirectoryCommand.h
@@ -3,7 +3,7 @@
#ifndef cmIncludeDirectoryCommand_h
#define cmIncludeDirectoryCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmIncludeDirectoryCommand; }
+ cmCommand* Clone() override { return new cmIncludeDirectoryCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
protected:
// used internally
diff --git a/Source/cmIncludeExternalMSProjectCommand.cxx b/Source/cmIncludeExternalMSProjectCommand.cxx
index 03388c7e9..bd16b1d92 100644
--- a/Source/cmIncludeExternalMSProjectCommand.cxx
+++ b/Source/cmIncludeExternalMSProjectCommand.cxx
@@ -91,9 +91,8 @@ bool cmIncludeExternalMSProjectCommand::InitialPass(
if (!platformMapping.empty())
target->SetProperty("VS_PLATFORM_MAPPING", platformMapping.c_str());
- for (std::vector<std::string>::const_iterator it = depends.begin();
- it != depends.end(); ++it) {
- target->AddUtility(it->c_str());
+ for (std::string const& d : depends) {
+ target->AddUtility(d.c_str());
}
}
#endif
diff --git a/Source/cmIncludeExternalMSProjectCommand.h b/Source/cmIncludeExternalMSProjectCommand.h
index 375646fa6..945acdc13 100644
--- a/Source/cmIncludeExternalMSProjectCommand.h
+++ b/Source/cmIncludeExternalMSProjectCommand.h
@@ -3,7 +3,7 @@
#ifndef cmIncludeExternalMSProjectCommand_h
#define cmIncludeExternalMSProjectCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -25,17 +25,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
- {
- return new cmIncludeExternalMSProjectCommand;
- }
+ cmCommand* Clone() override { return new cmIncludeExternalMSProjectCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmIncludeGuardCommand.cxx b/Source/cmIncludeGuardCommand.cxx
new file mode 100644
index 000000000..505b07cad
--- /dev/null
+++ b/Source/cmIncludeGuardCommand.cxx
@@ -0,0 +1,108 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmIncludeGuardCommand.h"
+
+#include "cmExecutionStatus.h"
+#include "cmMakefile.h"
+#include "cmStateDirectory.h"
+#include "cmStateSnapshot.h"
+#include "cmSystemTools.h"
+#include "cmake.h"
+
+namespace {
+
+enum IncludeGuardScope
+{
+ VARIABLE,
+ DIRECTORY,
+ GLOBAL
+};
+
+std::string GetIncludeGuardVariableName(std::string const& filePath)
+{
+ std::string result = "__INCGUARD_";
+#ifdef CMAKE_BUILD_WITH_CMAKE
+ result += cmSystemTools::ComputeStringMD5(filePath);
+#else
+ result += cmSystemTools::MakeCidentifier(filePath);
+#endif
+ result += "__";
+ return result;
+}
+
+bool CheckIncludeGuardIsSet(cmMakefile* mf, std::string const& includeGuardVar)
+{
+ if (mf->GetProperty(includeGuardVar)) {
+ return true;
+ }
+ cmStateSnapshot dirSnapshot =
+ mf->GetStateSnapshot().GetBuildsystemDirectoryParent();
+ while (dirSnapshot.GetState()) {
+ cmStateDirectory stateDir = dirSnapshot.GetDirectory();
+ if (stateDir.GetProperty(includeGuardVar)) {
+ return true;
+ }
+ dirSnapshot = dirSnapshot.GetBuildsystemDirectoryParent();
+ }
+ return false;
+}
+
+} // anonymous namespace
+
+// cmIncludeGuardCommand
+bool cmIncludeGuardCommand::InitialPass(std::vector<std::string> const& args,
+ cmExecutionStatus& status)
+{
+ if (args.size() > 1) {
+ this->SetError(
+ "given an invalid number of arguments. The command takes at "
+ "most 1 argument.");
+ return false;
+ }
+
+ IncludeGuardScope scope = VARIABLE;
+
+ if (!args.empty()) {
+ std::string const& arg = args[0];
+ if (arg == "DIRECTORY") {
+ scope = DIRECTORY;
+ } else if (arg == "GLOBAL") {
+ scope = GLOBAL;
+ } else {
+ this->SetError("given an invalid scope: " + arg);
+ return false;
+ }
+ }
+
+ std::string includeGuardVar = GetIncludeGuardVariableName(
+ this->Makefile->GetDefinition("CMAKE_CURRENT_LIST_FILE"));
+
+ cmMakefile* const mf = this->Makefile;
+
+ switch (scope) {
+ case VARIABLE:
+ if (mf->IsDefinitionSet(includeGuardVar)) {
+ status.SetReturnInvoked();
+ return true;
+ }
+ mf->AddDefinition(includeGuardVar, true);
+ break;
+ case DIRECTORY:
+ if (CheckIncludeGuardIsSet(mf, includeGuardVar)) {
+ status.SetReturnInvoked();
+ return true;
+ }
+ mf->SetProperty(includeGuardVar, "TRUE");
+ break;
+ case GLOBAL:
+ cmake* const cm = mf->GetCMakeInstance();
+ if (cm->GetProperty(includeGuardVar)) {
+ status.SetReturnInvoked();
+ return true;
+ }
+ cm->SetProperty(includeGuardVar, "TRUE");
+ break;
+ }
+
+ return true;
+}
diff --git a/Source/cmIncludeGuardCommand.h b/Source/cmIncludeGuardCommand.h
new file mode 100644
index 000000000..eaad9b89a
--- /dev/null
+++ b/Source/cmIncludeGuardCommand.h
@@ -0,0 +1,37 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmIncludeGuardCommand_h
+#define cmIncludeGuardCommand_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+#include "cmCommand.h"
+
+class cmExecutionStatus;
+
+/** \class cmIncludeGuardCommand
+ * \brief cmIncludeGuardCommand identical to C++ #pragma_once command
+ * Can work in 3 modes: GLOBAL (works on global properties),
+ * DIRECTORY(use directory property), VARIABLE(unnamed overload without
+ * arguments) define an ordinary variable to be used as include guard checker
+ */
+class cmIncludeGuardCommand : public cmCommand
+{
+public:
+ /**
+ * This is a virtual constructor for the command.
+ */
+ cmCommand* Clone() override { return new cmIncludeGuardCommand; }
+
+ /**
+ * This is called when the command is first encountered in
+ * the CMakeLists.txt file.
+ */
+ bool InitialPass(std::vector<std::string> const& args,
+ cmExecutionStatus& status) override;
+};
+
+#endif
diff --git a/Source/cmIncludeRegularExpressionCommand.h b/Source/cmIncludeRegularExpressionCommand.h
index bac4b8fc3..8da991d08 100644
--- a/Source/cmIncludeRegularExpressionCommand.h
+++ b/Source/cmIncludeRegularExpressionCommand.h
@@ -3,7 +3,7 @@
#ifndef cmIncludeRegularExpressionCommand_h
#define cmIncludeRegularExpressionCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,17 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
- {
- return new cmIncludeRegularExpressionCommand;
- }
+ cmCommand* Clone() override { return new cmIncludeRegularExpressionCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmInstallCommand.cxx b/Source/cmInstallCommand.cxx
index 294fb178d..685fc671c 100644
--- a/Source/cmInstallCommand.cxx
+++ b/Source/cmInstallCommand.cxx
@@ -141,23 +141,23 @@ bool cmInstallCommand::HandleScriptMode(std::vector<std::string> const& args)
// Scan the args again, this time adding install generators each time we
// encounter a SCRIPT or CODE arg:
//
- for (size_t i = 0; i < args.size(); ++i) {
- if (args[i] == "SCRIPT") {
+ for (std::string const& arg : args) {
+ if (arg == "SCRIPT") {
doing_script = true;
doing_code = false;
- } else if (args[i] == "CODE") {
+ } else if (arg == "CODE") {
doing_script = false;
doing_code = true;
- } else if (args[i] == "COMPONENT") {
+ } else if (arg == "COMPONENT") {
doing_script = false;
doing_code = false;
} else if (doing_script) {
doing_script = false;
- std::string script = args[i];
+ std::string script = arg;
if (!cmSystemTools::FileIsFullPath(script.c_str())) {
script = this->Makefile->GetCurrentSourceDirectory();
script += "/";
- script += args[i];
+ script += arg;
}
if (cmSystemTools::FileIsDirectory(script)) {
this->SetError("given a directory as value of SCRIPT argument.");
@@ -167,7 +167,7 @@ bool cmInstallCommand::HandleScriptMode(std::vector<std::string> const& args)
script.c_str(), false, component.c_str(), exclude_from_all));
} else if (doing_code) {
doing_code = false;
- std::string const& code = args[i];
+ std::string const& code = arg;
this->Makefile->AddInstallGenerator(new cmInstallScriptGenerator(
code.c_str(), true, component.c_str(), exclude_from_all));
}
@@ -204,7 +204,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
cmCommandArgumentsHelper argHelper;
cmCommandArgumentGroup group;
- cmCAStringVector genericArgVector(&argHelper, CM_NULLPTR);
+ cmCAStringVector genericArgVector(&argHelper, nullptr);
cmCAStringVector archiveArgVector(&argHelper, "ARCHIVE", &group);
cmCAStringVector libraryArgVector(&argHelper, "LIBRARY", &group);
cmCAStringVector runtimeArgVector(&argHelper, "RUNTIME", &group);
@@ -216,10 +216,10 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
&group);
cmCAStringVector publicHeaderArgVector(&argHelper, "PUBLIC_HEADER", &group);
cmCAStringVector resourceArgVector(&argHelper, "RESOURCE", &group);
- genericArgVector.Follows(CM_NULLPTR);
+ genericArgVector.Follows(nullptr);
group.Follows(&genericArgVector);
- argHelper.Parse(&args, CM_NULLPTR);
+ argHelper.Parse(&args, nullptr);
// now parse the generic args (i.e. the ones not specialized on LIBRARY/
// ARCHIVE, RUNTIME etc. (see above)
@@ -229,7 +229,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
cmCAStringVector targetList(&genericArgs.Parser, "TARGETS");
cmCAString exports(&genericArgs.Parser, "EXPORT",
&genericArgs.ArgumentGroup);
- targetList.Follows(CM_NULLPTR);
+ targetList.Follows(nullptr);
genericArgs.ArgumentGroup.Follows(&targetList);
genericArgs.Parse(&genericArgVector.GetVector(), &unknownArgs);
bool success = genericArgs.Finalize();
@@ -336,19 +336,16 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
(this->Makefile->IsOn("WIN32") || this->Makefile->IsOn("CYGWIN") ||
this->Makefile->IsOn("MINGW"));
- for (std::vector<std::string>::const_iterator targetIt =
- targetList.GetVector().begin();
- targetIt != targetList.GetVector().end(); ++targetIt) {
+ for (std::string const& tgt : targetList.GetVector()) {
- if (this->Makefile->IsAlias(*targetIt)) {
+ if (this->Makefile->IsAlias(tgt)) {
std::ostringstream e;
- e << "TARGETS given target \"" << (*targetIt) << "\" which is an alias.";
+ e << "TARGETS given target \"" << tgt << "\" which is an alias.";
this->SetError(e.str());
return false;
}
// Lookup this target in the current directory.
- if (cmTarget* target =
- this->Makefile->FindLocalNonAliasTarget(*targetIt)) {
+ if (cmTarget* target = this->Makefile->FindLocalNonAliasTarget(tgt)) {
// Found the target. Check its type.
if (target->GetType() != cmStateEnums::EXECUTABLE &&
target->GetType() != cmStateEnums::STATIC_LIBRARY &&
@@ -357,7 +354,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
target->GetType() != cmStateEnums::OBJECT_LIBRARY &&
target->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
std::ostringstream e;
- e << "TARGETS given target \"" << (*targetIt)
+ e << "TARGETS given target \"" << tgt
<< "\" which is not an executable, library, or module.";
this->SetError(e.str());
return false;
@@ -367,7 +364,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
if (!this->Makefile->GetGlobalGenerator()->HasKnownObjectFileLocation(
&reason)) {
std::ostringstream e;
- e << "TARGETS given OBJECT library \"" << (*targetIt)
+ e << "TARGETS given OBJECT library \"" << tgt
<< "\" which may not be installed" << reason << ".";
this->SetError(e.str());
return false;
@@ -378,7 +375,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
} else {
// Did not find the target.
std::ostringstream e;
- e << "TARGETS given target \"" << (*targetIt)
+ e << "TARGETS given target \"" << tgt
<< "\" which does not exist in this directory.";
this->SetError(e.str());
return false;
@@ -398,19 +395,18 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
bool installsResource = false;
// Generate install script code to install the given targets.
- for (std::vector<cmTarget*>::iterator ti = targets.begin();
- ti != targets.end(); ++ti) {
+ for (cmTarget* ti : targets) {
// Handle each target type.
- cmTarget& target = *(*ti);
- cmInstallTargetGenerator* archiveGenerator = CM_NULLPTR;
- cmInstallTargetGenerator* libraryGenerator = CM_NULLPTR;
- cmInstallTargetGenerator* runtimeGenerator = CM_NULLPTR;
- cmInstallTargetGenerator* objectGenerator = CM_NULLPTR;
- cmInstallTargetGenerator* frameworkGenerator = CM_NULLPTR;
- cmInstallTargetGenerator* bundleGenerator = CM_NULLPTR;
- cmInstallFilesGenerator* privateHeaderGenerator = CM_NULLPTR;
- cmInstallFilesGenerator* publicHeaderGenerator = CM_NULLPTR;
- cmInstallFilesGenerator* resourceGenerator = CM_NULLPTR;
+ cmTarget& target = *ti;
+ cmInstallTargetGenerator* archiveGenerator = nullptr;
+ cmInstallTargetGenerator* libraryGenerator = nullptr;
+ cmInstallTargetGenerator* runtimeGenerator = nullptr;
+ cmInstallTargetGenerator* objectGenerator = nullptr;
+ cmInstallTargetGenerator* frameworkGenerator = nullptr;
+ cmInstallTargetGenerator* bundleGenerator = nullptr;
+ cmInstallFilesGenerator* privateHeaderGenerator = nullptr;
+ cmInstallFilesGenerator* publicHeaderGenerator = nullptr;
+ cmInstallFilesGenerator* resourceGenerator = nullptr;
// Track whether this is a namelink-only rule.
bool namelinkOnly = false;
@@ -437,8 +433,7 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
runtimeGenerator =
CreateInstallTargetGenerator(target, runtimeArgs, false);
}
- if ((archiveGenerator == CM_NULLPTR) &&
- (runtimeGenerator == CM_NULLPTR)) {
+ if ((archiveGenerator == nullptr) && (runtimeGenerator == nullptr)) {
this->SetError("Library TARGETS given no DESTINATION!");
return false;
}
@@ -688,16 +683,16 @@ bool cmInstallCommand::HandleTargetsMode(std::vector<std::string> const& args)
}
// Keep track of whether we're installing anything in each category
- installsArchive = installsArchive || archiveGenerator != CM_NULLPTR;
- installsLibrary = installsLibrary || libraryGenerator != CM_NULLPTR;
- installsRuntime = installsRuntime || runtimeGenerator != CM_NULLPTR;
- installsObject = installsObject || objectGenerator != CM_NULLPTR;
- installsFramework = installsFramework || frameworkGenerator != CM_NULLPTR;
- installsBundle = installsBundle || bundleGenerator != CM_NULLPTR;
+ installsArchive = installsArchive || archiveGenerator != nullptr;
+ installsLibrary = installsLibrary || libraryGenerator != nullptr;
+ installsRuntime = installsRuntime || runtimeGenerator != nullptr;
+ installsObject = installsObject || objectGenerator != nullptr;
+ installsFramework = installsFramework || frameworkGenerator != nullptr;
+ installsBundle = installsBundle || bundleGenerator != nullptr;
installsPrivateHeader =
- installsPrivateHeader || privateHeaderGenerator != CM_NULLPTR;
+ installsPrivateHeader || privateHeaderGenerator != nullptr;
installsPublicHeader =
- installsPublicHeader || publicHeaderGenerator != CM_NULLPTR;
+ installsPublicHeader || publicHeaderGenerator != nullptr;
installsResource = installsResource || resourceGenerator;
this->Makefile->AddInstallGenerator(archiveGenerator);
@@ -779,7 +774,7 @@ bool cmInstallCommand::HandleFilesMode(std::vector<std::string> const& args)
bool programs = (args[0] == "PROGRAMS");
cmInstallCommandArguments ica(this->DefaultComponentName);
cmCAStringVector files(&ica.Parser, programs ? "PROGRAMS" : "FILES");
- files.Follows(CM_NULLPTR);
+ files.Follows(nullptr);
ica.ArgumentGroup.Follows(&files);
std::vector<std::string> unknownArgs;
ica.Parse(&args, &unknownArgs);
@@ -816,10 +811,9 @@ bool cmInstallCommand::HandleFilesMode(std::vector<std::string> const& args)
this->Makefile->GetPolicyStatus(cmPolicies::CMP0062);
cmGlobalGenerator* gg = this->Makefile->GetGlobalGenerator();
- for (std::vector<std::string>::const_iterator fileIt = filesVector.begin();
- fileIt != filesVector.end(); ++fileIt) {
- if (gg->IsExportedTargetsFile(*fileIt)) {
- const char* modal = CM_NULLPTR;
+ for (std::string const& file : filesVector) {
+ if (gg->IsExportedTargetsFile(file)) {
+ const char* modal = nullptr;
std::ostringstream e;
cmake::MessageType messageType = cmake::AUTHOR_WARNING;
@@ -836,8 +830,8 @@ bool cmInstallCommand::HandleFilesMode(std::vector<std::string> const& args)
messageType = cmake::FATAL_ERROR;
}
if (modal) {
- e << "The file\n " << *fileIt << "\nwas generated by the export() "
- "command. It "
+ e << "The file\n " << file << "\nwas generated by the export() "
+ "command. It "
<< modal << " not be installed with the "
"install() command. Use the install(EXPORT) mechanism "
"instead. See the cmake-packages(7) manual for more.\n";
@@ -895,7 +889,7 @@ bool cmInstallCommand::HandleDirectoryMode(
bool exclude_from_all = false;
bool message_never = false;
std::vector<std::string> dirs;
- const char* destination = CM_NULLPTR;
+ const char* destination = nullptr;
std::string permissions_file;
std::string permissions_dir;
std::vector<std::string> configurations;
@@ -1181,7 +1175,7 @@ bool cmInstallCommand::HandleExportAndroidMKMode(
cmCAEnabler exportOld(&ica.Parser, "EXPORT_LINK_INTERFACE_LIBRARIES",
&ica.ArgumentGroup);
cmCAString filename(&ica.Parser, "FILE", &ica.ArgumentGroup);
- exp.Follows(CM_NULLPTR);
+ exp.Follows(nullptr);
ica.ArgumentGroup.Follows(&exp);
std::vector<std::string> unknownArgs;
@@ -1273,7 +1267,7 @@ bool cmInstallCommand::HandleExportMode(std::vector<std::string> const& args)
cmCAEnabler exportOld(&ica.Parser, "EXPORT_LINK_INTERFACE_LIBRARIES",
&ica.ArgumentGroup);
cmCAString filename(&ica.Parser, "FILE", &ica.ArgumentGroup);
- exp.Follows(CM_NULLPTR);
+ exp.Follows(nullptr);
ica.ArgumentGroup.Follows(&exp);
std::vector<std::string> unknownArgs;
@@ -1340,10 +1334,7 @@ bool cmInstallCommand::HandleExportMode(std::vector<std::string> const& args)
cmExportSet* exportSet =
this->Makefile->GetGlobalGenerator()->GetExportSets()[exp.GetString()];
if (exportOld.IsEnabled()) {
- for (std::vector<cmTargetExport*>::const_iterator tei =
- exportSet->GetTargetExports()->begin();
- tei != exportSet->GetTargetExports()->end(); ++tei) {
- cmTargetExport const* te = *tei;
+ for (cmTargetExport* te : *exportSet->GetTargetExports()) {
cmTarget* tgt =
this->Makefile->GetGlobalGenerator()->FindTarget(te->TargetName);
const bool newCMP0022Behavior =
@@ -1380,20 +1371,19 @@ bool cmInstallCommand::MakeFilesFullPath(
const char* modeName, const std::vector<std::string>& relFiles,
std::vector<std::string>& absFiles)
{
- for (std::vector<std::string>::const_iterator fileIt = relFiles.begin();
- fileIt != relFiles.end(); ++fileIt) {
- std::string file = (*fileIt);
+ for (std::string const& relFile : relFiles) {
+ std::string file = relFile;
std::string::size_type gpos = cmGeneratorExpression::Find(file);
if (gpos != 0 && !cmSystemTools::FileIsFullPath(file.c_str())) {
file = this->Makefile->GetCurrentSourceDirectory();
file += "/";
- file += *fileIt;
+ file += relFile;
}
// Make sure the file is not a directory.
if (gpos == std::string::npos && cmSystemTools::FileIsDirectory(file)) {
std::ostringstream e;
- e << modeName << " given directory \"" << (*fileIt) << "\" to install.";
+ e << modeName << " given directory \"" << relFile << "\" to install.";
this->SetError(e.str());
return false;
}
diff --git a/Source/cmInstallCommand.h b/Source/cmInstallCommand.h
index f5d1f9265..8bd015933 100644
--- a/Source/cmInstallCommand.h
+++ b/Source/cmInstallCommand.h
@@ -3,7 +3,7 @@
#ifndef cmInstallCommand_h
#define cmInstallCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmInstallCommand; }
+ cmCommand* Clone() override { return new cmInstallCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
bool HandleScriptMode(std::vector<std::string> const& args);
diff --git a/Source/cmInstallCommandArguments.cxx b/Source/cmInstallCommandArguments.cxx
index b73414dd0..12abac81b 100644
--- a/Source/cmInstallCommandArguments.cxx
+++ b/Source/cmInstallCommandArguments.cxx
@@ -2,15 +2,13 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmInstallCommandArguments.h"
-#include "cmConfigure.h"
-
#include "cmSystemTools.h"
// Table of valid permissions.
const char* cmInstallCommandArguments::PermissionsTable[] = {
"OWNER_READ", "OWNER_WRITE", "OWNER_EXECUTE", "GROUP_READ",
"GROUP_WRITE", "GROUP_EXECUTE", "WORLD_READ", "WORLD_WRITE",
- "WORLD_EXECUTE", "SETUID", "SETGID", CM_NULLPTR
+ "WORLD_EXECUTE", "SETUID", "SETGID", nullptr
};
const std::string cmInstallCommandArguments::EmptyString;
@@ -28,7 +26,7 @@ cmInstallCommandArguments::cmInstallCommandArguments(
, Optional(&Parser, "OPTIONAL", &ArgumentGroup)
, NamelinkOnly(&Parser, "NAMELINK_ONLY", &ArgumentGroup)
, NamelinkSkip(&Parser, "NAMELINK_SKIP", &ArgumentGroup)
- , GenericArguments(CM_NULLPTR)
+ , GenericArguments(nullptr)
, DefaultComponentName(defaultComponent)
{
}
@@ -38,10 +36,10 @@ const std::string& cmInstallCommandArguments::GetDestination() const
if (!this->DestinationString.empty()) {
return this->DestinationString;
}
- if (this->GenericArguments != CM_NULLPTR) {
+ if (this->GenericArguments != nullptr) {
return this->GenericArguments->GetDestination();
}
- return this->EmptyString;
+ return EmptyString;
}
const std::string& cmInstallCommandArguments::GetComponent() const
@@ -49,7 +47,7 @@ const std::string& cmInstallCommandArguments::GetComponent() const
if (!this->Component.GetString().empty()) {
return this->Component.GetString();
}
- if (this->GenericArguments != CM_NULLPTR) {
+ if (this->GenericArguments != nullptr) {
return this->GenericArguments->GetComponent();
}
if (!this->DefaultComponentName.empty()) {
@@ -64,10 +62,10 @@ const std::string& cmInstallCommandArguments::GetRename() const
if (!this->Rename.GetString().empty()) {
return this->Rename.GetString();
}
- if (this->GenericArguments != CM_NULLPTR) {
+ if (this->GenericArguments != nullptr) {
return this->GenericArguments->GetRename();
}
- return this->EmptyString;
+ return EmptyString;
}
const std::string& cmInstallCommandArguments::GetPermissions() const
@@ -75,10 +73,10 @@ const std::string& cmInstallCommandArguments::GetPermissions() const
if (!this->PermissionsString.empty()) {
return this->PermissionsString;
}
- if (this->GenericArguments != CM_NULLPTR) {
+ if (this->GenericArguments != nullptr) {
return this->GenericArguments->GetPermissions();
}
- return this->EmptyString;
+ return EmptyString;
}
bool cmInstallCommandArguments::GetOptional() const
@@ -86,7 +84,7 @@ bool cmInstallCommandArguments::GetOptional() const
if (this->Optional.IsEnabled()) {
return true;
}
- if (this->GenericArguments != CM_NULLPTR) {
+ if (this->GenericArguments != nullptr) {
return this->GenericArguments->GetOptional();
}
return false;
@@ -97,7 +95,7 @@ bool cmInstallCommandArguments::GetExcludeFromAll() const
if (this->ExcludeFromAll.IsEnabled()) {
return true;
}
- if (this->GenericArguments != CM_NULLPTR) {
+ if (this->GenericArguments != nullptr) {
return this->GenericArguments->GetExcludeFromAll();
}
return false;
@@ -108,7 +106,7 @@ bool cmInstallCommandArguments::GetNamelinkOnly() const
if (this->NamelinkOnly.IsEnabled()) {
return true;
}
- if (this->GenericArguments != CM_NULLPTR) {
+ if (this->GenericArguments != nullptr) {
return this->GenericArguments->GetNamelinkOnly();
}
return false;
@@ -119,7 +117,7 @@ bool cmInstallCommandArguments::GetNamelinkSkip() const
if (this->NamelinkSkip.IsEnabled()) {
return true;
}
- if (this->GenericArguments != CM_NULLPTR) {
+ if (this->GenericArguments != nullptr) {
return this->GenericArguments->GetNamelinkSkip();
}
return false;
@@ -131,7 +129,7 @@ const std::vector<std::string>& cmInstallCommandArguments::GetConfigurations()
if (!this->Configurations.GetVector().empty()) {
return this->Configurations.GetVector();
}
- if (this->GenericArguments != CM_NULLPTR) {
+ if (this->GenericArguments != nullptr) {
return this->GenericArguments->GetConfigurations();
}
return this->Configurations.GetVector();
@@ -155,11 +153,9 @@ void cmInstallCommandArguments::Parse(const std::vector<std::string>* args,
bool cmInstallCommandArguments::CheckPermissions()
{
- this->PermissionsString = "";
- for (std::vector<std::string>::const_iterator permIt =
- this->Permissions.GetVector().begin();
- permIt != this->Permissions.GetVector().end(); ++permIt) {
- if (!this->CheckPermissions(*permIt, this->PermissionsString)) {
+ this->PermissionsString.clear();
+ for (std::string const& perm : this->Permissions.GetVector()) {
+ if (!this->CheckPermissions(perm, this->PermissionsString)) {
return false;
}
}
diff --git a/Source/cmInstallDirectoryGenerator.cxx b/Source/cmInstallDirectoryGenerator.cxx
index 54ad85c3b..e4209bd22 100644
--- a/Source/cmInstallDirectoryGenerator.cxx
+++ b/Source/cmInstallDirectoryGenerator.cxx
@@ -7,7 +7,8 @@
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
+
+#include <memory> // IWYU pragma: keep
cmInstallDirectoryGenerator::cmInstallDirectoryGenerator(
std::vector<std::string> const& dirs, const char* dest,
@@ -17,7 +18,7 @@ cmInstallDirectoryGenerator::cmInstallDirectoryGenerator(
bool optional)
: cmInstallGenerator(dest, configurations, component, message,
exclude_from_all)
- , LocalGenerator(CM_NULLPTR)
+ , LocalGenerator(nullptr)
, Directories(dirs)
, FilePermissions(file_permissions)
, DirPermissions(dir_permissions)
@@ -62,19 +63,17 @@ void cmInstallDirectoryGenerator::GenerateScriptForConfig(
{
std::vector<std::string> dirs;
cmGeneratorExpression ge;
- for (std::vector<std::string>::const_iterator i = this->Directories.begin();
- i != this->Directories.end(); ++i) {
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*i);
+ for (std::string const& d : this->Directories) {
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(d);
cmSystemTools::ExpandListArgument(
cge->Evaluate(this->LocalGenerator, config), dirs);
}
// Make sure all dirs have absolute paths.
cmMakefile const& mf = *this->LocalGenerator->GetMakefile();
- for (std::vector<std::string>::iterator i = dirs.begin(); i != dirs.end();
- ++i) {
- if (!cmSystemTools::FileIsFullPath(i->c_str())) {
- *i = std::string(mf.GetCurrentSourceDirectory()) + "/" + *i;
+ for (std::string& d : dirs) {
+ if (!cmSystemTools::FileIsFullPath(d.c_str())) {
+ d = std::string(mf.GetCurrentSourceDirectory()) + "/" + d;
}
}
@@ -86,7 +85,7 @@ void cmInstallDirectoryGenerator::AddDirectoryInstallRule(
std::vector<std::string> const& dirs)
{
// Write code to install the directories.
- const char* no_rename = CM_NULLPTR;
+ const char* no_rename = nullptr;
this->AddInstallRule(os, this->GetDestination(config),
cmInstallType_DIRECTORY, dirs, this->Optional,
this->FilePermissions.c_str(),
diff --git a/Source/cmInstallDirectoryGenerator.h b/Source/cmInstallDirectoryGenerator.h
index aa2cbc690..ac6e50457 100644
--- a/Source/cmInstallDirectoryGenerator.h
+++ b/Source/cmInstallDirectoryGenerator.h
@@ -6,7 +6,7 @@
#include "cmInstallGenerator.h"
#include "cmScriptGenerator.h"
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <string>
@@ -27,16 +27,16 @@ public:
const char* component, MessageLevel message,
bool exclude_from_all, const char* literal_args,
bool optional = false);
- ~cmInstallDirectoryGenerator() CM_OVERRIDE;
+ ~cmInstallDirectoryGenerator() override;
- void Compute(cmLocalGenerator* lg) CM_OVERRIDE;
+ void Compute(cmLocalGenerator* lg) override;
std::string GetDestination(std::string const& config) const;
protected:
- void GenerateScriptActions(std::ostream& os, Indent indent) CM_OVERRIDE;
+ void GenerateScriptActions(std::ostream& os, Indent indent) override;
void GenerateScriptForConfig(std::ostream& os, const std::string& config,
- Indent indent) CM_OVERRIDE;
+ Indent indent) override;
void AddDirectoryInstallRule(std::ostream& os, const std::string& config,
Indent indent,
std::vector<std::string> const& dirs);
diff --git a/Source/cmInstallExportAndroidMKGenerator.cxx b/Source/cmInstallExportAndroidMKGenerator.cxx
index 8eeaa9c7c..dd85b8843 100644
--- a/Source/cmInstallExportAndroidMKGenerator.cxx
+++ b/Source/cmInstallExportAndroidMKGenerator.cxx
@@ -95,8 +95,8 @@ void cmInstallExportAndroidMKGenerator::GenerateScriptConfigs(
std::string config_test = this->CreateConfigTest(i->first);
os << indent << "if(" << config_test << ")\n";
this->AddInstallRule(os, this->Destination, cmInstallType_FILES, files,
- false, this->FilePermissions.c_str(), CM_NULLPTR,
- CM_NULLPTR, CM_NULLPTR, indent.Next());
+ false, this->FilePermissions.c_str(), nullptr,
+ nullptr, nullptr, indent.Next());
os << indent << "endif()\n";
files.clear();
}
@@ -135,6 +135,6 @@ void cmInstallExportAndroidMKGenerator::GenerateScriptActions(
std::vector<std::string> files;
files.push_back(this->MainImportFile);
this->AddInstallRule(os, this->Destination, cmInstallType_FILES, files,
- false, this->FilePermissions.c_str(), CM_NULLPTR,
- CM_NULLPTR, CM_NULLPTR, indent);
+ false, this->FilePermissions.c_str(), nullptr, nullptr,
+ nullptr, indent);
}
diff --git a/Source/cmInstallExportGenerator.cxx b/Source/cmInstallExportGenerator.cxx
index b176e85c5..fdd231ca7 100644
--- a/Source/cmInstallExportGenerator.cxx
+++ b/Source/cmInstallExportGenerator.cxx
@@ -3,7 +3,6 @@
#include "cmInstallExportGenerator.h"
#include <algorithm>
-#include <map>
#include <sstream>
#include <utility>
@@ -29,7 +28,7 @@ cmInstallExportGenerator::cmInstallExportGenerator(
, FileName(filename)
, Namespace(name_space)
, ExportOld(exportOld)
- , LocalGenerator(CM_NULLPTR)
+ , LocalGenerator(nullptr)
{
if (android) {
#ifdef CMAKE_BUILD_WITH_CMAKE
@@ -111,11 +110,9 @@ size_t cmInstallExportGenerator::GetMaxConfigLength() const
len = this->ConfigurationName.size();
}
} else {
- for (std::vector<std::string>::const_iterator ci =
- this->ConfigurationTypes->begin();
- ci != this->ConfigurationTypes->end(); ++ci) {
- if (ci->size() > len) {
- len = ci->size();
+ for (std::string const& c : *this->ConfigurationTypes) {
+ if (c.size() > len) {
+ len = c.size();
}
}
}
@@ -153,10 +150,8 @@ void cmInstallExportGenerator::GenerateScript(std::ostream& os)
this->EFGen->AddConfiguration("");
}
} else {
- for (std::vector<std::string>::const_iterator ci =
- this->ConfigurationTypes->begin();
- ci != this->ConfigurationTypes->end(); ++ci) {
- this->EFGen->AddConfiguration(*ci);
+ for (std::string const& c : *this->ConfigurationTypes) {
+ this->EFGen->AddConfiguration(c);
}
}
this->EFGen->GenerateImportFile();
@@ -174,15 +169,13 @@ void cmInstallExportGenerator::GenerateScriptConfigs(std::ostream& os,
// Now create a configuration-specific install rule for the import
// file of each configuration.
std::vector<std::string> files;
- for (std::map<std::string, std::string>::const_iterator i =
- this->EFGen->GetConfigImportFiles().begin();
- i != this->EFGen->GetConfigImportFiles().end(); ++i) {
- files.push_back(i->second);
- std::string config_test = this->CreateConfigTest(i->first);
+ for (auto const& i : this->EFGen->GetConfigImportFiles()) {
+ files.push_back(i.second);
+ std::string config_test = this->CreateConfigTest(i.first);
os << indent << "if(" << config_test << ")\n";
this->AddInstallRule(os, this->Destination, cmInstallType_FILES, files,
- false, this->FilePermissions.c_str(), CM_NULLPTR,
- CM_NULLPTR, CM_NULLPTR, indent.Next());
+ false, this->FilePermissions.c_str(), nullptr,
+ nullptr, nullptr, indent.Next());
os << indent << "endif()\n";
files.clear();
}
@@ -221,6 +214,6 @@ void cmInstallExportGenerator::GenerateScriptActions(std::ostream& os,
std::vector<std::string> files;
files.push_back(this->MainImportFile);
this->AddInstallRule(os, this->Destination, cmInstallType_FILES, files,
- false, this->FilePermissions.c_str(), CM_NULLPTR,
- CM_NULLPTR, CM_NULLPTR, indent);
+ false, this->FilePermissions.c_str(), nullptr, nullptr,
+ nullptr, indent);
}
diff --git a/Source/cmInstallExportGenerator.h b/Source/cmInstallExportGenerator.h
index 047e6b3cd..d23cf063d 100644
--- a/Source/cmInstallExportGenerator.h
+++ b/Source/cmInstallExportGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmInstallExportGenerator_h
#define cmInstallExportGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmInstallGenerator.h"
#include "cmScriptGenerator.h"
@@ -30,11 +30,11 @@ public:
bool exclude_from_all, const char* filename,
const char* name_space, bool exportOld,
bool android);
- ~cmInstallExportGenerator() CM_OVERRIDE;
+ ~cmInstallExportGenerator() override;
cmExportSet* GetExportSet() { return this->ExportSet; }
- void Compute(cmLocalGenerator* lg) CM_OVERRIDE;
+ void Compute(cmLocalGenerator* lg) override;
cmLocalGenerator* GetLocalGenerator() const { return this->LocalGenerator; }
@@ -43,9 +43,9 @@ public:
std::string const& GetDestination() const { return this->Destination; }
protected:
- void GenerateScript(std::ostream& os) CM_OVERRIDE;
- void GenerateScriptConfigs(std::ostream& os, Indent indent) CM_OVERRIDE;
- void GenerateScriptActions(std::ostream& os, Indent indent) CM_OVERRIDE;
+ void GenerateScript(std::ostream& os) override;
+ void GenerateScriptConfigs(std::ostream& os, Indent indent) override;
+ void GenerateScriptActions(std::ostream& os, Indent indent) override;
void GenerateImportFile(cmExportSet const* exportSet);
void GenerateImportFile(const char* config, cmExportSet const* exportSet);
void ComputeTempDir();
diff --git a/Source/cmInstallFilesCommand.h b/Source/cmInstallFilesCommand.h
index b3c27b827..19f255902 100644
--- a/Source/cmInstallFilesCommand.h
+++ b/Source/cmInstallFilesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmInstallFilesCommand_h
#define cmInstallFilesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmInstallFilesCommand; }
+ cmCommand* Clone() override { return new cmInstallFilesCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
/**
* This is called at the end after all the information
@@ -39,8 +39,8 @@ public:
* not implement this method. At this point, reading and
* writing to the cache can be done.
*/
- void FinalPass() CM_OVERRIDE;
- bool HasFinalPass() const CM_OVERRIDE { return !this->IsFilesForm; }
+ void FinalPass() override;
+ bool HasFinalPass() const override { return !this->IsFilesForm; }
protected:
void CreateInstallGenerator() const;
diff --git a/Source/cmInstallFilesGenerator.cxx b/Source/cmInstallFilesGenerator.cxx
index 6323a9189..68e3f86d1 100644
--- a/Source/cmInstallFilesGenerator.cxx
+++ b/Source/cmInstallFilesGenerator.cxx
@@ -5,7 +5,8 @@
#include "cmGeneratorExpression.h"
#include "cmInstallType.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
+
+#include <memory> // IWYU pragma: keep
class cmLocalGenerator;
@@ -16,7 +17,7 @@ cmInstallFilesGenerator::cmInstallFilesGenerator(
const char* rename, bool optional)
: cmInstallGenerator(dest, configurations, component, message,
exclude_from_all)
- , LocalGenerator(CM_NULLPTR)
+ , LocalGenerator(nullptr)
, Files(files)
, FilePermissions(file_permissions)
, Rename(rename)
@@ -58,12 +59,12 @@ void cmInstallFilesGenerator::AddFilesInstallRule(
std::vector<std::string> const& files)
{
// Write code to install the files.
- const char* no_dir_permissions = CM_NULLPTR;
+ const char* no_dir_permissions = nullptr;
this->AddInstallRule(
os, this->GetDestination(config),
(this->Programs ? cmInstallType_PROGRAMS : cmInstallType_FILES), files,
this->Optional, this->FilePermissions.c_str(), no_dir_permissions,
- this->Rename.c_str(), CM_NULLPTR, indent);
+ this->Rename.c_str(), nullptr, indent);
}
void cmInstallFilesGenerator::GenerateScriptActions(std::ostream& os,
@@ -81,9 +82,8 @@ void cmInstallFilesGenerator::GenerateScriptForConfig(
{
std::vector<std::string> files;
cmGeneratorExpression ge;
- for (std::vector<std::string>::const_iterator i = this->Files.begin();
- i != this->Files.end(); ++i) {
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(*i);
+ for (std::string const& f : this->Files) {
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(f);
cmSystemTools::ExpandListArgument(
cge->Evaluate(this->LocalGenerator, config), files);
}
diff --git a/Source/cmInstallFilesGenerator.h b/Source/cmInstallFilesGenerator.h
index 62b57f9c7..0ef2a06b0 100644
--- a/Source/cmInstallFilesGenerator.h
+++ b/Source/cmInstallFilesGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmInstallFilesGenerator_h
#define cmInstallFilesGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmInstallGenerator.h"
#include "cmScriptGenerator.h"
@@ -27,16 +27,16 @@ public:
const char* component, MessageLevel message,
bool exclude_from_all, const char* rename,
bool optional = false);
- ~cmInstallFilesGenerator() CM_OVERRIDE;
+ ~cmInstallFilesGenerator() override;
- void Compute(cmLocalGenerator* lg) CM_OVERRIDE;
+ void Compute(cmLocalGenerator* lg) override;
std::string GetDestination(std::string const& config) const;
protected:
- void GenerateScriptActions(std::ostream& os, Indent indent) CM_OVERRIDE;
+ void GenerateScriptActions(std::ostream& os, Indent indent) override;
void GenerateScriptForConfig(std::ostream& os, const std::string& config,
- Indent indent) CM_OVERRIDE;
+ Indent indent) override;
void AddFilesInstallRule(std::ostream& os, std::string const& config,
Indent indent,
std::vector<std::string> const& files);
diff --git a/Source/cmInstallGenerator.cxx b/Source/cmInstallGenerator.cxx
index 13b588efb..4d019782b 100644
--- a/Source/cmInstallGenerator.cxx
+++ b/Source/cmInstallGenerator.cxx
@@ -113,9 +113,8 @@ void cmInstallGenerator::AddInstallRule(
if (files.size() == 1) {
os << " \"" << files[0] << "\"";
} else {
- for (std::vector<std::string>::const_iterator fi = files.begin();
- fi != files.end(); ++fi) {
- os << "\n" << indent << " \"" << *fi << "\"";
+ for (std::string const& f : files) {
+ os << "\n" << indent << " \"" << f << "\"";
}
os << "\n" << indent << " ";
if (!(literal_args && *literal_args)) {
@@ -131,9 +130,9 @@ void cmInstallGenerator::AddInstallRule(
std::string cmInstallGenerator::CreateComponentTest(const char* component,
bool exclude_from_all)
{
- std::string result = "\"${CMAKE_INSTALL_COMPONENT}\" STREQUAL \"";
+ std::string result = "\"x${CMAKE_INSTALL_COMPONENT}x\" STREQUAL \"x";
result += component;
- result += "\"";
+ result += "x\"";
if (!exclude_from_all) {
result += " OR NOT CMAKE_INSTALL_COMPONENT";
}
diff --git a/Source/cmInstallGenerator.h b/Source/cmInstallGenerator.h
index 8f8701f1a..fc1ce864f 100644
--- a/Source/cmInstallGenerator.h
+++ b/Source/cmInstallGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmInstallGenerator_h
#define cmInstallGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmInstallType.h"
#include "cmScriptGenerator.h"
@@ -36,14 +36,14 @@ public:
std::vector<std::string> const& configurations,
const char* component, MessageLevel message,
bool exclude_from_all);
- ~cmInstallGenerator() CM_OVERRIDE;
+ ~cmInstallGenerator() override;
void AddInstallRule(
std::ostream& os, std::string const& dest, cmInstallType type,
std::vector<std::string> const& files, bool optional = false,
- const char* permissions_file = CM_NULLPTR,
- const char* permissions_dir = CM_NULLPTR, const char* rename = CM_NULLPTR,
- const char* literal_args = CM_NULLPTR, Indent indent = Indent());
+ const char* permissions_file = nullptr,
+ const char* permissions_dir = nullptr, const char* rename = nullptr,
+ const char* literal_args = nullptr, Indent indent = Indent());
/** Get the install destination as it should appear in the
installation script. */
@@ -58,7 +58,7 @@ public:
virtual void Compute(cmLocalGenerator*) {}
protected:
- void GenerateScript(std::ostream& os) CM_OVERRIDE;
+ void GenerateScript(std::ostream& os) override;
std::string CreateComponentTest(const char* component,
bool exclude_from_all);
diff --git a/Source/cmInstallProgramsCommand.h b/Source/cmInstallProgramsCommand.h
index 242fb953d..5c705ebf6 100644
--- a/Source/cmInstallProgramsCommand.h
+++ b/Source/cmInstallProgramsCommand.h
@@ -3,7 +3,7 @@
#ifndef cmInstallProgramsCommand_h
#define cmInstallProgramsCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmInstallProgramsCommand; }
+ cmCommand* Clone() override { return new cmInstallProgramsCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
/**
* This is called at the end after all the information
@@ -39,9 +39,9 @@ public:
* not implement this method. At this point, reading and
* writing to the cache can be done.
*/
- void FinalPass() CM_OVERRIDE;
+ void FinalPass() override;
- bool HasFinalPass() const CM_OVERRIDE { return true; }
+ bool HasFinalPass() const override { return true; }
protected:
std::string FindInstallSource(const char* name) const;
diff --git a/Source/cmInstallScriptGenerator.cxx b/Source/cmInstallScriptGenerator.cxx
index b39a622f5..f7e6e44a3 100644
--- a/Source/cmInstallScriptGenerator.cxx
+++ b/Source/cmInstallScriptGenerator.cxx
@@ -11,7 +11,7 @@ cmInstallScriptGenerator::cmInstallScriptGenerator(const char* script,
bool code,
const char* component,
bool exclude_from_all)
- : cmInstallGenerator(CM_NULLPTR, std::vector<std::string>(), component,
+ : cmInstallGenerator(nullptr, std::vector<std::string>(), component,
MessageDefault, exclude_from_all)
, Script(script)
, Code(code)
diff --git a/Source/cmInstallScriptGenerator.h b/Source/cmInstallScriptGenerator.h
index e183999d0..fe0f7c6f1 100644
--- a/Source/cmInstallScriptGenerator.h
+++ b/Source/cmInstallScriptGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmInstallScriptGenerator_h
#define cmInstallScriptGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmInstallGenerator.h"
@@ -18,10 +18,10 @@ class cmInstallScriptGenerator : public cmInstallGenerator
public:
cmInstallScriptGenerator(const char* script, bool code,
const char* component, bool exclude_from_all);
- ~cmInstallScriptGenerator() CM_OVERRIDE;
+ ~cmInstallScriptGenerator() override;
protected:
- void GenerateScript(std::ostream& os) CM_OVERRIDE;
+ void GenerateScript(std::ostream& os) override;
std::string Script;
bool Code;
};
diff --git a/Source/cmInstallTargetGenerator.cxx b/Source/cmInstallTargetGenerator.cxx
index 84d6f7ac9..b964794ed 100644
--- a/Source/cmInstallTargetGenerator.cxx
+++ b/Source/cmInstallTargetGenerator.cxx
@@ -28,7 +28,7 @@ cmInstallTargetGenerator::cmInstallTargetGenerator(
: cmInstallGenerator(dest, configurations, component, message,
exclude_from_all)
, TargetName(targetName)
- , Target(CM_NULLPTR)
+ , Target(nullptr)
, FilePermissions(file_permissions)
, ImportLibrary(implib)
, Optional(optional)
@@ -312,8 +312,8 @@ void cmInstallTargetGenerator::GenerateScriptForConfig(
&cmInstallTargetGenerator::PreReplacementTweaks);
// Write code to install the target file.
- const char* no_dir_permissions = CM_NULLPTR;
- const char* no_rename = CM_NULLPTR;
+ const char* no_dir_permissions = nullptr;
+ const char* no_rename = nullptr;
bool optional = this->Optional || this->ImportLibrary;
this->AddInstallRule(os, this->GetDestination(config), type, filesFrom,
optional, this->FilePermissions.c_str(),
@@ -351,8 +351,8 @@ void cmInstallTargetGenerator::GenerateScriptForConfigObjectLibrary(
std::string const obj_dir = this->Target->GetObjectDirectory(config);
std::string const literal_args = " FILES_FROM_DIR \"" + obj_dir + "\"";
- const char* no_dir_permissions = CM_NULLPTR;
- const char* no_rename = CM_NULLPTR;
+ const char* no_dir_permissions = nullptr;
+ const char* no_rename = nullptr;
this->AddInstallRule(os, dest, cmInstallType_FILES, objects, this->Optional,
this->FilePermissions.c_str(), no_dir_permissions,
no_rename, literal_args.c_str(), indent);
@@ -362,9 +362,8 @@ void cmInstallTargetGenerator::GetInstallObjectNames(
std::string const& config, std::vector<std::string>& objects) const
{
this->Target->GetTargetObjectNames(config, objects);
- for (std::vector<std::string>::iterator i = objects.begin();
- i != objects.end(); ++i) {
- *i = computeInstallObjectDir(this->Target, config) + "/" + *i;
+ for (std::string& o : objects) {
+ o = computeInstallObjectDir(this->Target, config) + "/" + o;
}
}
@@ -476,9 +475,8 @@ void cmInstallTargetGenerator::AddTweak(std::ostream& os, Indent indent,
if (!tws.empty()) {
Indent indent2 = indent.Next().Next();
os << indent << "foreach(file\n";
- for (std::vector<std::string>::const_iterator i = files.begin();
- i != files.end(); ++i) {
- os << indent2 << "\"" << this->GetDestDirPath(*i) << "\"\n";
+ for (std::string const& f : files) {
+ os << indent2 << "\"" << this->GetDestDirPath(f) << "\"\n";
}
os << indent2 << ")\n";
os << tws;
@@ -546,11 +544,7 @@ void cmInstallTargetGenerator::AddInstallNamePatchRule(
this->Target->GetLinkInformation(config)) {
std::set<cmGeneratorTarget const*> const& sharedLibs =
cli->GetSharedLibrariesLinked();
- for (std::set<cmGeneratorTarget const*>::const_iterator j =
- sharedLibs.begin();
- j != sharedLibs.end(); ++j) {
- cmGeneratorTarget const* tgt = *j;
-
+ for (cmGeneratorTarget const* tgt : sharedLibs) {
// The install_name of an imported target does not change.
if (tgt->IsImported()) {
continue;
@@ -609,12 +603,9 @@ void cmInstallTargetGenerator::AddInstallNamePatchRule(
if (!new_id.empty()) {
os << "\n" << indent << " -id \"" << new_id << "\"";
}
- for (std::map<std::string, std::string>::const_iterator i =
- install_name_remap.begin();
- i != install_name_remap.end(); ++i) {
+ for (auto const& i : install_name_remap) {
os << "\n"
- << indent << " -change \"" << i->first << "\" \"" << i->second
- << "\"";
+ << indent << " -change \"" << i.first << "\" \"" << i.second << "\"";
}
os << "\n" << indent << " \"" << toDestDirPath << "\")\n";
}
@@ -702,10 +693,9 @@ void cmInstallTargetGenerator::AddChrpathPatchRule(
// Note: These paths are kept unique to avoid
// install_name_tool corruption.
std::set<std::string> runpaths;
- for (std::vector<std::string>::const_iterator i = oldRuntimeDirs.begin();
- i != oldRuntimeDirs.end(); ++i) {
+ for (std::string const& i : oldRuntimeDirs) {
std::string runpath =
- mf->GetGlobalGenerator()->ExpandCFGIntDir(*i, config);
+ mf->GetGlobalGenerator()->ExpandCFGIntDir(i, config);
if (runpaths.find(runpath) == runpaths.end()) {
runpaths.insert(runpath);
@@ -717,10 +707,9 @@ void cmInstallTargetGenerator::AddChrpathPatchRule(
}
runpaths.clear();
- for (std::vector<std::string>::const_iterator i = newRuntimeDirs.begin();
- i != newRuntimeDirs.end(); ++i) {
+ for (std::string const& i : newRuntimeDirs) {
std::string runpath =
- mf->GetGlobalGenerator()->ExpandCFGIntDir(*i, config);
+ mf->GetGlobalGenerator()->ExpandCFGIntDir(i, config);
if (runpaths.find(runpath) == runpaths.end()) {
os << indent << "execute_process(COMMAND " << installNameTool
diff --git a/Source/cmInstallTargetGenerator.h b/Source/cmInstallTargetGenerator.h
index cf2de58f9..f6bec20b3 100644
--- a/Source/cmInstallTargetGenerator.h
+++ b/Source/cmInstallTargetGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmInstallTargetGenerator_h
#define cmInstallTargetGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmInstallGenerator.h"
#include "cmScriptGenerator.h"
@@ -26,7 +26,7 @@ public:
std::vector<std::string> const& configurations,
const char* component, MessageLevel message,
bool exclude_from_all, bool optional);
- ~cmInstallTargetGenerator() CM_OVERRIDE;
+ ~cmInstallTargetGenerator() override;
/** Select the policy for installing shared library linkable name
symlinks. */
@@ -56,7 +56,7 @@ public:
const std::string& config,
NameType nameType = NameNormal);
- void Compute(cmLocalGenerator* lg) CM_OVERRIDE;
+ void Compute(cmLocalGenerator* lg) override;
cmGeneratorTarget* GetTarget() const { return this->Target; }
@@ -65,9 +65,9 @@ public:
std::string GetDestination(std::string const& config) const;
protected:
- void GenerateScript(std::ostream& os) CM_OVERRIDE;
+ void GenerateScript(std::ostream& os) override;
void GenerateScriptForConfig(std::ostream& os, const std::string& config,
- Indent indent) CM_OVERRIDE;
+ Indent indent) override;
void GenerateScriptForConfigObjectLibrary(std::ostream& os,
const std::string& config,
Indent indent);
diff --git a/Source/cmInstallTargetsCommand.cxx b/Source/cmInstallTargetsCommand.cxx
index e00eba012..d721ca0ee 100644
--- a/Source/cmInstallTargetsCommand.cxx
+++ b/Source/cmInstallTargetsCommand.cxx
@@ -2,12 +2,12 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmInstallTargetsCommand.h"
+#include <unordered_map>
#include <utility>
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
#include "cmTarget.h"
-#include "cm_unordered_map.hxx"
class cmExecutionStatus;
diff --git a/Source/cmInstallTargetsCommand.h b/Source/cmInstallTargetsCommand.h
index cc8484365..9950fb7db 100644
--- a/Source/cmInstallTargetsCommand.h
+++ b/Source/cmInstallTargetsCommand.h
@@ -3,7 +3,7 @@
#ifndef cmInstallTargetsCommand_h
#define cmInstallTargetsCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -25,14 +25,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmInstallTargetsCommand; }
+ cmCommand* Clone() override { return new cmInstallTargetsCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmInstalledFile.cxx b/Source/cmInstalledFile.cxx
index d51fd8d74..3ffeabdb5 100644
--- a/Source/cmInstalledFile.cxx
+++ b/Source/cmInstalledFile.cxx
@@ -7,19 +7,16 @@
#include "cmMakefile.h"
#include "cmSystemTools.h"
-#include "cmConfigure.h"
#include <utility>
cmInstalledFile::cmInstalledFile()
- : NameExpression(CM_NULLPTR)
+ : NameExpression(nullptr)
{
}
cmInstalledFile::~cmInstalledFile()
{
- if (NameExpression) {
- delete NameExpression;
- }
+ delete NameExpression;
}
cmInstalledFile::Property::Property()
@@ -91,11 +88,9 @@ bool cmInstalledFile::GetProperty(const std::string& prop,
std::string output;
std::string separator;
- for (ExpressionVectorType::const_iterator j =
- property.ValueExpressions.begin();
- j != property.ValueExpressions.end(); ++j) {
+ for (auto ve : property.ValueExpressions) {
output += separator;
- output += (*j)->GetInput();
+ output += ve->GetInput();
separator = ";";
}
diff --git a/Source/cmInstalledFile.h b/Source/cmInstalledFile.h
index fbf754ffd..47a49590d 100644
--- a/Source/cmInstalledFile.h
+++ b/Source/cmInstalledFile.h
@@ -6,9 +6,9 @@
#include "cmConfigure.h" // IWYU pragma: keep
#include "cmGeneratorExpression.h"
-#include "cm_auto_ptr.hxx"
#include <map>
+#include <memory> // IWYU pragma: keep
#include <string>
#include <vector>
@@ -22,7 +22,7 @@ class cmMakefile;
class cmInstalledFile
{
public:
- typedef CM_AUTO_PTR<cmCompiledGeneratorExpression>
+ typedef std::unique_ptr<cmCompiledGeneratorExpression>
CompiledGeneratorExpressionPtrType;
typedef std::vector<cmCompiledGeneratorExpression*> ExpressionVectorType;
diff --git a/Source/cmLinkDirectoriesCommand.cxx b/Source/cmLinkDirectoriesCommand.cxx
index 9b0c28817..98ab7e7b3 100644
--- a/Source/cmLinkDirectoriesCommand.cxx
+++ b/Source/cmLinkDirectoriesCommand.cxx
@@ -19,9 +19,8 @@ bool cmLinkDirectoriesCommand::InitialPass(
return true;
}
- for (std::vector<std::string>::const_iterator i = args.begin();
- i != args.end(); ++i) {
- this->AddLinkDir(*i);
+ for (std::string const& i : args) {
+ this->AddLinkDir(i);
}
return true;
}
diff --git a/Source/cmLinkDirectoriesCommand.h b/Source/cmLinkDirectoriesCommand.h
index b64e48d70..3fd4e50ab 100644
--- a/Source/cmLinkDirectoriesCommand.h
+++ b/Source/cmLinkDirectoriesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmLinkDirectoriesCommand_h
#define cmLinkDirectoriesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -26,14 +26,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmLinkDirectoriesCommand; }
+ cmCommand* Clone() override { return new cmLinkDirectoriesCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
void AddLinkDir(std::string const& dir);
diff --git a/Source/cmLinkItem.h b/Source/cmLinkItem.h
index f0fded21f..e8c94871b 100644
--- a/Source/cmLinkItem.h
+++ b/Source/cmLinkItem.h
@@ -3,7 +3,7 @@
#ifndef cmLinkItem_h
#define cmLinkItem_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <algorithm>
#include <map>
@@ -24,7 +24,7 @@ class cmLinkItem : public std::string
public:
cmLinkItem()
: std_string()
- , Target(CM_NULLPTR)
+ , Target(nullptr)
{
}
cmLinkItem(const std_string& n, cmGeneratorTarget const* t)
@@ -105,7 +105,7 @@ struct cmOptionalLinkInterface : public cmLinkInterface
, AllDone(false)
, Exists(false)
, HadHeadSensitiveCondition(false)
- , ExplicitLibraries(CM_NULLPTR)
+ , ExplicitLibraries(nullptr)
{
}
bool LibrariesDone;
diff --git a/Source/cmLinkLibrariesCommand.h b/Source/cmLinkLibrariesCommand.h
index f1b3a6816..af25fba4a 100644
--- a/Source/cmLinkLibrariesCommand.h
+++ b/Source/cmLinkLibrariesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmLinkLibrariesCommand_h
#define cmLinkLibrariesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -25,14 +25,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmLinkLibrariesCommand; }
+ cmCommand* Clone() override { return new cmLinkLibrariesCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmLinkLineComputer.cxx b/Source/cmLinkLineComputer.cxx
index c0f702e25..7511fd21b 100644
--- a/Source/cmLinkLineComputer.cxx
+++ b/Source/cmLinkLineComputer.cxx
@@ -59,17 +59,16 @@ std::string cmLinkLineComputer::ComputeLinkLibs(cmComputeLinkInformation& cli)
std::string linkLibs;
typedef cmComputeLinkInformation::ItemVector ItemVector;
ItemVector const& items = cli.GetItems();
- for (ItemVector::const_iterator li = items.begin(); li != items.end();
- ++li) {
- if (li->Target &&
- li->Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+ for (auto const& item : items) {
+ if (item.Target &&
+ item.Target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
- if (li->IsPath) {
+ if (item.IsPath) {
linkLibs +=
- this->ConvertToOutputFormat(this->ConvertToLinkReference(li->Value));
+ this->ConvertToOutputFormat(this->ConvertToLinkReference(item.Value));
} else {
- linkLibs += li->Value;
+ linkLibs += item.Value;
}
linkLibs += " ";
}
@@ -103,9 +102,8 @@ std::string cmLinkLineComputer::ComputeLinkPath(
{
std::string linkPath;
std::vector<std::string> const& libDirs = cli.GetDirectories();
- for (std::vector<std::string>::const_iterator libDir = libDirs.begin();
- libDir != libDirs.end(); ++libDir) {
- std::string libpath = this->ConvertToOutputForExisting(*libDir);
+ for (std::string const& libDir : libDirs) {
+ std::string libpath = this->ConvertToOutputForExisting(libDir);
linkPath += " " + libPathFlag;
linkPath += libpath;
linkPath += libPathTerminator;
@@ -123,10 +121,9 @@ std::string cmLinkLineComputer::ComputeRPath(cmComputeLinkInformation& cli)
std::vector<std::string> runtimeDirs;
cli.GetRPath(runtimeDirs, this->Relink);
- for (std::vector<std::string>::iterator ri = runtimeDirs.begin();
- ri != runtimeDirs.end(); ++ri) {
+ for (std::string const& rd : runtimeDirs) {
rpath += cli.GetRuntimeFlag();
- rpath += this->ConvertToOutputFormat(*ri);
+ rpath += this->ConvertToOutputFormat(rd);
rpath += " ";
}
} else {
@@ -150,10 +147,9 @@ std::string cmLinkLineComputer::ComputeFrameworkPath(
std::string frameworkPath;
if (!fwSearchFlag.empty()) {
std::vector<std::string> const& fwDirs = cli.GetFrameworkPaths();
- for (std::vector<std::string>::const_iterator fdi = fwDirs.begin();
- fdi != fwDirs.end(); ++fdi) {
+ for (std::string const& fd : fwDirs) {
frameworkPath += fwSearchFlag;
- frameworkPath += this->ConvertToOutputFormat(*fdi);
+ frameworkPath += this->ConvertToOutputFormat(fd);
frameworkPath += " ";
}
}
diff --git a/Source/cmLinkLineComputer.h b/Source/cmLinkLineComputer.h
index d33e8d1ff..a016358fa 100644
--- a/Source/cmLinkLineComputer.h
+++ b/Source/cmLinkLineComputer.h
@@ -4,7 +4,7 @@
#ifndef cmLinkLineComputer_h
#define cmLinkLineComputer_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
diff --git a/Source/cmLinkLineDeviceComputer.cxx b/Source/cmLinkLineDeviceComputer.cxx
index 942e9b92c..3beeae321 100644
--- a/Source/cmLinkLineDeviceComputer.cxx
+++ b/Source/cmLinkLineDeviceComputer.cxx
@@ -5,7 +5,6 @@
#include <set>
#include <sstream>
-#include <vector>
#include "cmComputeLinkInformation.h"
#include "cmGeneratorTarget.h"
@@ -32,14 +31,13 @@ std::string cmLinkLineDeviceComputer::ComputeLinkLibraries(
typedef cmComputeLinkInformation::ItemVector ItemVector;
ItemVector const& items = cli.GetItems();
std::string config = cli.GetConfig();
- for (ItemVector::const_iterator li = items.begin(); li != items.end();
- ++li) {
- if (!li->Target) {
+ for (auto const& item : items) {
+ if (!item.Target) {
continue;
}
bool skippable = false;
- switch (li->Target->GetType()) {
+ switch (item.Target->GetType()) {
case cmStateEnums::SHARED_LIBRARY:
case cmStateEnums::MODULE_LIBRARY:
case cmStateEnums::INTERFACE_LIBRARY:
@@ -49,7 +47,7 @@ std::string cmLinkLineDeviceComputer::ComputeLinkLibraries(
// If a static library is resolving its device linking, it should
// be removed for other device linking
skippable =
- li->Target->GetPropertyAsBool("CUDA_RESOLVE_DEVICE_SYMBOLS");
+ item.Target->GetPropertyAsBool("CUDA_RESOLVE_DEVICE_SYMBOLS");
break;
default:
break;
@@ -60,16 +58,16 @@ std::string cmLinkLineDeviceComputer::ComputeLinkLibraries(
}
std::set<std::string> langs;
- li->Target->GetLanguages(langs, config);
+ item.Target->GetLanguages(langs, config);
if (langs.count("CUDA") == 0) {
continue;
}
- if (li->IsPath) {
+ if (item.IsPath) {
fout << this->ConvertToOutputFormat(
- this->ConvertToLinkReference(li->Value));
+ this->ConvertToLinkReference(item.Value));
} else {
- fout << li->Value;
+ fout << item.Value;
}
fout << " ";
}
diff --git a/Source/cmLinkLineDeviceComputer.h b/Source/cmLinkLineDeviceComputer.h
index c3fac6182..81b48b3d4 100644
--- a/Source/cmLinkLineDeviceComputer.h
+++ b/Source/cmLinkLineDeviceComputer.h
@@ -4,7 +4,7 @@
#ifndef cmLinkLineDeviceComputer_h
#define cmLinkLineDeviceComputer_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
@@ -23,14 +23,13 @@ class cmLinkLineDeviceComputer : public cmLinkLineComputer
public:
cmLinkLineDeviceComputer(cmOutputConverter* outputConverter,
cmStateDirectory const& stateDir);
- ~cmLinkLineDeviceComputer() CM_OVERRIDE;
+ ~cmLinkLineDeviceComputer() override;
std::string ComputeLinkLibraries(cmComputeLinkInformation& cli,
- std::string const& stdLibString)
- CM_OVERRIDE;
+ std::string const& stdLibString) override;
std::string GetLinkerLanguage(cmGeneratorTarget* target,
- std::string const& config) CM_OVERRIDE;
+ std::string const& config) override;
};
class cmNinjaLinkLineDeviceComputer : public cmLinkLineDeviceComputer
@@ -42,8 +41,7 @@ public:
cmStateDirectory const& stateDir,
cmGlobalNinjaGenerator const* gg);
- std::string ConvertToLinkReference(std::string const& input) const
- CM_OVERRIDE;
+ std::string ConvertToLinkReference(std::string const& input) const override;
private:
cmGlobalNinjaGenerator const* GG;
diff --git a/Source/cmLinkedTree.h b/Source/cmLinkedTree.h
index 55592cb35..8865e23a1 100644
--- a/Source/cmLinkedTree.h
+++ b/Source/cmLinkedTree.h
@@ -3,7 +3,7 @@
#ifndef cmLinkedTree_h
#define cmLinkedTree_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <assert.h>
#include <iterator>
@@ -49,7 +49,7 @@ public:
public:
iterator()
- : Tree(CM_NULLPTR)
+ : Tree(nullptr)
, Position(0)
{
}
diff --git a/Source/cmListCommand.cxx b/Source/cmListCommand.cxx
index 0542c4fce..ae4f0a84e 100644
--- a/Source/cmListCommand.cxx
+++ b/Source/cmListCommand.cxx
@@ -182,9 +182,9 @@ bool cmListCommand::HandleGetCommand(std::vector<std::string> const& args)
value += sep;
sep = ";";
if (item < 0) {
- item = (int)nitem + item;
+ item = static_cast<int>(nitem) + item;
}
- if (item < 0 || nitem <= (size_t)item) {
+ if (item < 0 || nitem <= static_cast<size_t>(item)) {
std::ostringstream str;
str << "index: " << item << " out of range (-" << nitem << ", "
<< nitem - 1 << ")";
@@ -273,9 +273,9 @@ bool cmListCommand::HandleInsertCommand(std::vector<std::string> const& args)
if (!varArgsExpanded.empty()) {
size_t nitem = varArgsExpanded.size();
if (item < 0) {
- item = (int)nitem + item;
+ item = static_cast<int>(nitem) + item;
}
- if (item < 0 || nitem <= (size_t)item) {
+ if (item < 0 || nitem <= static_cast<size_t>(item)) {
std::ostringstream str;
str << "index: " << item << " out of range (-" << varArgsExpanded.size()
<< ", "
@@ -423,9 +423,9 @@ bool cmListCommand::HandleRemoveAtCommand(std::vector<std::string> const& args)
for (cc = 2; cc < args.size(); ++cc) {
int item = atoi(args[cc].c_str());
if (item < 0) {
- item = (int)nitem + item;
+ item = static_cast<int>(nitem) + item;
}
- if (item < 0 || nitem <= (size_t)item) {
+ if (item < 0 || nitem <= static_cast<size_t>(item)) {
std::ostringstream str;
str << "index: " << item << " out of range (-" << nitem << ", "
<< nitem - 1 << ")";
diff --git a/Source/cmListCommand.h b/Source/cmListCommand.h
index 7789f7df1..29653998c 100644
--- a/Source/cmListCommand.h
+++ b/Source/cmListCommand.h
@@ -3,7 +3,7 @@
#ifndef cmListCommand_h
#define cmListCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -22,14 +22,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmListCommand; }
+ cmCommand* Clone() override { return new cmListCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
protected:
bool HandleLengthCommand(std::vector<std::string> const& args);
diff --git a/Source/cmListFileCache.cxx b/Source/cmListFileCache.cxx
index 0c73cd725..8e8a54d5f 100644
--- a/Source/cmListFileCache.cxx
+++ b/Source/cmListFileCache.cxx
@@ -9,7 +9,6 @@
#include "cmSystemTools.h"
#include "cmake.h"
-#include "cmConfigure.h"
#include <algorithm>
#include <assert.h>
#include <sstream>
@@ -82,7 +81,7 @@ bool cmListFileParser::ParseFile()
}
if (bom == cmListFileLexer_BOM_Broken) {
- cmListFileLexer_SetFileName(this->Lexer, CM_NULLPTR, CM_NULLPTR);
+ cmListFileLexer_SetFileName(this->Lexer, nullptr, nullptr);
this->IssueFileOpenError("Error while reading Byte-Order-Mark. "
"File not seekable?");
return false;
@@ -90,7 +89,7 @@ bool cmListFileParser::ParseFile()
// Verify the Byte-Order-Mark, if any.
if (bom != cmListFileLexer_BOM_None && bom != cmListFileLexer_BOM_UTF8) {
- cmListFileLexer_SetFileName(this->Lexer, CM_NULLPTR, CM_NULLPTR);
+ cmListFileLexer_SetFileName(this->Lexer, nullptr, nullptr);
this->IssueFileOpenError(
"File starts with a Byte-Order-Mark that is not UTF-8.");
return false;
@@ -330,13 +329,13 @@ cmListFileBacktrace::cmListFileBacktrace(cmStateSnapshot const& bottom,
cmListFileBacktrace::cmListFileBacktrace()
: Bottom()
- , Cur(CM_NULLPTR)
+ , Cur(nullptr)
{
}
cmListFileBacktrace::cmListFileBacktrace(cmStateSnapshot const& snapshot)
: Bottom(snapshot.GetCallStackBottom())
- , Cur(CM_NULLPTR)
+ , Cur(nullptr)
{
}
diff --git a/Source/cmLoadCacheCommand.cxx b/Source/cmLoadCacheCommand.cxx
index 00a30bf0e..32fdef51c 100644
--- a/Source/cmLoadCacheCommand.cxx
+++ b/Source/cmLoadCacheCommand.cxx
@@ -27,17 +27,16 @@ bool cmLoadCacheCommand::InitialPass(std::vector<std::string> const& args,
// If this set is empty, all cache entries are brought in
// and they can not be overridden.
bool excludeFiles = false;
- unsigned int i;
std::set<std::string> excludes;
- for (i = 0; i < args.size(); i++) {
+ for (std::string const& arg : args) {
if (excludeFiles) {
- excludes.insert(args[i]);
+ excludes.insert(arg);
}
- if (args[i] == "EXCLUDE") {
+ if (arg == "EXCLUDE") {
excludeFiles = true;
}
- if (excludeFiles && (args[i] == "INCLUDE_INTERNALS")) {
+ if (excludeFiles && (arg == "INCLUDE_INTERNALS")) {
break;
}
}
@@ -48,25 +47,25 @@ bool cmLoadCacheCommand::InitialPass(std::vector<std::string> const& args,
bool includeFiles = false;
std::set<std::string> includes;
- for (i = 0; i < args.size(); i++) {
+ for (std::string const& arg : args) {
if (includeFiles) {
- includes.insert(args[i]);
+ includes.insert(arg);
}
- if (args[i] == "INCLUDE_INTERNALS") {
+ if (arg == "INCLUDE_INTERNALS") {
includeFiles = true;
}
- if (includeFiles && (args[i] == "EXCLUDE")) {
+ if (includeFiles && (arg == "EXCLUDE")) {
break;
}
}
// Loop over each build directory listed in the arguments. Each
// directory has a cache file.
- for (i = 0; i < args.size(); i++) {
- if ((args[i] == "EXCLUDE") || (args[i] == "INCLUDE_INTERNALS")) {
+ for (std::string const& arg : args) {
+ if ((arg == "EXCLUDE") || (arg == "INCLUDE_INTERNALS")) {
break;
}
- this->Makefile->GetCMakeInstance()->LoadCache(args[i], false, excludes,
+ this->Makefile->GetCMakeInstance()->LoadCache(arg, false, excludes,
includes);
}
@@ -125,7 +124,7 @@ bool cmLoadCacheCommand::ReadWithPrefix(std::vector<std::string> const& args)
if (i != end) {
// Completed a line.
this->CheckLine(line.c_str());
- line = "";
+ line.clear();
// Skip the newline character.
++i;
diff --git a/Source/cmLoadCacheCommand.h b/Source/cmLoadCacheCommand.h
index 1a8a0fc4c..e0f6e4f48 100644
--- a/Source/cmLoadCacheCommand.h
+++ b/Source/cmLoadCacheCommand.h
@@ -3,7 +3,7 @@
#ifndef cmLoadCacheCommand_h
#define cmLoadCacheCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <set>
#include <string>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmLoadCacheCommand; }
+ cmCommand* Clone() override { return new cmLoadCacheCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
protected:
std::set<std::string> VariablesToRead;
diff --git a/Source/cmLoadCommandCommand.cxx b/Source/cmLoadCommandCommand.cxx
index 92a32a147..6bfac172f 100644
--- a/Source/cmLoadCommandCommand.cxx
+++ b/Source/cmLoadCommandCommand.cxx
@@ -34,12 +34,12 @@ public:
}
///! clean up any memory allocated by the plugin
- ~cmLoadedCommand() CM_OVERRIDE;
+ ~cmLoadedCommand() override;
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmLoadedCommand* newC = new cmLoadedCommand;
// we must copy when we clone
@@ -52,7 +52,7 @@ public:
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus&) CM_OVERRIDE;
+ cmExecutionStatus&) override;
/**
* This is called at the end after all the information
@@ -60,10 +60,10 @@ public:
* not implement this method. At this point, reading and
* writing to the cache can be done.
*/
- void FinalPass() CM_OVERRIDE;
- bool HasFinalPass() const CM_OVERRIDE
+ void FinalPass() override;
+ bool HasFinalPass() const override
{
- return this->info.FinalPass != CM_NULLPTR;
+ return this->info.FinalPass != nullptr;
}
static const char* LastName;
@@ -86,11 +86,11 @@ public:
#endif
signal(SIGILL, TrapsForSignalsCFunction);
} else {
- signal(SIGSEGV, CM_NULLPTR);
+ signal(SIGSEGV, nullptr);
#ifdef SIGBUS
- signal(SIGBUS, CM_NULLPTR);
+ signal(SIGBUS, nullptr);
#endif
- signal(SIGILL, CM_NULLPTR);
+ signal(SIGILL, nullptr);
}
}
@@ -102,7 +102,7 @@ extern "C" void TrapsForSignalsCFunction(int sig)
cmLoadedCommand::TrapsForSignals(sig);
}
-const char* cmLoadedCommand::LastName = CM_NULLPTR;
+const char* cmLoadedCommand::LastName = nullptr;
bool cmLoadedCommand::InitialPass(std::vector<std::string> const& args,
cmExecutionStatus&)
@@ -118,17 +118,16 @@ bool cmLoadedCommand::InitialPass(std::vector<std::string> const& args,
// create argc and argv and then invoke the command
int argc = static_cast<int>(args.size());
- char** argv = CM_NULLPTR;
+ char** argv = nullptr;
if (argc) {
- argv = (char**)malloc(argc * sizeof(char*));
+ argv = static_cast<char**>(malloc(argc * sizeof(char*)));
}
int i;
for (i = 0; i < argc; ++i) {
argv[i] = strdup(args[i].c_str());
}
cmLoadedCommand::InstallSignalHandlers(info.Name);
- int result =
- info.InitialPass((void*)&info, (void*)this->Makefile, argc, argv);
+ int result = info.InitialPass(&info, this->Makefile, argc, argv);
cmLoadedCommand::InstallSignalHandlers(info.Name, 1);
cmFreeArguments(argc, argv);
@@ -147,7 +146,7 @@ void cmLoadedCommand::FinalPass()
{
if (this->info.FinalPass) {
cmLoadedCommand::InstallSignalHandlers(info.Name);
- this->info.FinalPass((void*)&this->info, (void*)this->Makefile);
+ this->info.FinalPass(&this->info, this->Makefile);
cmLoadedCommand::InstallSignalHandlers(info.Name, 1);
}
}
@@ -156,7 +155,7 @@ cmLoadedCommand::~cmLoadedCommand()
{
if (this->info.Destructor) {
cmLoadedCommand::InstallSignalHandlers(info.Name);
- this->info.Destructor((void*)&this->info);
+ this->info.Destructor(&this->info);
cmLoadedCommand::InstallSignalHandlers(info.Name, 1);
}
if (this->info.Error) {
@@ -198,7 +197,7 @@ bool cmLoadCommandCommand::InitialPass(std::vector<std::string> const& args,
// Try to find the program.
std::string fullPath = cmSystemTools::FindFile(moduleName, path);
- if (fullPath == "") {
+ if (fullPath.empty()) {
std::ostringstream e;
e << "Attempt to load command failed from file \"" << moduleName << "\"";
this->SetError(e.str());
@@ -225,14 +224,13 @@ bool cmLoadCommandCommand::InitialPass(std::vector<std::string> const& args,
// find the init function
std::string initFuncName = args[0] + "Init";
- CM_INIT_FUNCTION initFunction =
- (CM_INIT_FUNCTION)cmsys::DynamicLoader::GetSymbolAddress(lib,
- initFuncName);
+ CM_INIT_FUNCTION initFunction = reinterpret_cast<CM_INIT_FUNCTION>(
+ cmsys::DynamicLoader::GetSymbolAddress(lib, initFuncName));
if (!initFunction) {
initFuncName = "_";
initFuncName += args[0];
initFuncName += "Init";
- initFunction = (CM_INIT_FUNCTION)(
+ initFunction = reinterpret_cast<CM_INIT_FUNCTION>(
cmsys::DynamicLoader::GetSymbolAddress(lib, initFuncName));
}
// if the symbol is found call it to set the name on the
diff --git a/Source/cmLoadCommandCommand.h b/Source/cmLoadCommandCommand.h
index 030786e3d..021e6c7bb 100644
--- a/Source/cmLoadCommandCommand.h
+++ b/Source/cmLoadCommandCommand.h
@@ -3,7 +3,7 @@
#ifndef cmLoadCommandCommand_h
#define cmLoadCommandCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,9 +15,9 @@ class cmExecutionStatus;
class cmLoadCommandCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmLoadCommandCommand; }
+ cmCommand* Clone() override { return new cmLoadCommandCommand; }
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmLocalCommonGenerator.cxx b/Source/cmLocalCommonGenerator.cxx
index 6524db401..50ebfa119 100644
--- a/Source/cmLocalCommonGenerator.cxx
+++ b/Source/cmLocalCommonGenerator.cxx
@@ -22,7 +22,7 @@ cmLocalCommonGenerator::cmLocalCommonGenerator(cmGlobalGenerator* gg,
this->ConfigName = config;
} else {
// No configuration type given.
- this->ConfigName = "";
+ this->ConfigName.clear();
}
}
@@ -67,10 +67,9 @@ std::string cmLocalCommonGenerator::GetTargetFortranFlags(
this->Makefile->GetDefinition("CMAKE_Fortran_MODPATH_FLAG")) {
std::vector<std::string> includes;
this->GetIncludeDirectories(includes, target, "C", config);
- for (std::vector<std::string>::const_iterator idi = includes.begin();
- idi != includes.end(); ++idi) {
+ for (std::string const& id : includes) {
std::string flg = modpath_flag;
- flg += this->ConvertToOutputFormat(*idi, cmOutputConverter::SHELL);
+ flg += this->ConvertToOutputFormat(id, cmOutputConverter::SHELL);
this->AppendFlags(flags, flg);
}
}
diff --git a/Source/cmLocalCommonGenerator.h b/Source/cmLocalCommonGenerator.h
index a5afcd87d..a60573ca6 100644
--- a/Source/cmLocalCommonGenerator.h
+++ b/Source/cmLocalCommonGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmLocalCommonGenerator_h
#define cmLocalCommonGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
@@ -21,14 +21,14 @@ class cmLocalCommonGenerator : public cmLocalGenerator
public:
cmLocalCommonGenerator(cmGlobalGenerator* gg, cmMakefile* mf,
std::string const& wd);
- ~cmLocalCommonGenerator() CM_OVERRIDE;
+ ~cmLocalCommonGenerator() override;
std::string const& GetConfigName() { return this->ConfigName; }
std::string GetWorkingDirectory() const { return this->WorkingDirectory; }
std::string GetTargetFortranFlags(cmGeneratorTarget const* target,
- std::string const& config) CM_OVERRIDE;
+ std::string const& config) override;
protected:
std::string WorkingDirectory;
diff --git a/Source/cmLocalGenerator.cxx b/Source/cmLocalGenerator.cxx
index 6ce31c5ea..1a088ea9e 100644
--- a/Source/cmLocalGenerator.cxx
+++ b/Source/cmLocalGenerator.cxx
@@ -102,9 +102,7 @@ cmLocalGenerator::cmLocalGenerator(cmGlobalGenerator* gg, cmMakefile* makefile)
this->LinkerSysroot = this->Makefile->GetSafeDefinition("CMAKE_SYSROOT");
}
- for (std::vector<std::string>::iterator i = enabledLanguages.begin();
- i != enabledLanguages.end(); ++i) {
- std::string const& lang = *i;
+ for (std::string const& lang : enabledLanguages) {
if (lang == "NONE") {
continue;
}
@@ -209,18 +207,16 @@ void cmLocalGenerator::TraceDependencies()
if (configs.empty()) {
configs.push_back("");
}
- for (std::vector<std::string>::const_iterator ci = configs.begin();
- ci != configs.end(); ++ci) {
- this->GlobalGenerator->CreateEvaluationSourceFiles(*ci);
+ for (std::string const& c : configs) {
+ this->GlobalGenerator->CreateEvaluationSourceFiles(c);
}
// Generate the rule files for each target.
- std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
- t != targets.end(); ++t) {
- if ((*t)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+ const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
+ if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
- (*t)->TraceDependencies();
+ target->TraceDependencies();
}
}
@@ -259,34 +255,60 @@ void cmLocalGenerator::GenerateTestFiles()
fout << "include(\"" << testIncludeFile << "\")" << std::endl;
}
+ const char* testIncludeFiles =
+ this->Makefile->GetProperty("TEST_INCLUDE_FILES");
+ if (testIncludeFiles) {
+ std::vector<std::string> includesList;
+ cmSystemTools::ExpandListArgument(testIncludeFiles, includesList);
+ for (std::string const& i : includesList) {
+ fout << "include(\"" << i << "\")" << std::endl;
+ }
+ }
+
// Ask each test generator to write its code.
std::vector<cmTestGenerator*> const& testers =
this->Makefile->GetTestGenerators();
- for (std::vector<cmTestGenerator*>::const_iterator gi = testers.begin();
- gi != testers.end(); ++gi) {
- (*gi)->Compute(this);
- (*gi)->Generate(fout, config, configurationTypes);
+ for (cmTestGenerator* tester : testers) {
+ tester->Compute(this);
+ tester->Generate(fout, config, configurationTypes);
}
typedef std::vector<cmStateSnapshot> vec_t;
vec_t const& children = this->Makefile->GetStateSnapshot().GetChildren();
std::string parentBinDir = this->GetCurrentBinaryDirectory();
- for (vec_t::const_iterator i = children.begin(); i != children.end(); ++i) {
+ for (cmStateSnapshot const& i : children) {
// TODO: Use add_subdirectory instead?
- std::string outP = i->GetDirectory().GetCurrentBinary();
+ std::string outP = i.GetDirectory().GetCurrentBinary();
outP = this->ConvertToRelativePath(parentBinDir, outP);
outP = cmOutputConverter::EscapeForCMake(outP);
fout << "subdirs(" << outP << ")" << std::endl;
}
+
+ // Add directory labels property
+ const char* directoryLabels =
+ this->Makefile->GetDefinition("CMAKE_DIRECTORY_LABELS");
+ const char* labels = this->Makefile->GetProperty("LABELS");
+
+ if (labels || directoryLabels) {
+ fout << "set_directory_properties(PROPERTIES LABELS ";
+ if (labels) {
+ fout << cmOutputConverter::EscapeForCMake(labels);
+ }
+ if (labels && directoryLabels) {
+ fout << ";";
+ }
+ if (directoryLabels) {
+ fout << cmOutputConverter::EscapeForCMake(directoryLabels);
+ }
+ fout << ")" << std::endl;
+ }
}
void cmLocalGenerator::CreateEvaluationFileOutputs(std::string const& config)
{
std::vector<cmGeneratorExpressionEvaluationFile*> ef =
this->Makefile->GetEvaluationFiles();
- for (std::vector<cmGeneratorExpressionEvaluationFile*>::const_iterator li =
- ef.begin();
- li != ef.end(); ++li) {
- (*li)->CreateOutputFile(this, config);
+ for (cmGeneratorExpressionEvaluationFile* geef : ef) {
+ geef->CreateOutputFile(this, config);
}
}
@@ -295,14 +317,12 @@ void cmLocalGenerator::ProcessEvaluationFiles(
{
std::vector<cmGeneratorExpressionEvaluationFile*> ef =
this->Makefile->GetEvaluationFiles();
- for (std::vector<cmGeneratorExpressionEvaluationFile*>::const_iterator li =
- ef.begin();
- li != ef.end(); ++li) {
- (*li)->Generate(this);
+ for (cmGeneratorExpressionEvaluationFile* geef : ef) {
+ geef->Generate(this);
if (cmSystemTools::GetFatalErrorOccured()) {
return;
}
- std::vector<std::string> files = (*li)->GetFiles();
+ std::vector<std::string> files = geef->GetFiles();
std::sort(files.begin(), files.end());
std::vector<std::string> intersection;
@@ -327,6 +347,7 @@ void cmLocalGenerator::GenerateInstallRules()
{
// Compute the install prefix.
const char* prefix = this->Makefile->GetDefinition("CMAKE_INSTALL_PREFIX");
+
#if defined(_WIN32) && !defined(__CYGWIN__)
std::string prefix_win32;
if (!prefix) {
@@ -370,12 +391,11 @@ void cmLocalGenerator::GenerateInstallRules()
// Choose a default install configuration.
std::string default_config = config;
const char* default_order[] = { "RELEASE", "MINSIZEREL", "RELWITHDEBINFO",
- "DEBUG", CM_NULLPTR };
+ "DEBUG", nullptr };
for (const char** c = default_order; *c && default_config.empty(); ++c) {
- for (std::vector<std::string>::iterator i = configurationTypes.begin();
- i != configurationTypes.end(); ++i) {
- if (cmSystemTools::UpperCase(*i) == *c) {
- default_config = *i;
+ for (std::string const& configurationType : configurationTypes) {
+ if (cmSystemTools::UpperCase(configurationType) == *c) {
+ default_config = configurationType;
}
}
}
@@ -451,13 +471,24 @@ void cmLocalGenerator::GenerateInstallRules()
/* clang-format on */
}
+ // Copy cmake cross compile state to install code.
+ if (const char* crosscompiling =
+ this->Makefile->GetDefinition("CMAKE_CROSSCOMPILING")) {
+ /* clang-format off */
+ fout <<
+ "# Is this installation the result of a crosscompile?\n"
+ "if(NOT DEFINED CMAKE_CROSSCOMPILING)\n"
+ " set(CMAKE_CROSSCOMPILING \"" << crosscompiling << "\")\n"
+ "endif()\n"
+ "\n";
+ /* clang-format on */
+ }
+
// Ask each install generator to write its code.
std::vector<cmInstallGenerator*> const& installers =
this->Makefile->GetInstallGenerators();
- for (std::vector<cmInstallGenerator*>::const_iterator gi =
- installers.begin();
- gi != installers.end(); ++gi) {
- (*gi)->Generate(fout, config, configurationTypes);
+ for (cmInstallGenerator* installer : installers) {
+ installer->Generate(fout, config, configurationTypes);
}
// Write rules from old-style specification stored in targets.
@@ -469,10 +500,9 @@ void cmLocalGenerator::GenerateInstallRules()
if (!children.empty()) {
fout << "if(NOT CMAKE_INSTALL_LOCAL_ONLY)\n";
fout << " # Include the install script for each subdirectory.\n";
- for (std::vector<cmStateSnapshot>::const_iterator ci = children.begin();
- ci != children.end(); ++ci) {
- if (!ci->GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
- std::string odir = ci->GetDirectory().GetCurrentBinary();
+ for (cmStateSnapshot const& c : children) {
+ if (!c.GetDirectory().GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
+ std::string odir = c.GetDirectory().GetCurrentBinary();
cmSystemTools::ConvertToUnixSlashes(odir);
fout << " include(\"" << odir << "/cmake_install.cmake\")"
<< std::endl;
@@ -504,6 +534,8 @@ void cmLocalGenerator::GenerateInstallRules()
void cmLocalGenerator::AddGeneratorTarget(cmGeneratorTarget* gt)
{
this->GeneratorTargets.push_back(gt);
+ this->GeneratorTargetSearchIndex.insert(
+ std::pair<std::string, cmGeneratorTarget*>(gt->GetName(), gt));
this->GlobalGenerator->IndexGeneratorTarget(gt);
}
@@ -537,13 +569,12 @@ private:
cmGeneratorTarget* cmLocalGenerator::FindLocalNonAliasGeneratorTarget(
const std::string& name) const
{
- std::vector<cmGeneratorTarget*>::const_iterator ti =
- std::find_if(this->GeneratorTargets.begin(), this->GeneratorTargets.end(),
- NamedGeneratorTargetFinder(name));
- if (ti != this->GeneratorTargets.end()) {
- return *ti;
+ GeneratorTargetMap::const_iterator ti =
+ this->GeneratorTargetSearchIndex.find(name);
+ if (ti != this->GeneratorTargetSearchIndex.end()) {
+ return ti->second;
}
- return CM_NULLPTR;
+ return nullptr;
}
void cmLocalGenerator::ComputeTargetManifest()
@@ -556,17 +587,13 @@ void cmLocalGenerator::ComputeTargetManifest()
}
// Add our targets to the manifest for each configuration.
- std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
- t != targets.end(); ++t) {
- cmGeneratorTarget* target = *t;
+ const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
- for (std::vector<std::string>::iterator ci = configNames.begin();
- ci != configNames.end(); ++ci) {
- const char* config = ci->c_str();
- target->ComputeTargetManifest(config);
+ for (std::string const& c : configNames) {
+ target->ComputeTargetManifest(c);
}
}
}
@@ -581,13 +608,10 @@ bool cmLocalGenerator::ComputeTargetCompileFeatures()
}
// Process compile features of all targets.
- std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
- t != targets.end(); ++t) {
- cmGeneratorTarget* target = *t;
- for (std::vector<std::string>::iterator ci = configNames.begin();
- ci != configNames.end(); ++ci) {
- if (!target->ComputeCompileFeatures(*ci)) {
+ const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
+ for (std::string const& c : configNames) {
+ if (!target->ComputeCompileFeatures(c)) {
return false;
}
}
@@ -663,7 +687,7 @@ std::string cmLocalGenerator::GetIncludeFlags(
// normal flag is repeated for each directory.
std::string sysFlagVar = "CMAKE_INCLUDE_SYSTEM_FLAG_";
sysFlagVar += lang;
- const char* sysIncludeFlag = CM_NULLPTR;
+ const char* sysIncludeFlag = nullptr;
if (repeatFlag) {
sysIncludeFlag = this->Makefile->GetDefinition(sysFlagVar);
}
@@ -684,16 +708,15 @@ std::string cmLocalGenerator::GetIncludeFlags(
#ifdef __APPLE__
emitted.insert("/System/Library/Frameworks");
#endif
- std::vector<std::string>::const_iterator i;
- for (i = includes.begin(); i != includes.end(); ++i) {
+ for (std::string const& i : includes) {
if (fwSearchFlag && *fwSearchFlag && this->Makefile->IsOn("APPLE") &&
- cmSystemTools::IsPathToFramework(i->c_str())) {
- std::string frameworkDir = *i;
+ cmSystemTools::IsPathToFramework(i.c_str())) {
+ std::string frameworkDir = i;
frameworkDir += "/../";
frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
if (emitted.insert(frameworkDir).second) {
if (sysFwSearchFlag && target &&
- target->IsSystemIncludeDirectory(*i, config)) {
+ target->IsSystemIncludeDirectory(i, config)) {
includeFlags << sysFwSearchFlag;
} else {
includeFlags << fwSearchFlag;
@@ -706,7 +729,7 @@ std::string cmLocalGenerator::GetIncludeFlags(
if (!flagUsed || repeatFlag) {
if (sysIncludeFlag && target &&
- target->IsSystemIncludeDirectory(*i, config)) {
+ target->IsSystemIncludeDirectory(i, config)) {
includeFlags << sysIncludeFlag;
} else {
includeFlags << includeFlag;
@@ -714,7 +737,7 @@ std::string cmLocalGenerator::GetIncludeFlags(
flagUsed = true;
}
std::string includePath =
- this->ConvertToIncludeReference(*i, shellFormat, forceFullPaths);
+ this->ConvertToIncludeReference(i, shellFormat, forceFullPaths);
if (quotePaths && !includePath.empty() && includePath[0] != '\"') {
includeFlags << "\"";
}
@@ -758,12 +781,11 @@ void cmLocalGenerator::AddCompileOptions(std::string& flags,
cmSystemTools::ParseWindowsCommandLine(targetFlags, opts);
}
target->GetCompileOptions(opts, config, lang);
- for (std::vector<std::string>::const_iterator i = opts.begin();
- i != opts.end(); ++i) {
- if (r.find(i->c_str())) {
+ for (std::string const& opt : opts) {
+ if (r.find(opt.c_str())) {
// (Re-)Escape this flag. COMPILE_FLAGS were already parsed
// as a command line above, and COMPILE_OPTIONS are escaped.
- this->AppendFlagEscape(flags, *i);
+ this->AppendFlagEscape(flags, opt);
}
}
} else {
@@ -774,30 +796,27 @@ void cmLocalGenerator::AddCompileOptions(std::string& flags,
}
std::vector<std::string> opts;
target->GetCompileOptions(opts, config, lang);
- for (std::vector<std::string>::const_iterator i = opts.begin();
- i != opts.end(); ++i) {
+ for (std::string const& opt : opts) {
// COMPILE_OPTIONS are escaped.
- this->AppendFlagEscape(flags, *i);
+ this->AppendFlagEscape(flags, opt);
}
}
- for (std::map<std::string, std::string>::const_iterator it =
- target->GetMaxLanguageStandards().begin();
- it != target->GetMaxLanguageStandards().end(); ++it) {
- const char* standard = target->GetProperty(it->first + "_STANDARD");
+ for (auto const& it : target->GetMaxLanguageStandards()) {
+ const char* standard = target->GetProperty(it.first + "_STANDARD");
if (!standard) {
continue;
}
- if (this->Makefile->IsLaterStandard(it->first, standard, it->second)) {
+ if (this->Makefile->IsLaterStandard(it.first, standard, it.second)) {
std::ostringstream e;
e << "The COMPILE_FEATURES property of target \"" << target->GetName()
<< "\" was evaluated when computing the link "
"implementation, and the \""
- << it->first << "_STANDARD\" was \"" << it->second
+ << it.first << "_STANDARD\" was \"" << it.second
<< "\" for that computation. Computing the "
"COMPILE_FEATURES based on the link implementation resulted in a "
"higher \""
- << it->first << "_STANDARD\" \"" << standard
+ << it.first << "_STANDARD\" \"" << standard
<< "\". "
"This is not permitted. The COMPILE_FEATURES may not both depend "
"on "
@@ -872,13 +891,12 @@ void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
if (const char* value = this->Makefile->GetDefinition(impDirVar)) {
std::vector<std::string> impDirVec;
cmSystemTools::ExpandListArgument(value, impDirVec);
- for (std::vector<std::string>::const_iterator i = impDirVec.begin();
- i != impDirVec.end(); ++i) {
- std::string d = rootPath + *i;
+ for (std::string const& i : impDirVec) {
+ std::string d = rootPath + i;
cmSystemTools::ConvertToUnixSlashes(d);
emitted.insert(d);
if (!stripImplicitInclDirs) {
- implicitDirs.push_back(*i);
+ implicitDirs.push_back(i);
}
}
}
@@ -893,26 +911,24 @@ void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
if (this->Makefile->IsOn("CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE")) {
const char* topSourceDir = this->GetState()->GetSourceDirectory();
const char* topBinaryDir = this->GetState()->GetBinaryDirectory();
- for (std::vector<std::string>::const_iterator i = includes.begin();
- i != includes.end(); ++i) {
+ for (std::string const& i : includes) {
// Emit this directory only if it is a subdirectory of the
// top-level source or binary tree.
- if (cmSystemTools::ComparePath(*i, topSourceDir) ||
- cmSystemTools::ComparePath(*i, topBinaryDir) ||
- cmSystemTools::IsSubDirectory(*i, topSourceDir) ||
- cmSystemTools::IsSubDirectory(*i, topBinaryDir)) {
- if (emitted.insert(*i).second) {
- dirs.push_back(*i);
+ if (cmSystemTools::ComparePath(i, topSourceDir) ||
+ cmSystemTools::ComparePath(i, topBinaryDir) ||
+ cmSystemTools::IsSubDirectory(i, topSourceDir) ||
+ cmSystemTools::IsSubDirectory(i, topBinaryDir)) {
+ if (emitted.insert(i).second) {
+ dirs.push_back(i);
}
}
}
}
// Construct the final ordered include directory list.
- for (std::vector<std::string>::const_iterator i = includes.begin();
- i != includes.end(); ++i) {
- if (emitted.insert(*i).second) {
- dirs.push_back(*i);
+ for (std::string const& i : includes) {
+ if (emitted.insert(i).second) {
+ dirs.push_back(i);
}
}
@@ -930,10 +946,9 @@ void cmLocalGenerator::GetIncludeDirectories(std::vector<std::string>& dirs,
dirs.push_back(*i);
}
- for (std::vector<std::string>::const_iterator i = implicitDirs.begin();
- i != implicitDirs.end(); ++i) {
- if (std::find(includes.begin(), includes.end(), *i) != includes.end()) {
- dirs.push_back(*i);
+ for (std::string const& i : implicitDirs) {
+ if (std::find(includes.begin(), includes.end(), i) != includes.end()) {
+ dirs.push_back(i);
}
}
}
@@ -991,9 +1006,7 @@ void cmLocalGenerator::GetTargetFlags(
target->GetSourceFiles(sources, buildType);
std::string defFlag =
this->Makefile->GetSafeDefinition("CMAKE_LINK_DEF_FILE_FLAG");
- for (std::vector<cmSourceFile*>::const_iterator i = sources.begin();
- i != sources.end(); ++i) {
- cmSourceFile* sf = *i;
+ for (cmSourceFile* sf : sources) {
if (sf->GetExtension() == "def") {
linkFlags += defFlag;
linkFlags += this->ConvertToOutputFormat(
@@ -1144,10 +1157,9 @@ static std::string GetFrameworkFlags(const std::string& lang,
lg->GetIncludeDirectories(includes, target, "C", config);
// check all include directories for frameworks as this
// will already have added a -F for the framework
- for (std::vector<std::string>::iterator i = includes.begin();
- i != includes.end(); ++i) {
- if (lg->GetGlobalGenerator()->NameResolvesToFramework(*i)) {
- std::string frameworkDir = *i;
+ for (std::string const& include : includes) {
+ if (lg->GetGlobalGenerator()->NameResolvesToFramework(include)) {
+ std::string frameworkDir = include;
frameworkDir += "/../";
frameworkDir = cmSystemTools::CollapseFullPath(frameworkDir);
emitted.insert(frameworkDir);
@@ -1157,11 +1169,11 @@ static std::string GetFrameworkFlags(const std::string& lang,
std::string flags;
if (cmComputeLinkInformation* cli = target->GetLinkInformation(config)) {
std::vector<std::string> const& frameworks = cli->GetFrameworkPaths();
- for (std::vector<std::string>::const_iterator i = frameworks.begin();
- i != frameworks.end(); ++i) {
- if (emitted.insert(*i).second) {
+ for (std::string const& framework : frameworks) {
+ if (emitted.insert(framework).second) {
flags += fwSearchFlag;
- flags += lg->ConvertToOutputFormat(*i, cmOutputConverter::SHELL);
+ flags +=
+ lg->ConvertToOutputFormat(framework, cmOutputConverter::SHELL);
flags += " ";
}
}
@@ -1301,7 +1313,7 @@ void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
target->GetAppleArchs(config, archs);
const char* sysroot = this->Makefile->GetDefinition("CMAKE_OSX_SYSROOT");
if (sysroot && sysroot[0] == '/' && !sysroot[1]) {
- sysroot = CM_NULLPTR;
+ sysroot = nullptr;
}
std::string sysrootFlagVar =
std::string("CMAKE_") + lang + "_SYSROOT_FLAG";
@@ -1314,10 +1326,9 @@ void cmLocalGenerator::AddArchitectureFlags(std::string& flags,
this->Makefile->GetDefinition(deploymentTargetFlagVar);
if (!archs.empty() && !lang.empty() &&
(lang[0] == 'C' || lang[0] == 'F')) {
- for (std::vector<std::string>::iterator i = archs.begin();
- i != archs.end(); ++i) {
+ for (std::string const& arch : archs) {
flags += " -arch ";
- flags += *i;
+ flags += arch;
}
}
@@ -1399,7 +1410,7 @@ bool cmLocalGenerator::GetRealDependency(const std::string& inName,
// If the input name is the empty string, there is no real
// dependency. Short-circuit the other checks:
- if (name == "") {
+ if (name.empty()) {
return false;
}
@@ -1502,20 +1513,34 @@ void cmLocalGenerator::AddCompilerRequirementFlag(
// This compiler has no notion of language standard levels.
return;
}
- std::string stdProp = lang + "_STANDARD";
- const char* standardProp = target->GetProperty(stdProp);
- if (!standardProp) {
- return;
- }
std::string extProp = lang + "_EXTENSIONS";
- std::string type = "EXTENSION";
bool ext = true;
if (const char* extPropValue = target->GetProperty(extProp)) {
if (cmSystemTools::IsOff(extPropValue)) {
ext = false;
- type = "STANDARD";
}
}
+ std::string stdProp = lang + "_STANDARD";
+ const char* standardProp = target->GetProperty(stdProp);
+ if (!standardProp) {
+ if (ext) {
+ // No language standard is specified and extensions are not disabled.
+ // Check if this compiler needs a flag to enable extensions.
+ std::string const option_flag =
+ "CMAKE_" + lang + "_EXTENSION_COMPILE_OPTION";
+ if (const char* opt =
+ target->Target->GetMakefile()->GetDefinition(option_flag)) {
+ std::vector<std::string> optVec;
+ cmSystemTools::ExpandListArgument(opt, optVec);
+ for (std::string const& i : optVec) {
+ this->AppendFlagEscape(flags, i);
+ }
+ }
+ }
+ return;
+ }
+
+ std::string const type = ext ? "EXTENSION" : "STANDARD";
if (target->GetPropertyAsBool(lang + "_STANDARD_REQUIRED")) {
std::string option_flag =
@@ -1535,14 +1560,14 @@ void cmLocalGenerator::AddCompilerRequirementFlag(
} else {
std::vector<std::string> optVec;
cmSystemTools::ExpandListArgument(opt, optVec);
- for (size_t i = 0; i < optVec.size(); ++i) {
- this->AppendFlagEscape(flags, optVec[i]);
+ for (std::string const& i : optVec) {
+ this->AppendFlagEscape(flags, i);
}
}
return;
}
- static std::map<std::string, std::vector<std::string> > langStdMap;
+ static std::map<std::string, std::vector<std::string>> langStdMap;
if (langStdMap.empty()) {
// Maintain sorted order, most recent first.
langStdMap["CXX"].push_back("17");
@@ -1583,8 +1608,10 @@ void cmLocalGenerator::AddCompilerRequirementFlag(
return;
}
- // Greater or equal because the standards are stored in
- // backward chronological order.
+ // If the standard requested is older than the compiler's default
+ // then we need to use a flag to change it. The comparison is
+ // greater-or-equal because the standards are stored in backward
+ // chronological order.
if (stdIt >= defaultStdIt) {
std::string option_flag =
"CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
@@ -1593,12 +1620,15 @@ void cmLocalGenerator::AddCompilerRequirementFlag(
target->Target->GetMakefile()->GetRequiredDefinition(option_flag);
std::vector<std::string> optVec;
cmSystemTools::ExpandListArgument(opt, optVec);
- for (size_t i = 0; i < optVec.size(); ++i) {
- this->AppendFlagEscape(flags, optVec[i]);
+ for (std::string const& i : optVec) {
+ this->AppendFlagEscape(flags, i);
}
return;
}
+ // The standard requested is at least as new as the compiler's default,
+ // and the standard request is not required. Decay to the newest standard
+ // for which a flag is defined.
for (; stdIt < defaultStdIt; ++stdIt) {
std::string option_flag =
"CMAKE_" + lang + *stdIt + "_" + type + "_COMPILE_OPTION";
@@ -1607,8 +1637,8 @@ void cmLocalGenerator::AddCompilerRequirementFlag(
target->Target->GetMakefile()->GetDefinition(option_flag)) {
std::vector<std::string> optVec;
cmSystemTools::ExpandListArgument(opt, optVec);
- for (size_t i = 0; i < optVec.size(); ++i) {
- this->AppendFlagEscape(flags, optVec[i]);
+ for (std::string const& i : optVec) {
+ this->AppendFlagEscape(flags, i);
}
return;
}
@@ -1679,7 +1709,7 @@ void cmLocalGenerator::AddVisibilityPresetFlags(
}
std::string warnCMP0063;
- std::string* pWarnCMP0063 = CM_NULLPTR;
+ std::string* pWarnCMP0063 = nullptr;
if (target->GetType() != cmStateEnums::SHARED_LIBRARY &&
target->GetType() != cmStateEnums::MODULE_LIBRARY &&
!target->IsExecutableWithExports()) {
@@ -1790,7 +1820,7 @@ void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
std::string const& lang,
int targetType)
{
- const char* picFlags = CM_NULLPTR;
+ const char* picFlags = nullptr;
if (targetType == cmStateEnums::EXECUTABLE) {
std::string flagsVar = "CMAKE_";
@@ -1807,9 +1837,8 @@ void cmLocalGenerator::AddPositionIndependentFlags(std::string& flags,
if (picFlags) {
std::vector<std::string> options;
cmSystemTools::ExpandListArgument(picFlags, options);
- for (std::vector<std::string>::const_iterator oi = options.begin();
- oi != options.end(); ++oi) {
- this->AppendFlagEscape(flags, *oi);
+ for (std::string const& o : options) {
+ this->AppendFlagEscape(flags, o);
}
}
}
@@ -1873,15 +1902,14 @@ void cmLocalGenerator::AppendIPOLinkerFlags(std::string& flags,
const std::string name = "CMAKE_" + lang + "_LINK_OPTIONS_IPO";
const char* rawFlagsList = this->Makefile->GetDefinition(name);
- if (rawFlagsList == CM_NULLPTR) {
+ if (rawFlagsList == nullptr) {
return;
}
std::vector<std::string> flagsList;
cmSystemTools::ExpandListArgument(rawFlagsList, flagsList);
- for (std::vector<std::string>::const_iterator oi = flagsList.begin();
- oi != flagsList.end(); ++oi) {
- this->AppendFlagEscape(flags, *oi);
+ for (std::string const& o : flagsList) {
+ this->AppendFlagEscape(flags, o);
}
}
@@ -1903,13 +1931,12 @@ void cmLocalGenerator::AppendDefines(
std::set<std::string>& defines,
const std::vector<std::string>& defines_vec) const
{
- for (std::vector<std::string>::const_iterator di = defines_vec.begin();
- di != defines_vec.end(); ++di) {
+ for (std::string const& d : defines_vec) {
// Skip unsupported definitions.
- if (!this->CheckDefinition(*di)) {
+ if (!this->CheckDefinition(d)) {
continue;
}
- defines.insert(*di);
+ defines.insert(d);
}
}
@@ -1979,9 +2006,8 @@ void cmLocalGenerator::AppendFeatureOptions(std::string& flags,
if (const char* optionList = this->Makefile->GetDefinition(optVar)) {
std::vector<std::string> options;
cmSystemTools::ExpandListArgument(optionList, options);
- for (std::vector<std::string>::const_iterator oi = options.begin();
- oi != options.end(); ++oi) {
- this->AppendFlagEscape(flags, *oi);
+ for (std::string const& o : options) {
+ this->AppendFlagEscape(flags, o);
}
}
}
@@ -2003,7 +2029,7 @@ const char* cmLocalGenerator::GetFeature(const std::string& feature,
}
snp = snp.GetBuildsystemDirectoryParent();
}
- return CM_NULLPTR;
+ return nullptr;
}
std::string cmLocalGenerator::GetProjectName() const
@@ -2025,10 +2051,9 @@ std::string cmLocalGenerator::ConstructComment(
comment = "Generating ";
const char* sep = "";
std::string currentBinaryDir = this->GetCurrentBinaryDirectory();
- for (std::vector<std::string>::const_iterator o = ccg.GetOutputs().begin();
- o != ccg.GetOutputs().end(); ++o) {
+ for (std::string const& o : ccg.GetOutputs()) {
comment += sep;
- comment += this->ConvertToRelativePath(currentBinaryDir, *o);
+ comment += this->ConvertToRelativePath(currentBinaryDir, o);
sep = ", ";
}
return comment;
@@ -2058,37 +2083,36 @@ void cmLocalGenerator::GenerateTargetInstallRules(
{
// Convert the old-style install specification from each target to
// an install generator and run it.
- std::vector<cmGeneratorTarget*> tgts = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
- l != tgts.end(); ++l) {
- if ((*l)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+ const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
+ for (cmGeneratorTarget* l : tgts) {
+ if (l->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
// Include the user-specified pre-install script for this target.
- if (const char* preinstall = (*l)->GetProperty("PRE_INSTALL_SCRIPT")) {
- cmInstallScriptGenerator g(preinstall, false, CM_NULLPTR, false);
+ if (const char* preinstall = l->GetProperty("PRE_INSTALL_SCRIPT")) {
+ cmInstallScriptGenerator g(preinstall, false, nullptr, false);
g.Generate(os, config, configurationTypes);
}
// Install this target if a destination is given.
- if ((*l)->Target->GetInstallPath() != "") {
+ if (!l->Target->GetInstallPath().empty()) {
// Compute the full install destination. Note that converting
// to unix slashes also removes any trailing slash.
// We also skip over the leading slash given by the user.
- std::string destination = (*l)->Target->GetInstallPath().substr(1);
+ std::string destination = l->Target->GetInstallPath().substr(1);
cmSystemTools::ConvertToUnixSlashes(destination);
if (destination.empty()) {
destination = ".";
}
// Generate the proper install generator for this target type.
- switch ((*l)->GetType()) {
+ switch (l->GetType()) {
case cmStateEnums::EXECUTABLE:
case cmStateEnums::STATIC_LIBRARY:
case cmStateEnums::MODULE_LIBRARY: {
// Use a target install generator.
- cmInstallTargetGeneratorLocal g(this, (*l)->GetName(),
+ cmInstallTargetGeneratorLocal g(this, l->GetName(),
destination.c_str(), false);
g.Generate(os, config, configurationTypes);
} break;
@@ -2097,18 +2121,18 @@ void cmLocalGenerator::GenerateTargetInstallRules(
// Special code to handle DLL. Install the import library
// to the normal destination and the DLL to the runtime
// destination.
- cmInstallTargetGeneratorLocal g1(this, (*l)->GetName(),
+ cmInstallTargetGeneratorLocal g1(this, l->GetName(),
destination.c_str(), true);
g1.Generate(os, config, configurationTypes);
// We also skip over the leading slash given by the user.
- destination = (*l)->Target->GetRuntimeInstallPath().substr(1);
+ destination = l->Target->GetRuntimeInstallPath().substr(1);
cmSystemTools::ConvertToUnixSlashes(destination);
- cmInstallTargetGeneratorLocal g2(this, (*l)->GetName(),
+ cmInstallTargetGeneratorLocal g2(this, l->GetName(),
destination.c_str(), false);
g2.Generate(os, config, configurationTypes);
#else
// Use a target install generator.
- cmInstallTargetGeneratorLocal g(this, (*l)->GetName(),
+ cmInstallTargetGeneratorLocal g(this, l->GetName(),
destination.c_str(), false);
g.Generate(os, config, configurationTypes);
#endif
@@ -2119,8 +2143,8 @@ void cmLocalGenerator::GenerateTargetInstallRules(
}
// Include the user-specified post-install script for this target.
- if (const char* postinstall = (*l)->GetProperty("POST_INSTALL_SCRIPT")) {
- cmInstallScriptGenerator g(postinstall, false, CM_NULLPTR, false);
+ if (const char* postinstall = l->GetProperty("POST_INSTALL_SCRIPT")) {
+ cmInstallScriptGenerator g(postinstall, false, nullptr, false);
g.Generate(os, config, configurationTypes);
}
}
diff --git a/Source/cmLocalGenerator.h b/Source/cmLocalGenerator.h
index 9f78be465..4a7d2ca64 100644
--- a/Source/cmLocalGenerator.h
+++ b/Source/cmLocalGenerator.h
@@ -3,13 +3,14 @@
#ifndef cmLocalGenerator_h
#define cmLocalGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cm_kwiml.h"
#include <iosfwd>
#include <map>
#include <set>
#include <string>
+#include <unordered_map>
#include <vector>
#include "cmListFileCache.h"
@@ -282,8 +283,8 @@ public:
// Compute object file names.
std::string GetObjectFileNameWithoutTarget(
const cmSourceFile& source, std::string const& dir_max,
- bool* hasSourceExtension = CM_NULLPTR,
- char const* customOutputExtension = CM_NULLPTR);
+ bool* hasSourceExtension = nullptr,
+ char const* customOutputExtension = nullptr);
/** Fill out the static linker flags for the given target. */
void GetStaticLibraryFlags(std::string& flags, std::string const& config,
@@ -311,7 +312,7 @@ public:
virtual void ComputeObjectFilenames(
std::map<cmSourceFile const*, std::string>& mapping,
- cmGeneratorTarget const* gt = CM_NULLPTR);
+ cmGeneratorTarget const* gt = nullptr);
bool IsWindowsShell() const;
bool IsWatcomWMake() const;
@@ -353,8 +354,12 @@ protected:
std::string::size_type ObjectPathMax;
std::set<std::string> ObjectMaxPathViolations;
- std::set<cmGeneratorTarget const*> WarnCMP0063;
+ typedef std::unordered_map<std::string, cmGeneratorTarget*>
+ GeneratorTargetMap;
+ GeneratorTargetMap GeneratorTargetSearchIndex;
std::vector<cmGeneratorTarget*> GeneratorTargets;
+
+ std::set<cmGeneratorTarget const*> WarnCMP0063;
std::vector<cmGeneratorTarget*> ImportedGeneratorTargets;
std::vector<cmGeneratorTarget*> OwnedImportedGeneratorTargets;
std::map<std::string, std::string> AliasTargets;
diff --git a/Source/cmLocalGhsMultiGenerator.cxx b/Source/cmLocalGhsMultiGenerator.cxx
index 5f37af528..ab6774e00 100644
--- a/Source/cmLocalGhsMultiGenerator.cxx
+++ b/Source/cmLocalGhsMultiGenerator.cxx
@@ -20,9 +20,9 @@ cmLocalGhsMultiGenerator::~cmLocalGhsMultiGenerator()
void cmLocalGhsMultiGenerator::Generate()
{
- std::vector<cmGeneratorTarget*> tgts = this->GetGeneratorTargets();
+ const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
+ for (std::vector<cmGeneratorTarget*>::const_iterator l = tgts.begin();
l != tgts.end(); ++l) {
if ((*l)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
diff --git a/Source/cmLocalNinjaGenerator.cxx b/Source/cmLocalNinjaGenerator.cxx
index 266710cb1..477ce51f0 100644
--- a/Source/cmLocalNinjaGenerator.cxx
+++ b/Source/cmLocalNinjaGenerator.cxx
@@ -5,6 +5,7 @@
#include <algorithm>
#include <assert.h>
#include <iterator>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
#include <utility>
@@ -22,7 +23,6 @@
#include "cmState.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
cmLocalNinjaGenerator::cmLocalNinjaGenerator(cmGlobalGenerator* gg,
@@ -55,7 +55,7 @@ void cmLocalNinjaGenerator::Generate()
this->HomeRelativeOutputPath = this->ConvertToRelativePath(
this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
if (this->HomeRelativeOutputPath == ".") {
- this->HomeRelativeOutputPath = "";
+ this->HomeRelativeOutputPath.clear();
}
this->WriteProcessedMakefile(this->GetBuildFileStream());
@@ -79,19 +79,19 @@ void cmLocalNinjaGenerator::Generate()
}
}
- std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
- t != targets.end(); ++t) {
- if ((*t)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+ const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
+ for (cmGeneratorTarget* target : targets) {
+ if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
- cmNinjaTargetGenerator* tg = cmNinjaTargetGenerator::New(*t);
+ cmNinjaTargetGenerator* tg = cmNinjaTargetGenerator::New(target);
if (tg) {
tg->Generate();
// Add the target to "all" if required.
if (!this->GetGlobalNinjaGenerator()->IsExcluded(
- this->GetGlobalNinjaGenerator()->GetLocalGenerators()[0], *t)) {
- this->GetGlobalNinjaGenerator()->AddDependencyToAll(*t);
+ this->GetGlobalNinjaGenerator()->GetLocalGenerators()[0],
+ target)) {
+ this->GetGlobalNinjaGenerator()->AddDependencyToAll(target);
}
delete tg;
}
@@ -212,8 +212,7 @@ void cmLocalNinjaGenerator::WritePools(std::ostream& os)
os, "Pools defined by global property JOB_POOLS");
std::vector<std::string> pools;
cmSystemTools::ExpandListArgument(jobpools, pools);
- for (size_t i = 0; i < pools.size(); ++i) {
- std::string const& pool = pools[i];
+ for (std::string const& pool : pools) {
const std::string::size_type eq = pool.find('=');
unsigned int jobs;
if (eq != std::string::npos &&
@@ -250,12 +249,10 @@ void cmLocalNinjaGenerator::ComputeObjectFilenames(
{
// Determine if these object files should use a custom extension
char const* custom_ext = gt->GetCustomObjectExtension();
- for (std::map<cmSourceFile const*, std::string>::iterator si =
- mapping.begin();
- si != mapping.end(); ++si) {
- cmSourceFile const* sf = si->first;
+ for (auto& si : mapping) {
+ cmSourceFile const* sf = si.first;
bool keptSourceExtension;
- si->second = this->GetObjectFileNameWithoutTarget(
+ si.second = this->GetObjectFileNameWithoutTarget(
*sf, gt->ObjectDirectory, &keptSourceExtension, custom_ext);
}
}
@@ -291,10 +288,9 @@ void cmLocalNinjaGenerator::AppendCustomCommandDeps(
cmCustomCommandGenerator const& ccg, cmNinjaDeps& ninjaDeps)
{
const std::vector<std::string>& deps = ccg.GetDepends();
- for (std::vector<std::string>::const_iterator i = deps.begin();
- i != deps.end(); ++i) {
+ for (std::string const& i : deps) {
std::string dep;
- if (this->GetRealDependency(*i, this->GetConfigName(), dep)) {
+ if (this->GetRealDependency(i, this->GetConfigName(), dep)) {
ninjaDeps.push_back(
this->GetGlobalNinjaGenerator()->ConvertToNinjaPath(dep));
}
@@ -408,9 +404,8 @@ void cmLocalNinjaGenerator::WriteCustomCommandBuildStatement(
this->GetGlobalNinjaGenerator()->MapToNinjaPath());
this->AppendCustomCommandDeps(ccg, ninjaDeps);
- for (cmNinjaDeps::iterator i = ninjaOutputs.begin(); i != ninjaOutputs.end();
- ++i) {
- this->GetGlobalNinjaGenerator()->SeenCustomCommandOutput(*i);
+ for (std::string const& ninjaOutput : ninjaOutputs) {
+ this->GetGlobalNinjaGenerator()->SeenCustomCommandOutput(ninjaOutput);
}
std::vector<std::string> cmdLines;
@@ -445,10 +440,9 @@ void cmLocalNinjaGenerator::AddCustomCommandTarget(cmCustomCommand const* cc,
void cmLocalNinjaGenerator::WriteCustomCommandBuildStatements()
{
- for (std::vector<cmCustomCommand const*>::iterator vi =
- this->CustomCommands.begin();
- vi != this->CustomCommands.end(); ++vi) {
- CustomCommandTargetMap::iterator i = this->CustomCommandTargets.find(*vi);
+ for (cmCustomCommand const* customCommand : this->CustomCommands) {
+ CustomCommandTargetMap::iterator i =
+ this->CustomCommandTargets.find(customCommand);
assert(i != this->CustomCommandTargets.end());
// A custom command may appear on multiple targets. However, some build
@@ -511,7 +505,7 @@ std::string cmLocalNinjaGenerator::MakeCustomLauncher(
std::string launcher = property_value;
launcher += " ";
- CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
this->CreateRulePlaceholderExpander());
rulePlaceholderExpander->ExpandRuleVariables(this, launcher, vars);
diff --git a/Source/cmLocalNinjaGenerator.h b/Source/cmLocalNinjaGenerator.h
index a45e01851..bb16899be 100644
--- a/Source/cmLocalNinjaGenerator.h
+++ b/Source/cmLocalNinjaGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmLocalNinjaGenerator_h
#define cmLocalNinjaGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <map>
@@ -38,14 +38,14 @@ class cmLocalNinjaGenerator : public cmLocalCommonGenerator
public:
cmLocalNinjaGenerator(cmGlobalGenerator* gg, cmMakefile* mf);
- ~cmLocalNinjaGenerator() CM_OVERRIDE;
+ ~cmLocalNinjaGenerator() override;
- void Generate() CM_OVERRIDE;
+ void Generate() override;
- cmRulePlaceholderExpander* CreateRulePlaceholderExpander() const CM_OVERRIDE;
+ cmRulePlaceholderExpander* CreateRulePlaceholderExpander() const override;
- std::string GetTargetDirectory(cmGeneratorTarget const* target) const
- CM_OVERRIDE;
+ std::string GetTargetDirectory(
+ cmGeneratorTarget const* target) const override;
const cmGlobalNinjaGenerator* GetGlobalNinjaGenerator() const;
cmGlobalNinjaGenerator* GetGlobalNinjaGenerator();
@@ -76,13 +76,13 @@ public:
void ComputeObjectFilenames(
std::map<cmSourceFile const*, std::string>& mapping,
- cmGeneratorTarget const* gt = CM_NULLPTR) CM_OVERRIDE;
+ cmGeneratorTarget const* gt = nullptr) override;
protected:
std::string ConvertToIncludeReference(
std::string const& path,
cmOutputConverter::OutputFormat format = cmOutputConverter::SHELL,
- bool forceFullPaths = false) CM_OVERRIDE;
+ bool forceFullPaths = false) override;
private:
cmGeneratedFileStream& GetBuildFileStream() const;
@@ -105,7 +105,7 @@ private:
std::string HomeRelativeOutputPath;
- typedef std::map<cmCustomCommand const*, std::set<cmGeneratorTarget*> >
+ typedef std::map<cmCustomCommand const*, std::set<cmGeneratorTarget*>>
CustomCommandTargetMap;
CustomCommandTargetMap CustomCommandTargets;
std::vector<cmCustomCommand const*> CustomCommands;
diff --git a/Source/cmLocalUnixMakefileGenerator3.cxx b/Source/cmLocalUnixMakefileGenerator3.cxx
index 9b9d22cf5..e26182a15 100644
--- a/Source/cmLocalUnixMakefileGenerator3.cxx
+++ b/Source/cmLocalUnixMakefileGenerator3.cxx
@@ -5,13 +5,12 @@
#include "cmsys/FStream.hxx"
#include "cmsys/Terminal.h"
#include <algorithm>
-#include <functional>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
#include <utility>
#include "cmAlgorithms.h"
-#include "cmCustomCommand.h"
#include "cmCustomCommandGenerator.h"
#include "cmFileTimeComparison.h"
#include "cmGeneratedFileStream.h"
@@ -30,7 +29,6 @@
#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmVersion.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
// Include dependency scanners for supported languages. Only the
@@ -116,17 +114,16 @@ void cmLocalUnixMakefileGenerator3::Generate()
this->Makefile->IsOn("CMAKE_SKIP_ASSEMBLY_SOURCE_RULES");
// Generate the rule files for each target.
- std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
+ const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
cmGlobalUnixMakefileGenerator3* gg =
static_cast<cmGlobalUnixMakefileGenerator3*>(this->GlobalGenerator);
- for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
- t != targets.end(); ++t) {
- if ((*t)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
+ for (cmGeneratorTarget* target : targets) {
+ if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
- CM_AUTO_PTR<cmMakefileTargetGenerator> tg(
- cmMakefileTargetGenerator::New(*t));
- if (tg.get()) {
+ std::unique_ptr<cmMakefileTargetGenerator> tg(
+ cmMakefileTargetGenerator::New(target));
+ if (tg) {
tg->WriteRuleFiles();
gg->RecordTargetProgress(tg.get());
}
@@ -146,7 +143,7 @@ void cmLocalUnixMakefileGenerator3::ComputeHomeRelativeOutputPath()
this->HomeRelativeOutputPath = this->MaybeConvertToRelativePath(
this->GetBinaryDirectory(), this->GetCurrentBinaryDirectory());
if (this->HomeRelativeOutputPath == ".") {
- this->HomeRelativeOutputPath = "";
+ this->HomeRelativeOutputPath.clear();
}
if (!this->HomeRelativeOutputPath.empty()) {
this->HomeRelativeOutputPath += "/";
@@ -159,12 +156,10 @@ void cmLocalUnixMakefileGenerator3::ComputeObjectFilenames(
{
// Determine if these object files should use a custom extension
char const* custom_ext = gt->GetCustomObjectExtension();
- for (std::map<cmSourceFile const*, std::string>::iterator si =
- mapping.begin();
- si != mapping.end(); ++si) {
- cmSourceFile const* sf = si->first;
+ for (auto& si : mapping) {
+ cmSourceFile const* sf = si.first;
bool keptSourceExtension;
- si->second = this->GetObjectFileNameWithoutTarget(
+ si.second = this->GetObjectFileNameWithoutTarget(
*sf, gt->ObjectDirectory, &keptSourceExtension, custom_ext);
}
}
@@ -172,10 +167,8 @@ void cmLocalUnixMakefileGenerator3::ComputeObjectFilenames(
void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles(
std::map<std::string, LocalObjectInfo>& localObjectFiles)
{
- std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator ti = targets.begin();
- ti != targets.end(); ++ti) {
- cmGeneratorTarget* gt = *ti;
+ const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
+ for (cmGeneratorTarget* gt : targets) {
if (gt->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
}
@@ -189,9 +182,7 @@ void cmLocalUnixMakefileGenerator3::GetLocalObjectFiles(
dir += this->GetTargetDirectory(gt);
dir += "/";
// Compute the name of each object file.
- for (std::vector<cmSourceFile const*>::iterator si = objectSources.begin();
- si != objectSources.end(); ++si) {
- cmSourceFile const* sf = *si;
+ for (cmSourceFile const* sf : objectSources) {
bool hasSourceExtension = true;
std::string objectName =
this->GetObjectFileNameWithoutTarget(*sf, dir, &hasSourceExtension);
@@ -210,18 +201,16 @@ void cmLocalUnixMakefileGenerator3::GetIndividualFileTargets(
{
std::map<std::string, LocalObjectInfo> localObjectFiles;
this->GetLocalObjectFiles(localObjectFiles);
- for (std::map<std::string, LocalObjectInfo>::iterator lo =
- localObjectFiles.begin();
- lo != localObjectFiles.end(); ++lo) {
- targets.push_back(lo->first);
-
- std::string::size_type dot_pos = lo->first.rfind(".");
- std::string base = lo->first.substr(0, dot_pos);
- if (lo->second.HasPreprocessRule) {
+ for (auto const& localObjectFile : localObjectFiles) {
+ targets.push_back(localObjectFile.first);
+
+ std::string::size_type dot_pos = localObjectFile.first.rfind(".");
+ std::string base = localObjectFile.first.substr(0, dot_pos);
+ if (localObjectFile.second.HasPreprocessRule) {
targets.push_back(base + ".i");
}
- if (lo->second.HasAssembleRule) {
+ if (localObjectFile.second.HasAssembleRule) {
targets.push_back(base + ".s");
}
}
@@ -270,23 +259,20 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
// now write out the object rules
// for each object file name
- for (std::map<std::string, LocalObjectInfo>::iterator lo =
- localObjectFiles.begin();
- lo != localObjectFiles.end(); ++lo) {
+ for (auto& localObjectFile : localObjectFiles) {
// Add a convenience rule for building the object file.
- this->WriteObjectConvenienceRule(ruleFileStream,
- "target to build an object file",
- lo->first.c_str(), lo->second);
+ this->WriteObjectConvenienceRule(
+ ruleFileStream, "target to build an object file",
+ localObjectFile.first.c_str(), localObjectFile.second);
// Check whether preprocessing and assembly rules make sense.
// They make sense only for C and C++ sources.
bool lang_has_preprocessor = false;
bool lang_has_assembly = false;
- for (std::vector<LocalObjectEntry>::const_iterator ei = lo->second.begin();
- ei != lo->second.end(); ++ei) {
- if (ei->Language == "C" || ei->Language == "CXX" ||
- ei->Language == "CUDA" || ei->Language == "Fortran") {
+ for (LocalObjectEntry const& entry : localObjectFile.second) {
+ if (entry.Language == "C" || entry.Language == "CXX" ||
+ entry.Language == "CUDA" || entry.Language == "Fortran") {
// Right now, C, C++, Fortran and CUDA have both a preprocessor and the
// ability to generate assembly code
lang_has_preprocessor = true;
@@ -297,21 +283,21 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefile()
// Add convenience rules for preprocessed and assembly files.
if (lang_has_preprocessor && do_preprocess_rules) {
- std::string::size_type dot_pos = lo->first.rfind(".");
- std::string base = lo->first.substr(0, dot_pos);
- this->WriteObjectConvenienceRule(ruleFileStream,
- "target to preprocess a source file",
- (base + ".i").c_str(), lo->second);
- lo->second.HasPreprocessRule = true;
+ std::string::size_type dot_pos = localObjectFile.first.rfind(".");
+ std::string base = localObjectFile.first.substr(0, dot_pos);
+ this->WriteObjectConvenienceRule(
+ ruleFileStream, "target to preprocess a source file",
+ (base + ".i").c_str(), localObjectFile.second);
+ localObjectFile.second.HasPreprocessRule = true;
}
if (lang_has_assembly && do_assembly_rules) {
- std::string::size_type dot_pos = lo->first.rfind(".");
- std::string base = lo->first.substr(0, dot_pos);
+ std::string::size_type dot_pos = localObjectFile.first.rfind(".");
+ std::string base = localObjectFile.first.substr(0, dot_pos);
this->WriteObjectConvenienceRule(
ruleFileStream, "target to generate assembly for a file",
- (base + ".s").c_str(), lo->second);
- lo->second.HasAssembleRule = true;
+ (base + ".s").c_str(), localObjectFile.second);
+ localObjectFile.second.HasAssembleRule = true;
}
}
@@ -348,16 +334,15 @@ void cmLocalUnixMakefileGenerator3::WriteObjectConvenienceRule(
std::vector<std::string> depends;
depends.push_back(output);
std::vector<std::string> no_commands;
- this->WriteMakeRule(ruleFileStream, CM_NULLPTR, outNoExt, depends,
+ this->WriteMakeRule(ruleFileStream, nullptr, outNoExt, depends,
no_commands, true, true);
inHelp = false;
}
// Recursively make the rule for each target using the object file.
std::vector<std::string> commands;
- for (std::vector<LocalObjectEntry>::const_iterator t = info.begin();
- t != info.end(); ++t) {
- std::string tgtMakefileName = this->GetRelativeTargetDirectory(t->Target);
+ for (LocalObjectEntry const& t : info) {
+ std::string tgtMakefileName = this->GetRelativeTargetDirectory(t.Target);
std::string targetName = tgtMakefileName;
tgtMakefileName += "/build.make";
targetName += "/";
@@ -382,20 +367,19 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
// for each target we just provide a rule to cd up to the top and do a make
// on the target
- std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
+ const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
std::string localName;
- for (std::vector<cmGeneratorTarget*>::iterator t = targets.begin();
- t != targets.end(); ++t) {
- if (((*t)->GetType() == cmStateEnums::EXECUTABLE) ||
- ((*t)->GetType() == cmStateEnums::STATIC_LIBRARY) ||
- ((*t)->GetType() == cmStateEnums::SHARED_LIBRARY) ||
- ((*t)->GetType() == cmStateEnums::MODULE_LIBRARY) ||
- ((*t)->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
- ((*t)->GetType() == cmStateEnums::UTILITY)) {
- emitted.insert((*t)->GetName());
+ for (cmGeneratorTarget* target : targets) {
+ if ((target->GetType() == cmStateEnums::EXECUTABLE) ||
+ (target->GetType() == cmStateEnums::STATIC_LIBRARY) ||
+ (target->GetType() == cmStateEnums::SHARED_LIBRARY) ||
+ (target->GetType() == cmStateEnums::MODULE_LIBRARY) ||
+ (target->GetType() == cmStateEnums::OBJECT_LIBRARY) ||
+ (target->GetType() == cmStateEnums::UTILITY)) {
+ emitted.insert(target->GetName());
// for subdirs add a rule to build this specific target by name.
- localName = this->GetRelativeTargetDirectory(*t);
+ localName = this->GetRelativeTargetDirectory(target);
localName += "/rule";
commands.clear();
depends.clear();
@@ -411,20 +395,20 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
localName, depends, commands, true);
// Add a target with the canonical name (no prefix, suffix or path).
- if (localName != (*t)->GetName()) {
+ if (localName != target->GetName()) {
commands.clear();
depends.push_back(localName);
this->WriteMakeRule(ruleFileStream, "Convenience name for target.",
- (*t)->GetName(), depends, commands, true);
+ target->GetName(), depends, commands, true);
}
// Add a fast rule to build the target
- std::string makefileName = this->GetRelativeTargetDirectory(*t);
+ std::string makefileName = this->GetRelativeTargetDirectory(target);
makefileName += "/build.make";
// make sure the makefile name is suitable for a makefile
- std::string makeTargetName = this->GetRelativeTargetDirectory(*t);
+ std::string makeTargetName = this->GetRelativeTargetDirectory(target);
makeTargetName += "/build";
- localName = (*t)->GetName();
+ localName = target->GetName();
localName += "/fast";
depends.clear();
commands.clear();
@@ -437,10 +421,10 @@ void cmLocalUnixMakefileGenerator3::WriteLocalMakefileTargets(
// Add a local name for the rule to relink the target before
// installation.
- if ((*t)->NeedRelinkBeforeInstall(this->ConfigName)) {
- makeTargetName = this->GetRelativeTargetDirectory(*t);
+ if (target->NeedRelinkBeforeInstall(this->ConfigName)) {
+ makeTargetName = this->GetRelativeTargetDirectory(target);
makeTargetName += "/preinstall";
- localName = (*t)->GetName();
+ localName = target->GetName();
localName += "/preinstall";
depends.clear();
commands.clear();
@@ -581,9 +565,8 @@ void cmLocalUnixMakefileGenerator3::WriteMakeRule(
// Split dependencies into multiple rule lines. This allows for
// very long dependency lists even on older make implementations.
std::string binDir = this->GetBinaryDirectory();
- for (std::vector<std::string>::const_iterator dep = depends.begin();
- dep != depends.end(); ++dep) {
- replace = *dep;
+ for (std::string const& depend : depends) {
+ replace = depend;
replace = cmSystemTools::ConvertToOutputPath(
this->MaybeConvertToRelativePath(binDir, replace).c_str());
os << cmMakeSafe(tgt) << space << ": " << cmMakeSafe(replace) << "\n";
@@ -718,7 +701,7 @@ void cmLocalUnixMakefileGenerator3::WriteSpecialTargetsTop(
// Add a fake suffix to keep HP happy. Must be max 32 chars for SGI make.
std::vector<std::string> depends;
depends.push_back(".hpux_make_needs_suffix_list");
- this->WriteMakeRule(makefileStream, CM_NULLPTR, ".SUFFIXES", depends,
+ this->WriteMakeRule(makefileStream, nullptr, ".SUFFIXES", depends,
no_commands, false);
if (this->IsWatcomWMake()) {
// Switch on WMake feature, if an error or interrupt occurs during
@@ -892,9 +875,8 @@ void cmLocalUnixMakefileGenerator3::AppendRuleDepends(
void cmLocalUnixMakefileGenerator3::AppendCustomDepends(
std::vector<std::string>& depends, const std::vector<cmCustomCommand>& ccs)
{
- for (std::vector<cmCustomCommand>::const_iterator i = ccs.begin();
- i != ccs.end(); ++i) {
- cmCustomCommandGenerator ccg(*i, this->ConfigName, this);
+ for (cmCustomCommand const& cc : ccs) {
+ cmCustomCommandGenerator ccg(cc, this->ConfigName, this);
this->AppendCustomDepend(depends, ccg);
}
}
@@ -902,11 +884,10 @@ void cmLocalUnixMakefileGenerator3::AppendCustomDepends(
void cmLocalUnixMakefileGenerator3::AppendCustomDepend(
std::vector<std::string>& depends, cmCustomCommandGenerator const& ccg)
{
- for (std::vector<std::string>::const_iterator d = ccg.GetDepends().begin();
- d != ccg.GetDepends().end(); ++d) {
+ for (std::string const& d : ccg.GetDepends()) {
// Lookup the real name of the dependency in case it is a CMake target.
std::string dep;
- if (this->GetRealDependency(*d, this->ConfigName, dep)) {
+ if (this->GetRealDependency(d, this->ConfigName, dep)) {
depends.push_back(dep);
}
}
@@ -916,9 +897,8 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommands(
std::vector<std::string>& commands, const std::vector<cmCustomCommand>& ccs,
cmGeneratorTarget* target, std::string const& relative)
{
- for (std::vector<cmCustomCommand>::const_iterator i = ccs.begin();
- i != ccs.end(); ++i) {
- cmCustomCommandGenerator ccg(*i, this->ConfigName, this);
+ for (cmCustomCommand const& cc : ccs) {
+ cmCustomCommandGenerator ccg(cc, this->ConfigName, this);
this->AppendCustomCommand(commands, ccg, target, relative, true);
}
}
@@ -950,7 +930,7 @@ void cmLocalUnixMakefileGenerator3::AppendCustomCommand(
*content << dir;
}
- CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
this->CreateRulePlaceholderExpander());
// Add each command line to the set of commands.
@@ -1089,9 +1069,8 @@ void cmLocalUnixMakefileGenerator3::AppendCleanCommand(
}
if (!files.empty()) {
fout << "file(REMOVE_RECURSE\n";
- for (std::vector<std::string>::const_iterator f = files.begin();
- f != files.end(); ++f) {
- std::string fc = this->MaybeConvertToRelativePath(currentBinDir, *f);
+ for (std::string const& file : files) {
+ std::string fc = this->MaybeConvertToRelativePath(currentBinDir, file);
fout << " " << cmOutputConverter::EscapeForCMake(fc) << "\n";
}
fout << ")\n";
@@ -1183,10 +1162,10 @@ void cmLocalUnixMakefileGenerator3::AppendEcho(
}
// Reset the line to emtpy.
- line = "";
+ line.clear();
// Progress appears only on first line.
- progress = CM_NULLPTR;
+ progress = nullptr;
// Terminate on end-of-string.
if (*c == '\0') {
@@ -1454,13 +1433,10 @@ bool cmLocalUnixMakefileGenerator3::ScanDependencies(
const char* langStr = mf->GetSafeDefinition("CMAKE_DEPENDS_LANGUAGES");
std::vector<std::string> langs;
cmSystemTools::ExpandListArgument(langStr, langs);
- for (std::vector<std::string>::iterator li = langs.begin();
- li != langs.end(); ++li) {
+ for (std::string const& lang : langs) {
// construct the checker
- std::string lang = *li;
-
// Create the scanner for this language
- cmDepends* scanner = CM_NULLPTR;
+ cmDepends* scanner = nullptr;
if (lang == "C" || lang == "CXX" || lang == "RC" || lang == "ASM" ||
lang == "CUDA") {
// TODO: Handle RC (resource files) dependencies correctly.
@@ -1562,26 +1538,23 @@ void cmLocalUnixMakefileGenerator3::WriteLocalAllRules(
this->WriteDivider(ruleFileStream);
ruleFileStream << "# Targets provided globally by CMake.\n"
<< "\n";
- std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
- std::vector<cmGeneratorTarget*>::iterator glIt;
- for (glIt = targets.begin(); glIt != targets.end(); ++glIt) {
- if ((*glIt)->GetType() == cmStateEnums::GLOBAL_TARGET) {
+ const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
+ for (cmGeneratorTarget* gt : targets) {
+ if (gt->GetType() == cmStateEnums::GLOBAL_TARGET) {
std::string targetString =
- "Special rule for the target " + (*glIt)->GetName();
+ "Special rule for the target " + gt->GetName();
std::vector<std::string> commands;
std::vector<std::string> depends;
- const char* text = (*glIt)->GetProperty("EchoString");
+ const char* text = gt->GetProperty("EchoString");
if (!text) {
text = "Running external command ...";
}
- depends.insert(depends.end(), (*glIt)->GetUtilities().begin(),
- (*glIt)->GetUtilities().end());
+ depends.insert(depends.end(), gt->GetUtilities().begin(),
+ gt->GetUtilities().end());
this->AppendEcho(commands, text,
cmLocalUnixMakefileGenerator3::EchoGlobal);
- cmGeneratorTarget* gt = *glIt;
-
// Global targets store their rules in pre- and post-build commands.
this->AppendCustomDepends(depends, gt->GetPreBuildCommands());
this->AppendCustomDepends(depends, gt->GetPostBuildCommands());
@@ -1728,9 +1701,8 @@ void cmLocalUnixMakefileGenerator3::ClearDependencies(cmMakefile* mf,
// dependencies for that target.
cmDepends clearer;
clearer.SetVerbose(verbose);
- for (std::vector<std::string>::iterator l = files.begin(); l != files.end();
- ++l) {
- std::string dir = cmSystemTools::GetFilenamePath(*l);
+ for (std::string const& file : files) {
+ std::string dir = cmSystemTools::GetFilenamePath(file);
// Clear the implicit dependency makefile.
std::string dependFile = dir + "/depend.make";
@@ -1802,54 +1774,51 @@ void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
cmakefileStream
<< "# The set of languages for which implicit dependencies are needed:\n";
cmakefileStream << "set(CMAKE_DEPENDS_LANGUAGES\n";
- for (ImplicitDependLanguageMap::const_iterator l = implicitLangs.begin();
- l != implicitLangs.end(); ++l) {
- cmakefileStream << " \"" << l->first << "\"\n";
+ for (auto const& implicitLang : implicitLangs) {
+ cmakefileStream << " \"" << implicitLang.first << "\"\n";
}
cmakefileStream << " )\n";
// now list the files for each language
cmakefileStream
<< "# The set of files for implicit dependencies of each language:\n";
- for (ImplicitDependLanguageMap::const_iterator l = implicitLangs.begin();
- l != implicitLangs.end(); ++l) {
- cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << l->first << "\n";
- ImplicitDependFileMap const& implicitPairs = l->second;
+ for (auto const& implicitLang : implicitLangs) {
+ cmakefileStream << "set(CMAKE_DEPENDS_CHECK_" << implicitLang.first
+ << "\n";
+ ImplicitDependFileMap const& implicitPairs = implicitLang.second;
// for each file pair
- for (ImplicitDependFileMap::const_iterator pi = implicitPairs.begin();
- pi != implicitPairs.end(); ++pi) {
- for (cmDepends::DependencyVector::const_iterator di = pi->second.begin();
- di != pi->second.end(); ++di) {
- cmakefileStream << " \"" << *di << "\" ";
- cmakefileStream << "\"" << pi->first << "\"\n";
+ for (auto const& implicitPair : implicitPairs) {
+ for (auto const& di : implicitPair.second) {
+ cmakefileStream << " \"" << di << "\" ";
+ cmakefileStream << "\"" << implicitPair.first << "\"\n";
}
}
cmakefileStream << " )\n";
// Tell the dependency scanner what compiler is used.
std::string cidVar = "CMAKE_";
- cidVar += l->first;
+ cidVar += implicitLang.first;
cidVar += "_COMPILER_ID";
const char* cid = this->Makefile->GetDefinition(cidVar);
if (cid && *cid) {
- cmakefileStream << "set(CMAKE_" << l->first << "_COMPILER_ID \"" << cid
- << "\")\n";
+ cmakefileStream << "set(CMAKE_" << implicitLang.first
+ << "_COMPILER_ID \"" << cid << "\")\n";
}
// Build a list of preprocessor definitions for the target.
std::set<std::string> defines;
- this->AddCompileDefinitions(defines, target, this->ConfigName, l->first);
+ this->AddCompileDefinitions(defines, target, this->ConfigName,
+ implicitLang.first);
if (!defines.empty()) {
/* clang-format off */
cmakefileStream
<< "\n"
<< "# Preprocessor definitions for this target.\n"
- << "set(CMAKE_TARGET_DEFINITIONS_" << l->first << "\n";
+ << "set(CMAKE_TARGET_DEFINITIONS_" << implicitLang.first << "\n";
/* clang-format on */
- for (std::set<std::string>::const_iterator di = defines.begin();
- di != defines.end(); ++di) {
- cmakefileStream << " " << cmOutputConverter::EscapeForCMake(*di)
+ for (std::string const& define : defines) {
+ cmakefileStream << " " << cmOutputConverter::EscapeForCMake(define)
<< "\n";
}
cmakefileStream << " )\n";
@@ -1858,21 +1827,21 @@ void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
// Target-specific include directories:
cmakefileStream << "\n"
<< "# The include file search paths:\n";
- cmakefileStream << "set(CMAKE_" << l->first << "_TARGET_INCLUDE_PATH\n";
+ cmakefileStream << "set(CMAKE_" << implicitLang.first
+ << "_TARGET_INCLUDE_PATH\n";
std::vector<std::string> includes;
const std::string& config =
this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
- this->GetIncludeDirectories(includes, target, l->first, config);
+ this->GetIncludeDirectories(includes, target, implicitLang.first, config);
std::string binaryDir = this->GetState()->GetBinaryDirectory();
if (this->Makefile->IsOn("CMAKE_DEPENDS_IN_PROJECT_ONLY")) {
const char* sourceDir = this->GetState()->GetSourceDirectory();
cmEraseIf(includes, ::NotInProjectDir(sourceDir, binaryDir));
}
- for (std::vector<std::string>::iterator i = includes.begin();
- i != includes.end(); ++i) {
+ for (std::string const& include : includes) {
cmakefileStream << " \""
- << this->MaybeConvertToRelativePath(binaryDir, *i)
+ << this->MaybeConvertToRelativePath(binaryDir, include)
<< "\"\n";
}
cmakefileStream << " )\n";
@@ -1891,10 +1860,8 @@ void cmLocalUnixMakefileGenerator3::WriteDependLanguageInfo(
}
if (!transformRules.empty()) {
cmakefileStream << "set(CMAKE_INCLUDE_TRANSFORMS\n";
- for (std::vector<std::string>::const_iterator tri = transformRules.begin();
- tri != transformRules.end(); ++tri) {
- cmakefileStream << " " << cmOutputConverter::EscapeForCMake(*tri)
- << "\n";
+ for (std::string const& tr : transformRules) {
+ cmakefileStream << " " << cmOutputConverter::EscapeForCMake(tr) << "\n";
}
cmakefileStream << " )\n";
}
@@ -2004,10 +1971,9 @@ std::string cmLocalUnixMakefileGenerator3::ConvertToQuotedOutputPath(
#if defined(_WIN32) && !defined(__CYGWIN__)
if (!cmSystemTools::GetForceUnixPaths()) {
slash = "\\";
- for (std::string::iterator i = components[0].begin();
- i != components[0].end(); ++i) {
- if (*i == '/') {
- *i = '\\';
+ for (char& i : components[0]) {
+ if (i == '/') {
+ i = '\\';
}
}
}
@@ -2106,7 +2072,7 @@ void cmLocalUnixMakefileGenerator3::CreateCDCommand(
std::string outputForExisting = this->ConvertToOutputForExisting(tgtDir);
std::string prefix = cd_cmd + outputForExisting + " && ";
std::transform(commands.begin(), commands.end(), commands.begin(),
- std::bind1st(std::plus<std::string>(), prefix));
+ [&prefix](std::string const& s) { return prefix + s; });
}
}
diff --git a/Source/cmLocalUnixMakefileGenerator3.h b/Source/cmLocalUnixMakefileGenerator3.h
index f64409cba..b149524b6 100644
--- a/Source/cmLocalUnixMakefileGenerator3.h
+++ b/Source/cmLocalUnixMakefileGenerator3.h
@@ -3,7 +3,7 @@
#ifndef cmLocalUnixMakefileGenerator3_h
#define cmLocalUnixMakefileGenerator3_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmDepends.h"
#include "cmLocalCommonGenerator.h"
@@ -31,14 +31,14 @@ class cmLocalUnixMakefileGenerator3 : public cmLocalCommonGenerator
{
public:
cmLocalUnixMakefileGenerator3(cmGlobalGenerator* gg, cmMakefile* mf);
- ~cmLocalUnixMakefileGenerator3() CM_OVERRIDE;
+ ~cmLocalUnixMakefileGenerator3() override;
- void ComputeHomeRelativeOutputPath() CM_OVERRIDE;
+ void ComputeHomeRelativeOutputPath() override;
/**
* Generate the makefile for this directory.
*/
- void Generate() CM_OVERRIDE;
+ void Generate() override;
// this returns the relative path between the HomeOutputDirectory and this
// local generators StartOutputDirectory
@@ -88,9 +88,8 @@ public:
const std::string& tgt);
// append flags to a string
- void AppendFlags(std::string& flags,
- const std::string& newFlags) CM_OVERRIDE;
- void AppendFlags(std::string& flags, const char* newFlags) CM_OVERRIDE;
+ void AppendFlags(std::string& flags, const std::string& newFlags) override;
+ void AppendFlags(std::string& flags, const char* newFlags) override;
// append an echo command
enum EchoColor
@@ -108,14 +107,13 @@ public:
std::string Arg;
};
void AppendEcho(std::vector<std::string>& commands, std::string const& text,
- EchoColor color = EchoNormal,
- EchoProgress const* = CM_NULLPTR);
+ EchoColor color = EchoNormal, EchoProgress const* = nullptr);
/** Get whether the makefile is to have color. */
bool GetColorMakefile() const { return this->ColorMakefile; }
- std::string GetTargetDirectory(cmGeneratorTarget const* target) const
- CM_OVERRIDE;
+ std::string GetTargetDirectory(
+ cmGeneratorTarget const* target) const override;
// create a command that cds to the start dir then runs the commands
void CreateCDCommand(std::vector<std::string>& commands,
@@ -130,10 +128,10 @@ public:
/** Called from command-line hook to bring dependencies up to date
for a target. */
bool UpdateDependencies(const char* tgtInfo, bool verbose,
- bool color) CM_OVERRIDE;
+ bool color) override;
/** Called from command-line hook to clear dependencies. */
- void ClearDependencies(cmMakefile* mf, bool verbose) CM_OVERRIDE;
+ void ClearDependencies(cmMakefile* mf, bool verbose) override;
/** write some extra rules such as make test etc */
void WriteSpecialTargetsTop(std::ostream& makefileStream);
@@ -238,11 +236,11 @@ protected:
cmGeneratorTarget* target,
std::string const& relative,
bool echo_comment = false,
- std::ostream* content = CM_NULLPTR);
+ std::ostream* content = nullptr);
void AppendCleanCommand(std::vector<std::string>& commands,
const std::vector<std::string>& files,
cmGeneratorTarget* target,
- const char* filename = CM_NULLPTR);
+ const char* filename = nullptr);
// Helper methods for dependeny updates.
bool ScanDependencies(
@@ -255,7 +253,7 @@ private:
void ComputeObjectFilenames(
std::map<cmSourceFile const*, std::string>& mapping,
- cmGeneratorTarget const* gt = CM_NULLPTR) CM_OVERRIDE;
+ cmGeneratorTarget const* gt = nullptr) override;
friend class cmMakefileTargetGenerator;
friend class cmMakefileExecutableTargetGenerator;
@@ -272,7 +270,7 @@ private:
cmGeneratorTarget* Target;
std::string Language;
LocalObjectEntry()
- : Target(CM_NULLPTR)
+ : Target(nullptr)
, Language()
{
}
diff --git a/Source/cmLocalVisualStudio10Generator.cxx b/Source/cmLocalVisualStudio10Generator.cxx
index 85d4a73b7..5e81514d4 100644
--- a/Source/cmLocalVisualStudio10Generator.cxx
+++ b/Source/cmLocalVisualStudio10Generator.cxx
@@ -17,7 +17,12 @@ public:
virtual void CharacterDataHandler(const char* data, int length)
{
if (this->DoGUID) {
- this->GUID.assign(data + 1, length - 2);
+ if (data[0] == '{') {
+ // remove surrounding curly brackets
+ this->GUID.assign(data + 1, length - 2);
+ } else {
+ this->GUID.assign(data, length);
+ }
this->DoGUID = false;
}
}
@@ -60,8 +65,8 @@ cmLocalVisualStudio10Generator::~cmLocalVisualStudio10Generator()
void cmLocalVisualStudio10Generator::Generate()
{
- std::vector<cmGeneratorTarget*> tgts = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
+ const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
+ for (std::vector<cmGeneratorTarget*>::const_iterator l = tgts.begin();
l != tgts.end(); ++l) {
if ((*l)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
diff --git a/Source/cmLocalVisualStudio10Generator.h b/Source/cmLocalVisualStudio10Generator.h
index e57dd8f20..4cd56dde3 100644
--- a/Source/cmLocalVisualStudio10Generator.h
+++ b/Source/cmLocalVisualStudio10Generator.h
@@ -3,7 +3,7 @@
#ifndef cmLocalVisualStudio10Generator_h
#define cmLocalVisualStudio10Generator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
diff --git a/Source/cmLocalVisualStudio7Generator.cxx b/Source/cmLocalVisualStudio7Generator.cxx
index dd08e5bdb..d8030b7fb 100644
--- a/Source/cmLocalVisualStudio7Generator.cxx
+++ b/Source/cmLocalVisualStudio7Generator.cxx
@@ -62,8 +62,8 @@ cmLocalVisualStudio7Generator::~cmLocalVisualStudio7Generator()
void cmLocalVisualStudio7Generator::AddHelperCommands()
{
// Now create GUIDs for targets
- std::vector<cmGeneratorTarget*> tgts = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
+ const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
+ for (std::vector<cmGeneratorTarget*>::const_iterator l = tgts.begin();
l != tgts.end(); ++l) {
if ((*l)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
@@ -91,8 +91,9 @@ void cmLocalVisualStudio7Generator::AddCMakeListsRules()
// specification source changes.
if (cmSourceFile* sf = this->CreateVCProjBuildRule()) {
// Add the rule to targets that need it.
- std::vector<cmGeneratorTarget*> tgts = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
+ const std::vector<cmGeneratorTarget*>& tgts =
+ this->GetGeneratorTargets();
+ for (std::vector<cmGeneratorTarget*>::const_iterator l = tgts.begin();
l != tgts.end(); ++l) {
if ((*l)->GetType() == cmStateEnums::GLOBAL_TARGET) {
continue;
@@ -110,8 +111,8 @@ void cmLocalVisualStudio7Generator::FixGlobalTargets()
// Visual Studio .NET 2003 Service Pack 1 will not run post-build
// commands for targets in which no sources are built. Add dummy
// rules to force these targets to build.
- std::vector<cmGeneratorTarget*> tgts = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
+ const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
+ for (std::vector<cmGeneratorTarget*>::const_iterator l = tgts.begin();
l != tgts.end(); l++) {
if ((*l)->GetType() == cmStateEnums::GLOBAL_TARGET) {
std::vector<std::string> no_depends;
@@ -120,7 +121,7 @@ void cmLocalVisualStudio7Generator::FixGlobalTargets()
force_command.push_back(".");
cmCustomCommandLines force_commands;
force_commands.push_back(force_command);
- std::string no_main_dependency = "";
+ std::string no_main_dependency;
std::string force = this->GetCurrentBinaryDirectory();
force += cmake::GetCMakeFilesDirectory();
force += "/";
@@ -150,10 +151,10 @@ void cmLocalVisualStudio7Generator::WriteProjectFiles()
}
// Get the set of targets in this directory.
- std::vector<cmGeneratorTarget*> tgts = this->GetGeneratorTargets();
+ const std::vector<cmGeneratorTarget*>& tgts = this->GetGeneratorTargets();
// Create the project file for each target.
- for (std::vector<cmGeneratorTarget*>::iterator l = tgts.begin();
+ for (std::vector<cmGeneratorTarget*>::const_iterator l = tgts.begin();
l != tgts.end(); l++) {
if ((*l)->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
continue;
@@ -525,6 +526,7 @@ cmVS7FlagTable cmLocalVisualStudio7GeneratorLinkFlagTable[] = {
{ "TargetMachine", "MACHINE:SH5", "Machine SH5", "15", 0 },
{ "TargetMachine", "MACHINE:THUMB", "Machine THUMB", "16", 0 },
{ "TargetMachine", "MACHINE:X64", "Machine x64", "17", 0 },
+ { "TargetMachine", "MACHINE:ARM64", "Machine ARM64", "18", 0 },
{ "TurnOffAssemblyGeneration", "NOASSEMBLY",
"No assembly even if CLR information is present in objects.", "true", 0 },
{ "ModuleDefinitionFile", "DEF:", "add an export def file", "",
@@ -1451,8 +1453,8 @@ cmLocalVisualStudio7GeneratorFCInfo::cmLocalVisualStudio7GeneratorFCInfo(
}
if (const char* cflags = sf.GetProperty("COMPILE_FLAGS")) {
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(cflags);
- fc.CompileFlags = cge->Evaluate(lg, *i);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(cflags);
+ fc.CompileFlags = cge->Evaluate(lg, *i, false, gt);
needfc = true;
}
if (lg->FortranProject) {
@@ -1589,7 +1591,7 @@ bool cmLocalVisualStudio7Generator::WriteGroup(
// If the group has a name, write the header.
std::string name = sg->GetName();
- if (name != "") {
+ if (!name.empty()) {
this->WriteVCProjBeginGroup(fout, name.c_str(), "");
}
@@ -1707,7 +1709,7 @@ bool cmLocalVisualStudio7Generator::WriteGroup(
}
// If the group has a name, write the footer.
- if (name != "") {
+ if (!name.empty()) {
this->WriteVCProjEndGroup(fout);
}
@@ -1847,7 +1849,7 @@ void cmLocalVisualStudio7Generator::OutputTargetRules(
if (!addedPrelink) {
event.Write(target->GetPreLinkCommands());
}
- CM_AUTO_PTR<cmCustomCommand> pcc(
+ std::unique_ptr<cmCustomCommand> pcc(
this->MaybeCreateImplibDir(target, configName, this->FortranProject));
if (pcc.get()) {
event.Write(*pcc);
@@ -2004,7 +2006,7 @@ void cmLocalVisualStudio7Generator::WriteVCProjFooter(
i != props.end(); ++i) {
if (i->find("VS_GLOBAL_") == 0) {
std::string name = i->substr(10);
- if (name != "") {
+ if (!name.empty()) {
/* clang-format off */
fout << "\t\t<Global\n"
<< "\t\t\tName=\"" << name << "\"\n"
@@ -2077,9 +2079,12 @@ public:
if (strcmp(atts[i], "ProjectGUID") == 0) {
if (atts[i + 1]) {
this->GUID = atts[i + 1];
- this->GUID = this->GUID.substr(1, this->GUID.size() - 2);
+ if (this->GUID[0] == '{') {
+ // remove surrounding curly brackets
+ this->GUID = this->GUID.substr(1, this->GUID.size() - 2);
+ }
} else {
- this->GUID = "";
+ this->GUID.clear();
}
return;
}
diff --git a/Source/cmLocalVisualStudio7Generator.h b/Source/cmLocalVisualStudio7Generator.h
index 89a3ee353..7a77574fa 100644
--- a/Source/cmLocalVisualStudio7Generator.h
+++ b/Source/cmLocalVisualStudio7Generator.h
@@ -3,7 +3,7 @@
#ifndef cmLocalVisualStudio7Generator_h
#define cmLocalVisualStudio7Generator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <string>
diff --git a/Source/cmLocalVisualStudioGenerator.cxx b/Source/cmLocalVisualStudioGenerator.cxx
index 41025af6c..bbb91e04b 100644
--- a/Source/cmLocalVisualStudioGenerator.cxx
+++ b/Source/cmLocalVisualStudioGenerator.cxx
@@ -78,12 +78,12 @@ void cmLocalVisualStudioGenerator::ComputeObjectFilenames(
}
}
-CM_AUTO_PTR<cmCustomCommand>
+std::unique_ptr<cmCustomCommand>
cmLocalVisualStudioGenerator::MaybeCreateImplibDir(cmGeneratorTarget* target,
const std::string& config,
bool isFortran)
{
- CM_AUTO_PTR<cmCustomCommand> pcc;
+ std::unique_ptr<cmCustomCommand> pcc;
// If an executable exports symbols then VS wants to create an
// import library but forgets to create the output directory.
@@ -135,7 +135,7 @@ std::string cmLocalVisualStudioGenerator::ConstructScript(
std::string workingDirectory = ccg.GetWorkingDirectory();
// Avoid leading or trailing newlines.
- std::string newline = "";
+ std::string newline;
// Line to check for error between commands.
std::string check_error = newline_text;
@@ -191,13 +191,17 @@ std::string cmLocalVisualStudioGenerator::ConstructScript(
// Write each command on a single line.
for (unsigned int c = 0; c < ccg.GetNumberOfCommands(); ++c) {
+ // Add this command line.
+ std::string cmd = ccg.GetCommand(c);
+
+ if (cmd.empty()) {
+ continue;
+ }
+
// Start a new line.
script += newline;
newline = newline_text;
- // Add this command line.
- std::string cmd = ccg.GetCommand(c);
-
// Use "call " before any invocations of .bat or .cmd files
// invoked as custom commands.
//
diff --git a/Source/cmLocalVisualStudioGenerator.h b/Source/cmLocalVisualStudioGenerator.h
index 85fb8a511..cba24fed7 100644
--- a/Source/cmLocalVisualStudioGenerator.h
+++ b/Source/cmLocalVisualStudioGenerator.h
@@ -3,15 +3,14 @@
#ifndef cmLocalVisualStudioGenerator_h
#define cmLocalVisualStudioGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <map>
-#include <memory>
+#include <memory> // IWYU pragma: keep
#include <string>
#include "cmGlobalVisualStudioGenerator.h"
#include "cmLocalGenerator.h"
-#include "cm_auto_ptr.hxx"
class cmCustomCommand;
class cmCustomCommandGenerator;
@@ -56,9 +55,8 @@ protected:
virtual bool CustomCommandUseLocal() const { return false; }
/** Construct a custom command to make exe import lib dir. */
- CM_AUTO_PTR<cmCustomCommand> MaybeCreateImplibDir(cmGeneratorTarget* target,
- const std::string& config,
- bool isFortran);
+ std::unique_ptr<cmCustomCommand> MaybeCreateImplibDir(
+ cmGeneratorTarget* target, const std::string& config, bool isFortran);
};
#endif
diff --git a/Source/cmLocalXCodeGenerator.cxx b/Source/cmLocalXCodeGenerator.cxx
index 739ef4367..853e66c23 100644
--- a/Source/cmLocalXCodeGenerator.cxx
+++ b/Source/cmLocalXCodeGenerator.cxx
@@ -42,10 +42,9 @@ void cmLocalXCodeGenerator::Generate()
{
cmLocalGenerator::Generate();
- std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator iter = targets.begin();
- iter != targets.end(); ++iter) {
- (*iter)->HasMacOSXRpathInstallNameDir("");
+ const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
+ for (auto target : targets) {
+ target->HasMacOSXRpathInstallNameDir("");
}
}
@@ -53,10 +52,9 @@ void cmLocalXCodeGenerator::GenerateInstallRules()
{
cmLocalGenerator::GenerateInstallRules();
- std::vector<cmGeneratorTarget*> targets = this->GetGeneratorTargets();
- for (std::vector<cmGeneratorTarget*>::iterator iter = targets.begin();
- iter != targets.end(); ++iter) {
- (*iter)->HasMacOSXRpathInstallNameDir("");
+ const std::vector<cmGeneratorTarget*>& targets = this->GetGeneratorTargets();
+ for (auto target : targets) {
+ target->HasMacOSXRpathInstallNameDir("");
}
}
@@ -69,10 +67,8 @@ void cmLocalXCodeGenerator::ComputeObjectFilenames(
// to avoid exact duplicate file names. Note that Mac file names are not
// typically case sensitive, hence the LowerCase.
std::map<std::string, int> counts;
- for (std::map<cmSourceFile const*, std::string>::iterator si =
- mapping.begin();
- si != mapping.end(); ++si) {
- cmSourceFile const* sf = si->first;
+ for (auto& si : mapping) {
+ cmSourceFile const* sf = si.first;
std::string objectName =
cmSystemTools::GetFilenameWithoutLastExtension(sf->GetFullPath());
objectName += ".o";
@@ -82,6 +78,6 @@ void cmLocalXCodeGenerator::ComputeObjectFilenames(
if (2 == counts[objectNameLower]) {
// TODO: emit warning about duplicate name?
}
- si->second = objectName;
+ si.second = objectName;
}
}
diff --git a/Source/cmLocalXCodeGenerator.h b/Source/cmLocalXCodeGenerator.h
index 4ca02a9d0..8c9596f85 100644
--- a/Source/cmLocalXCodeGenerator.h
+++ b/Source/cmLocalXCodeGenerator.h
@@ -27,16 +27,16 @@ public:
///! Set cache only and recurse to false by default.
cmLocalXCodeGenerator(cmGlobalGenerator* gg, cmMakefile* mf);
- virtual ~cmLocalXCodeGenerator();
- virtual std::string GetTargetDirectory(
- cmGeneratorTarget const* target) const;
- virtual void AppendFlagEscape(std::string& flags,
- const std::string& rawFlag);
- virtual void Generate();
+ ~cmLocalXCodeGenerator() override;
+ std::string GetTargetDirectory(
+ cmGeneratorTarget const* target) const override;
+ void AppendFlagEscape(std::string& flags,
+ const std::string& rawFlag) override;
+ void Generate() override;
virtual void GenerateInstallRules();
- virtual void ComputeObjectFilenames(
+ void ComputeObjectFilenames(
std::map<cmSourceFile const*, std::string>& mapping,
- cmGeneratorTarget const* gt = 0);
+ cmGeneratorTarget const* gt = nullptr) override;
private:
};
diff --git a/Source/cmLocale.h b/Source/cmLocale.h
index 9f90a3a99..174f0f0f2 100644
--- a/Source/cmLocale.h
+++ b/Source/cmLocale.h
@@ -3,7 +3,7 @@
#ifndef cmLocale_h
#define cmLocale_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <locale.h>
#include <string>
@@ -14,7 +14,7 @@ class cmLocaleRAII
public:
cmLocaleRAII()
- : OldLocale(setlocale(LC_CTYPE, CM_NULLPTR))
+ : OldLocale(setlocale(LC_CTYPE, nullptr))
{
setlocale(LC_CTYPE, "");
}
diff --git a/Source/cmMSVC60LinkLineComputer.h b/Source/cmMSVC60LinkLineComputer.h
index f2892d53f..31223ecd4 100644
--- a/Source/cmMSVC60LinkLineComputer.h
+++ b/Source/cmMSVC60LinkLineComputer.h
@@ -4,7 +4,7 @@
#ifndef cmMSVC60LinkLineComputer_h
#define cmMSVC60LinkLineComputer_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
@@ -21,8 +21,7 @@ public:
cmMSVC60LinkLineComputer(cmOutputConverter* outputConverter,
cmStateDirectory const& stateDir);
- std::string ConvertToLinkReference(std::string const& input) const
- CM_OVERRIDE;
+ std::string ConvertToLinkReference(std::string const& input) const override;
};
#endif
diff --git a/Source/cmMachO.cxx b/Source/cmMachO.cxx
index a4350f7ce..7294c1cbf 100644
--- a/Source/cmMachO.cxx
+++ b/Source/cmMachO.cxx
@@ -134,7 +134,7 @@ public:
: cmMachOHeaderAndLoadCommands(_swap)
{
}
- bool read_mach_o(cmsys::ifstream& fin)
+ bool read_mach_o(cmsys::ifstream& fin) override
{
if (!read(fin, this->Header)) {
return false;
@@ -251,8 +251,7 @@ cmMachOInternal::cmMachOInternal(const char* fname)
}
// parse each Mach-O file
- for (size_t i = 0; i < this->FatArchs.size(); i++) {
- const fat_arch& arch = this->FatArchs[i];
+ for (const auto& arch : this->FatArchs) {
if (!this->read_mach_o(OSSwapBigToHostInt32(arch.offset))) {
return;
}
@@ -265,8 +264,8 @@ cmMachOInternal::cmMachOInternal(const char* fname)
cmMachOInternal::~cmMachOInternal()
{
- for (size_t i = 0; i < this->MachOList.size(); i++) {
- delete this->MachOList[i];
+ for (auto& i : this->MachOList) {
+ delete i;
}
}
@@ -283,7 +282,7 @@ bool cmMachOInternal::read_mach_o(uint32_t file_offset)
return false;
}
- cmMachOHeaderAndLoadCommands* f = NULL;
+ cmMachOHeaderAndLoadCommands* f = nullptr;
if (magic == MH_CIGAM || magic == MH_MAGIC) {
bool swap = false;
if (magic == MH_CIGAM) {
@@ -313,7 +312,7 @@ bool cmMachOInternal::read_mach_o(uint32_t file_offset)
// External class implementation.
cmMachO::cmMachO(const char* fname)
- : Internal(0)
+ : Internal(nullptr)
{
this->Internal = new cmMachOInternal(fname);
}
diff --git a/Source/cmMachO.h b/Source/cmMachO.h
index 42745cf60..aa17c6a77 100644
--- a/Source/cmMachO.h
+++ b/Source/cmMachO.h
@@ -3,7 +3,7 @@
#ifndef cmMachO_h
#define cmMachO_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <string>
diff --git a/Source/cmMacroCommand.cxx b/Source/cmMacroCommand.cxx
index a6a9ea316..74a1da00e 100644
--- a/Source/cmMacroCommand.cxx
+++ b/Source/cmMacroCommand.cxx
@@ -19,12 +19,12 @@ public:
cmMacroHelperCommand() {}
///! clean up any memory allocated by the macro
- ~cmMacroHelperCommand() CM_OVERRIDE {}
+ ~cmMacroHelperCommand() override {}
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
cmMacroHelperCommand* newC = new cmMacroHelperCommand;
// we must copy when we clone
@@ -40,10 +40,10 @@ public:
* the CMakeLists.txt file.
*/
bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
- cmExecutionStatus&) CM_OVERRIDE;
+ cmExecutionStatus&) override;
bool InitialPass(std::vector<std::string> const&,
- cmExecutionStatus&) CM_OVERRIDE
+ cmExecutionStatus&) override
{
return false;
}
@@ -98,20 +98,18 @@ bool cmMacroHelperCommand::InvokeInitialPass(
// Invoke all the functions that were collected in the block.
cmListFileFunction newLFF;
// for each function
- for (unsigned int c = 0; c < this->Functions.size(); ++c) {
+ for (cmListFileFunction const& func : this->Functions) {
// Replace the formal arguments and then invoke the command.
newLFF.Arguments.clear();
- newLFF.Arguments.reserve(this->Functions[c].Arguments.size());
- newLFF.Name = this->Functions[c].Name;
- newLFF.Line = this->Functions[c].Line;
+ newLFF.Arguments.reserve(func.Arguments.size());
+ newLFF.Name = func.Name;
+ newLFF.Line = func.Line;
// for each argument of the current function
- for (std::vector<cmListFileArgument>::iterator k =
- this->Functions[c].Arguments.begin();
- k != this->Functions[c].Arguments.end(); ++k) {
+ for (cmListFileArgument const& k : func.Arguments) {
cmListFileArgument arg;
- arg.Value = k->Value;
- if (k->Delim != cmListFileArgument::Bracket) {
+ arg.Value = k.Value;
+ if (k.Delim != cmListFileArgument::Bracket) {
// replace formal arguments
for (unsigned int j = 0; j < variables.size(); ++j) {
cmSystemTools::ReplaceString(arg.Value, variables[j],
@@ -131,8 +129,8 @@ bool cmMacroHelperCommand::InvokeInitialPass(
}
}
}
- arg.Delim = k->Delim;
- arg.Line = k->Line;
+ arg.Delim = k.Delim;
+ arg.Line = k.Line;
newLFF.Arguments.push_back(arg);
}
cmExecutionStatus status;
diff --git a/Source/cmMacroCommand.h b/Source/cmMacroCommand.h
index 0d35fe06e..d967388bf 100644
--- a/Source/cmMacroCommand.h
+++ b/Source/cmMacroCommand.h
@@ -3,7 +3,7 @@
#ifndef cmMacroCommand_h
#define cmMacroCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -19,10 +19,10 @@ class cmMacroFunctionBlocker : public cmFunctionBlocker
{
public:
cmMacroFunctionBlocker() { this->Depth = 0; }
- ~cmMacroFunctionBlocker() CM_OVERRIDE {}
+ ~cmMacroFunctionBlocker() override {}
bool IsFunctionBlocked(const cmListFileFunction&, cmMakefile& mf,
- cmExecutionStatus&) CM_OVERRIDE;
- bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf) CM_OVERRIDE;
+ cmExecutionStatus&) override;
+ bool ShouldRemove(const cmListFileFunction&, cmMakefile& mf) override;
std::vector<std::string> Args;
std::vector<cmListFileFunction> Functions;
@@ -36,14 +36,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmMacroCommand; }
+ cmCommand* Clone() override { return new cmMacroCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmMakeDirectoryCommand.h b/Source/cmMakeDirectoryCommand.h
index af72eab96..d2637f388 100644
--- a/Source/cmMakeDirectoryCommand.h
+++ b/Source/cmMakeDirectoryCommand.h
@@ -3,7 +3,7 @@
#ifndef cmMakeDirectoryCommand_h
#define cmMakeDirectoryCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -27,14 +27,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmMakeDirectoryCommand; }
+ cmCommand* Clone() override { return new cmMakeDirectoryCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmMakefile.cxx b/Source/cmMakefile.cxx
index 608b18a46..5643c978d 100644
--- a/Source/cmMakefile.cxx
+++ b/Source/cmMakefile.cxx
@@ -7,6 +7,7 @@
#include <algorithm>
#include <assert.h>
#include <ctype.h>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdlib.h>
#include <string.h>
@@ -37,7 +38,6 @@
#include "cmTestGenerator.h" // IWYU pragma: keep
#include "cmVersion.h"
#include "cmWorkingDirectory.h"
-#include "cm_auto_ptr.hxx"
#include "cm_sys_stat.h"
#include "cmake.h"
@@ -66,8 +66,8 @@ cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator,
this->DefineFlags = " ";
- this->cmDefineRegex.compile("#cmakedefine[ \t]+([A-Za-z_0-9]*)");
- this->cmDefine01Regex.compile("#cmakedefine01[ \t]+([A-Za-z_0-9]*)");
+ this->cmDefineRegex.compile("#([ \t]*)cmakedefine[ \t]+([A-Za-z_0-9]*)");
+ this->cmDefine01Regex.compile("#([ \t]*)cmakedefine01[ \t]+([A-Za-z_0-9]*)");
this->cmAtVarRegex.compile("(@[A-Za-z_0-9/.+-]+@)");
this->cmNamedCurly.compile("^[A-Za-z0-9/_.+-]+{");
@@ -87,12 +87,10 @@ cmMakefile::cmMakefile(cmGlobalGenerator* globalGenerator,
#if defined(CMAKE_BUILD_WITH_CMAKE)
this->AddSourceGroup("", "^.*$");
- this->AddSourceGroup("Source Files",
- "\\.(C|M|c|c\\+\\+|cc|cpp|cxx|f|f90|for|fpp"
- "|ftn|m|mm|rc|def|r|odl|idl|hpj|bat)$");
+ this->AddSourceGroup("Source Files", CM_SOURCE_REGEX);
this->AddSourceGroup("Header Files", CM_HEADER_REGEX);
this->AddSourceGroup("CMake Rules", "\\.rule$");
- this->AddSourceGroup("Resources", "\\.plist$");
+ this->AddSourceGroup("Resources", CM_RESOURCE_REGEX);
this->AddSourceGroup("Object Files", "\\.(lo|o|obj)$");
this->ObjectLibrariesSourceGroupIndex = this->SourceGroups.size();
@@ -208,15 +206,13 @@ void cmMakefile::PrintCommandTrace(const cmListFileFunction& lff) const
msg << lff.Name << "(";
bool expand = this->GetCMakeInstance()->GetTraceExpand();
std::string temp;
- for (std::vector<cmListFileArgument>::const_iterator i =
- lff.Arguments.begin();
- i != lff.Arguments.end(); ++i) {
+ for (cmListFileArgument const& arg : lff.Arguments) {
if (expand) {
- temp = i->Value;
+ temp = arg.Value;
this->ExpandVariablesInString(temp);
msg << temp;
} else {
- msg << i->Value;
+ msg << arg.Value;
}
msg << " ";
}
@@ -268,7 +264,7 @@ bool cmMakefile::ExecuteCommand(const cmListFileFunction& lff,
// Lookup the command prototype.
if (cmCommand* proto = this->GetState()->GetCommand(name)) {
// Clone the prototype.
- CM_AUTO_PTR<cmCommand> pcmd(proto->Clone());
+ std::unique_ptr<cmCommand> pcmd(proto->Clone());
pcmd->SetMakefile(this);
// Decide whether to invoke the command.
@@ -588,11 +584,13 @@ void cmMakefile::EnforceDirectoryLevelRules() const
void cmMakefile::AddEvaluationFile(
const std::string& inputFile,
- CM_AUTO_PTR<cmCompiledGeneratorExpression> outputName,
- CM_AUTO_PTR<cmCompiledGeneratorExpression> condition, bool inputIsContent)
+ std::unique_ptr<cmCompiledGeneratorExpression> outputName,
+ std::unique_ptr<cmCompiledGeneratorExpression> condition,
+ bool inputIsContent)
{
this->EvaluationFiles.push_back(new cmGeneratorExpressionEvaluationFile(
- inputFile, outputName, condition, inputIsContent));
+ inputFile, std::move(outputName), std::move(condition), inputIsContent,
+ this->GetPolicyStatus(cmPolicies::CMP0070)));
}
std::vector<cmGeneratorExpressionEvaluationFile*>
@@ -641,9 +639,8 @@ void cmMakefile::FinalPass()
// give all the commands a chance to do something
// after the file has been parsed before generation
- for (std::vector<cmCommand*>::iterator i = this->FinalPassCommands.begin();
- i != this->FinalPassCommands.end(); ++i) {
- (*i)->FinalPass();
+ for (cmCommand* fpCommand : this->FinalPassCommands) {
+ fpCommand->FinalPass();
}
// go through all configured files and see which ones still exist.
@@ -740,9 +737,8 @@ void cmMakefile::AddCustomCommandToTarget(
}
// Always create the byproduct sources and mark them generated.
- for (std::vector<std::string>::const_iterator o = byproducts.begin();
- o != byproducts.end(); ++o) {
- if (cmSourceFile* out = this->GetOrCreateSource(*o, true)) {
+ for (std::string const& o : byproducts) {
+ if (cmSourceFile* out = this->GetOrCreateSource(o, true)) {
out->SetProperty("GENERATED", "1");
}
}
@@ -780,23 +776,21 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput(
// Make sure there is at least one output.
if (outputs.empty()) {
cmSystemTools::Error("Attempt to add a custom rule with no output!");
- return CM_NULLPTR;
+ return nullptr;
}
// Validate custom commands. TODO: More strict?
- for (cmCustomCommandLines::const_iterator i = commandLines.begin();
- i != commandLines.end(); ++i) {
- cmCustomCommandLine const& cl = *i;
+ for (cmCustomCommandLine const& cl : commandLines) {
if (!cl.empty() && !cl[0].empty() && cl[0][0] == '"') {
std::ostringstream e;
e << "COMMAND may not contain literal quotes:\n " << cl[0] << "\n";
this->IssueMessage(cmake::FATAL_ERROR, e.str());
- return CM_NULLPTR;
+ return nullptr;
}
}
// Choose a source file on which to store the custom command.
- cmSourceFile* file = CM_NULLPTR;
+ cmSourceFile* file = nullptr;
if (!commandLines.empty() && !main_dependency.empty()) {
// The main dependency was specified. Use it unless a different
// custom command already used it.
@@ -810,7 +804,7 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput(
}
// The existing custom command is different. We need to
// generate a rule file for this new command.
- file = CM_NULLPTR;
+ file = nullptr;
} else if (!file) {
file = this->CreateSource(main_dependency);
}
@@ -843,15 +837,13 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput(
}
// Always create the output sources and mark them generated.
- for (std::vector<std::string>::const_iterator o = outputs.begin();
- o != outputs.end(); ++o) {
- if (cmSourceFile* out = this->GetOrCreateSource(*o, true)) {
+ for (std::string const& o : outputs) {
+ if (cmSourceFile* out = this->GetOrCreateSource(o, true)) {
out->SetProperty("GENERATED", "1");
}
}
- for (std::vector<std::string>::const_iterator o = byproducts.begin();
- o != byproducts.end(); ++o) {
- if (cmSourceFile* out = this->GetOrCreateSource(*o, true)) {
+ for (std::string const& o : byproducts) {
+ if (cmSourceFile* out = this->GetOrCreateSource(o, true)) {
out->SetProperty("GENERATED", "1");
}
}
@@ -880,9 +872,8 @@ cmSourceFile* cmMakefile::AddCustomCommandToOutput(
void cmMakefile::UpdateOutputToSourceMap(
std::vector<std::string> const& outputs, cmSourceFile* source)
{
- for (std::vector<std::string>::const_iterator o = outputs.begin();
- o != outputs.end(); ++o) {
- this->UpdateOutputToSourceMap(*o, source);
+ for (std::string const& o : outputs) {
+ this->UpdateOutputToSourceMap(o, source);
}
}
@@ -934,7 +925,7 @@ void cmMakefile::AddCustomCommandOldStyle(
std::vector<std::string> no_byproducts;
this->AddCustomCommandToTarget(target, no_byproducts, depends,
commandLines, cmTarget::POST_BUILD, comment,
- CM_NULLPTR);
+ nullptr);
return;
}
@@ -942,24 +933,23 @@ void cmMakefile::AddCustomCommandOldStyle(
cmsys::RegularExpression sourceFiles("\\.(C|M|c|c\\+\\+|cc|cpp|cxx|m|mm|"
"rc|def|r|odl|idl|hpj|bat|h|h\\+\\+|"
"hm|hpp|hxx|in|txx|inl)$");
- for (std::vector<std::string>::const_iterator oi = outputs.begin();
- oi != outputs.end(); ++oi) {
+ for (std::string const& oi : outputs) {
// Get the name of this output.
- const char* output = oi->c_str();
+ const char* output = oi.c_str();
cmSourceFile* sf;
// Choose whether to use a main dependency.
if (sourceFiles.find(source)) {
// The source looks like a real file. Use it as the main dependency.
sf = this->AddCustomCommandToOutput(output, depends, source,
- commandLines, comment, CM_NULLPTR);
+ commandLines, comment, nullptr);
} else {
// The source may not be a real file. Do not use a main dependency.
std::string no_main_dependency;
std::vector<std::string> depends2 = depends;
depends2.push_back(source);
sf = this->AddCustomCommandToOutput(output, depends2, no_main_dependency,
- commandLines, comment, CM_NULLPTR);
+ commandLines, comment, nullptr);
}
// If the rule was added to the source (and not a .rule file),
@@ -1063,9 +1053,8 @@ cmTarget* cmMakefile::AddUtilityCommand(
}
// Always create the byproduct sources and mark them generated.
- for (std::vector<std::string>::const_iterator o = byproducts.begin();
- o != byproducts.end(); ++o) {
- if (cmSourceFile* out = this->GetOrCreateSource(*o, true)) {
+ for (std::string const& byproduct : byproducts) {
+ if (cmSourceFile* out = this->GetOrCreateSource(byproduct, true)) {
out->SetProperty("GENERATED", "1");
}
}
@@ -1227,15 +1216,17 @@ void cmMakefile::InitializeFromParent(cmMakefile* parent)
parent->GetProperty("COMPILE_DEFINITIONS"));
std::vector<std::string> configs;
this->GetConfigurations(configs);
- for (std::vector<std::string>::const_iterator ci = configs.begin();
- ci != configs.end(); ++ci) {
+ for (std::string const& config : configs) {
std::string defPropName = "COMPILE_DEFINITIONS_";
- defPropName += cmSystemTools::UpperCase(*ci);
+ defPropName += cmSystemTools::UpperCase(config);
const char* prop = parent->GetProperty(defPropName);
this->SetProperty(defPropName, prop);
}
}
+ // labels
+ this->SetProperty("LABELS", parent->GetProperty("LABELS"));
+
// link libraries
this->SetProperty("LINK_LIBRARIES", parent->GetProperty("LINK_LIBRARIES"));
@@ -1389,10 +1380,8 @@ void cmMakefile::Configure()
if (this->IsRootMakefile()) {
bool hasVersion = false;
// search for the right policy command
- for (std::vector<cmListFileFunction>::iterator i =
- listFile.Functions.begin();
- i != listFile.Functions.end(); ++i) {
- if (cmSystemTools::LowerCase(i->Name) == "cmake_minimum_required") {
+ for (cmListFileFunction const& func : listFile.Functions) {
+ if (cmSystemTools::LowerCase(func.Name) == "cmake_minimum_required") {
hasVersion = true;
break;
}
@@ -1418,10 +1407,8 @@ void cmMakefile::Configure()
allowedCommands.insert("option");
allowedCommands.insert("message");
isProblem = false;
- for (std::vector<cmListFileFunction>::iterator i =
- listFile.Functions.begin();
- i != listFile.Functions.end(); ++i) {
- std::string name = cmSystemTools::LowerCase(i->Name);
+ for (cmListFileFunction const& func : listFile.Functions) {
+ std::string name = cmSystemTools::LowerCase(func.Name);
if (allowedCommands.find(name) == allowedCommands.end()) {
isProblem = true;
break;
@@ -1440,10 +1427,8 @@ void cmMakefile::Configure()
}
bool hasProject = false;
// search for a project command
- for (std::vector<cmListFileFunction>::iterator i =
- listFile.Functions.begin();
- i != listFile.Functions.end(); ++i) {
- if (cmSystemTools::LowerCase(i->Name) == "project") {
+ for (cmListFileFunction const& func : listFile.Functions) {
+ if (cmSystemTools::LowerCase(func.Name) == "project") {
hasProject = true;
break;
}
@@ -1575,9 +1560,8 @@ std::vector<cmTarget*> cmMakefile::GetImportedTargets() const
{
std::vector<cmTarget*> tgts;
tgts.reserve(this->ImportedTargets.size());
- for (TargetMap::const_iterator it = this->ImportedTargets.begin();
- it != this->ImportedTargets.end(); ++it) {
- tgts.push_back(it->second);
+ for (auto const& impTarget : this->ImportedTargets) {
+ tgts.push_back(impTarget.second);
}
return tgts;
}
@@ -1600,9 +1584,8 @@ void cmMakefile::AddIncludeDirectories(const std::vector<std::string>& incs,
}
// Property on each target:
- for (cmTargets::iterator l = this->Targets.begin(); l != this->Targets.end();
- ++l) {
- cmTarget& t = l->second;
+ for (auto& target : this->Targets) {
+ cmTarget& t = target.second;
t.InsertInclude(entryString, lfbt, before);
}
}
@@ -1615,9 +1598,8 @@ void cmMakefile::AddSystemIncludeDirectories(const std::set<std::string>& incs)
this->SystemIncludeDirectories.insert(incs.begin(), incs.end());
- for (cmTargets::iterator l = this->Targets.begin(); l != this->Targets.end();
- ++l) {
- cmTarget& t = l->second;
+ for (auto& target : this->Targets) {
+ cmTarget& t = target.second;
t.AddSystemIncludeDirectories(incs);
}
}
@@ -1664,7 +1646,7 @@ void cmMakefile::AddCacheDefinition(const std::string& name, const char* value,
nvalue = value ? value : "";
cmSystemTools::ExpandListArgument(nvalue, files);
- nvalue = "";
+ nvalue.clear();
for (cc = 0; cc < files.size(); cc++) {
if (!cmSystemTools::IsOff(files[cc].c_str())) {
files[cc] = cmSystemTools::CollapseFullPath(files[cc]);
@@ -1757,7 +1739,7 @@ void cmMakefile::RemoveDefinition(const std::string& name)
cmVariableWatch* vv = this->GetVariableWatch();
if (vv) {
vv->VariableAccessed(name, cmVariableWatch::VARIABLE_REMOVED_ACCESS,
- CM_NULLPTR, this);
+ nullptr, this);
}
#endif
}
@@ -1786,14 +1768,13 @@ void cmMakefile::AddGlobalLinkInformation(cmTarget& target)
std::vector<std::string> linkDirs;
cmSystemTools::ExpandListArgument(linkDirsProp, linkDirs);
- for (std::vector<std::string>::iterator j = linkDirs.begin();
- j != linkDirs.end(); ++j) {
- std::string newdir = *j;
+ for (std::string const& linkDir : linkDirs) {
+ std::string newdir = linkDir;
// remove trailing slashes
- if (*j->rbegin() == '/') {
- newdir = j->substr(0, j->size() - 1);
+ if (*linkDir.rbegin() == '/') {
+ newdir = linkDir.substr(0, linkDir.size() - 1);
}
- target.AddLinkDirectory(*j);
+ target.AddLinkDirectory(linkDir);
}
}
@@ -1886,29 +1867,26 @@ cmSourceFile* cmMakefile::LinearGetSourceFileWithOutput(
// look through all the source files that have custom commands
// and see if the custom command has the passed source file as an output
- for (std::vector<cmSourceFile*>::const_iterator i =
- this->SourceFiles.begin();
- i != this->SourceFiles.end(); ++i) {
+ for (cmSourceFile* src : this->SourceFiles) {
// does this source file have a custom command?
- if ((*i)->GetCustomCommand()) {
+ if (src->GetCustomCommand()) {
// Does the output of the custom command match the source file name?
const std::vector<std::string>& outputs =
- (*i)->GetCustomCommand()->GetOutputs();
- for (std::vector<std::string>::const_iterator o = outputs.begin();
- o != outputs.end(); ++o) {
- out = *o;
+ src->GetCustomCommand()->GetOutputs();
+ for (std::string const& output : outputs) {
+ out = output;
std::string::size_type pos = out.rfind(name);
// If the output matches exactly
if (pos != std::string::npos && pos == out.size() - name.size() &&
(pos == 0 || out[pos - 1] == '/')) {
- return *i;
+ return src;
}
}
}
}
// otherwise return NULL
- return CM_NULLPTR;
+ return nullptr;
}
cmSourceFile* cmMakefile::GetSourceFileWithOutput(
@@ -1924,31 +1902,29 @@ cmSourceFile* cmMakefile::GetSourceFileWithOutput(
if (o != this->OutputToSource.end()) {
return (*o).second;
}
- return CM_NULLPTR;
+ return nullptr;
}
#if defined(CMAKE_BUILD_WITH_CMAKE)
cmSourceGroup* cmMakefile::GetSourceGroup(
const std::vector<std::string>& name) const
{
- cmSourceGroup* sg = CM_NULLPTR;
+ cmSourceGroup* sg = nullptr;
// first look for source group starting with the same as the one we want
- for (std::vector<cmSourceGroup>::const_iterator sgIt =
- this->SourceGroups.begin();
- sgIt != this->SourceGroups.end(); ++sgIt) {
- std::string sgName = sgIt->GetName();
+ for (cmSourceGroup const& srcGroup : this->SourceGroups) {
+ std::string sgName = srcGroup.GetName();
if (sgName == name[0]) {
- sg = const_cast<cmSourceGroup*>(&(*sgIt));
+ sg = const_cast<cmSourceGroup*>(&srcGroup);
break;
}
}
- if (sg != CM_NULLPTR) {
+ if (sg != nullptr) {
// iterate through its children to find match source group
for (unsigned int i = 1; i < name.size(); ++i) {
sg = sg->LookupChild(name[i].c_str());
- if (sg == CM_NULLPTR) {
+ if (sg == nullptr) {
break;
}
}
@@ -1966,14 +1942,14 @@ void cmMakefile::AddSourceGroup(const std::string& name, const char* regex)
void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
const char* regex)
{
- cmSourceGroup* sg = CM_NULLPTR;
+ cmSourceGroup* sg = nullptr;
std::vector<std::string> currentName;
int i = 0;
const int lastElement = static_cast<int>(name.size() - 1);
for (i = lastElement; i >= 0; --i) {
currentName.assign(name.begin(), name.begin() + i + 1);
sg = this->GetSourceGroup(currentName);
- if (sg != CM_NULLPTR) {
+ if (sg != nullptr) {
break;
}
}
@@ -2001,14 +1977,65 @@ void cmMakefile::AddSourceGroup(const std::vector<std::string>& name,
}
// build the whole source group path
for (++i; i <= lastElement; ++i) {
- sg->AddChild(
- cmSourceGroup(name[i].c_str(), CM_NULLPTR, sg->GetFullName()));
+ sg->AddChild(cmSourceGroup(name[i].c_str(), nullptr, sg->GetFullName()));
sg = sg->LookupChild(name[i].c_str());
}
sg->SetGroupRegex(regex);
}
+cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(
+ const std::vector<std::string>& folders)
+{
+ cmSourceGroup* sg = this->GetSourceGroup(folders);
+ if (sg == nullptr) {
+ this->AddSourceGroup(folders);
+ sg = this->GetSourceGroup(folders);
+ }
+ return sg;
+}
+
+cmSourceGroup* cmMakefile::GetOrCreateSourceGroup(const std::string& name)
+{
+ const char* delimiter = this->GetDefinition("SOURCE_GROUP_DELIMITER");
+ if (delimiter == nullptr) {
+ delimiter = "\\";
+ }
+ return this->GetOrCreateSourceGroup(
+ cmSystemTools::tokenize(name, delimiter));
+}
+
+/**
+ * Find a source group whose regular expression matches the filename
+ * part of the given source name. Search backward through the list of
+ * source groups, and take the first matching group found. This way
+ * non-inherited SOURCE_GROUP commands will have precedence over
+ * inherited ones.
+ */
+cmSourceGroup* cmMakefile::FindSourceGroup(
+ const char* source, std::vector<cmSourceGroup>& groups) const
+{
+ // First search for a group that lists the file explicitly.
+ for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin();
+ sg != groups.rend(); ++sg) {
+ cmSourceGroup* result = sg->MatchChildrenFiles(source);
+ if (result) {
+ return result;
+ }
+ }
+
+ // Now search for a group whose regex matches the file.
+ for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin();
+ sg != groups.rend(); ++sg) {
+ cmSourceGroup* result = sg->MatchChildrenRegex(source);
+ if (result) {
+ return result;
+ }
+ }
+
+ // Shouldn't get here, but just in case, return the default group.
+ return &groups.front();
+}
#endif
static bool mightExpandVariablesCMP0019(const char* s)
@@ -2041,9 +2068,8 @@ void cmMakefile::ExpandVariablesCMP0019()
}
// Also for each target's INCLUDE_DIRECTORIES property:
- for (cmTargets::iterator l = this->Targets.begin(); l != this->Targets.end();
- ++l) {
- cmTarget& t = l->second;
+ for (auto& target : this->Targets) {
+ cmTarget& t = target.second;
if (t.GetType() == cmStateEnums::INTERFACE_LIBRARY ||
t.GetType() == cmStateEnums::GLOBAL_TARGET) {
continue;
@@ -2190,9 +2216,9 @@ bool cmMakefile::PlatformIsAppleIos() const
"iphonesimulator", "watchos", "watchsimulator",
};
- for (size_t i = 0; i < sizeof(embedded) / sizeof(embedded[0]); ++i) {
- if (sdkRoot.find(embedded[i]) == 0 ||
- sdkRoot.find(std::string("/") + embedded[i]) != std::string::npos) {
+ for (std::string const& i : embedded) {
+ if (sdkRoot.find(i) == 0 ||
+ sdkRoot.find(std::string("/") + i) != std::string::npos) {
return true;
}
}
@@ -2252,7 +2278,7 @@ bool cmMakefile::IsDefinitionSet(const std::string& name) const
}
}
#endif
- return def != CM_NULLPTR;
+ return def != nullptr;
}
const char* cmMakefile::GetDefinition(const std::string& name) const
@@ -2423,7 +2449,7 @@ cmake::MessageType cmMakefile::ExpandVariablesInStringOld(
std::string input = source;
// Start with empty output.
- source = "";
+ source.clear();
// Look for one @VAR@ at a time.
const char* in = input.c_str();
@@ -2561,7 +2587,7 @@ cmake::MessageType cmMakefile::ExpandVariablesInStringNew(
openstack.pop_back();
result.append(last, in - last);
std::string const& lookup = result.substr(var.loc);
- const char* value = CM_NULLPTR;
+ const char* value = nullptr;
std::string varresult;
std::string svalue;
static const std::string lineVar = "CMAKE_CURRENT_LIST_LINE";
@@ -2617,7 +2643,7 @@ cmake::MessageType cmMakefile::ExpandVariablesInStringNew(
if (!atOnly) {
t_lookup lookup;
const char* next = in + 1;
- const char* start = CM_NULLPTR;
+ const char* start = nullptr;
char nextc = *next;
if (nextc == '{') {
// Looking for a variable.
@@ -2817,40 +2843,6 @@ std::string cmMakefile::GetConfigurations(std::vector<std::string>& configs,
return buildType;
}
-#if defined(CMAKE_BUILD_WITH_CMAKE)
-/**
- * Find a source group whose regular expression matches the filename
- * part of the given source name. Search backward through the list of
- * source groups, and take the first matching group found. This way
- * non-inherited SOURCE_GROUP commands will have precedence over
- * inherited ones.
- */
-cmSourceGroup* cmMakefile::FindSourceGroup(
- const char* source, std::vector<cmSourceGroup>& groups) const
-{
- // First search for a group that lists the file explicitly.
- for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin();
- sg != groups.rend(); ++sg) {
- cmSourceGroup* result = sg->MatchChildrenFiles(source);
- if (result) {
- return result;
- }
- }
-
- // Now search for a group whose regex matches the file.
- for (std::vector<cmSourceGroup>::reverse_iterator sg = groups.rbegin();
- sg != groups.rend(); ++sg) {
- cmSourceGroup* result = sg->MatchChildrenRegex(source);
- if (result) {
- return result;
- }
- }
-
- // Shouldn't get here, but just in case, return the default group.
- return &groups.front();
-}
-#endif
-
bool cmMakefile::IsFunctionBlocked(const cmListFileFunction& lff,
cmExecutionStatus& status)
{
@@ -2883,7 +2875,7 @@ void cmMakefile::PopFunctionBlockerBarrier(bool reportError)
FunctionBlockersType::size_type barrier =
this->FunctionBlockerBarriers.back();
while (this->FunctionBlockers.size() > barrier) {
- CM_AUTO_PTR<cmFunctionBlocker> fb(this->FunctionBlockers.back());
+ std::unique_ptr<cmFunctionBlocker> fb(this->FunctionBlockers.back());
this->FunctionBlockers.pop_back();
if (reportError) {
// Report the context in which the unclosed block was opened.
@@ -2948,23 +2940,22 @@ bool cmMakefile::ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
if (!filename) {
filename = efp.c_str();
}
- std::vector<cmListFileArgument>::const_iterator i;
std::string value;
outArgs.reserve(inArgs.size());
- for (i = inArgs.begin(); i != inArgs.end(); ++i) {
+ for (cmListFileArgument const& i : inArgs) {
// No expansion in a bracket argument.
- if (i->Delim == cmListFileArgument::Bracket) {
- outArgs.push_back(i->Value);
+ if (i.Delim == cmListFileArgument::Bracket) {
+ outArgs.push_back(i.Value);
continue;
}
// Expand the variables in the argument.
- value = i->Value;
- this->ExpandVariablesInString(value, false, false, false, filename,
- i->Line, false, false);
+ value = i.Value;
+ this->ExpandVariablesInString(value, false, false, false, filename, i.Line,
+ false, false);
// If the argument is quoted, it should be one argument.
// Otherwise, it may be a list of arguments.
- if (i->Delim == cmListFileArgument::Quoted) {
+ if (i.Delim == cmListFileArgument::Quoted) {
outArgs.push_back(value);
} else {
cmSystemTools::ExpandListArgument(value, outArgs);
@@ -2981,29 +2972,28 @@ bool cmMakefile::ExpandArguments(
if (!filename) {
filename = efp.c_str();
}
- std::vector<cmListFileArgument>::const_iterator i;
std::string value;
outArgs.reserve(inArgs.size());
- for (i = inArgs.begin(); i != inArgs.end(); ++i) {
+ for (cmListFileArgument const& i : inArgs) {
// No expansion in a bracket argument.
- if (i->Delim == cmListFileArgument::Bracket) {
- outArgs.push_back(cmExpandedCommandArgument(i->Value, true));
+ if (i.Delim == cmListFileArgument::Bracket) {
+ outArgs.push_back(cmExpandedCommandArgument(i.Value, true));
continue;
}
// Expand the variables in the argument.
- value = i->Value;
- this->ExpandVariablesInString(value, false, false, false, filename,
- i->Line, false, false);
+ value = i.Value;
+ this->ExpandVariablesInString(value, false, false, false, filename, i.Line,
+ false, false);
// If the argument is quoted, it should be one argument.
// Otherwise, it may be a list of arguments.
- if (i->Delim == cmListFileArgument::Quoted) {
+ if (i.Delim == cmListFileArgument::Quoted) {
outArgs.push_back(cmExpandedCommandArgument(value, true));
} else {
std::vector<std::string> stringArgs;
cmSystemTools::ExpandListArgument(value, stringArgs);
- for (size_t j = 0; j < stringArgs.size(); ++j) {
- outArgs.push_back(cmExpandedCommandArgument(stringArgs[j], false));
+ for (std::string const& stringArg : stringArgs) {
+ outArgs.push_back(cmExpandedCommandArgument(stringArg, false));
}
}
}
@@ -3020,7 +3010,7 @@ void cmMakefile::AddFunctionBlocker(cmFunctionBlocker* fb)
this->FunctionBlockers.push_back(fb);
}
-CM_AUTO_PTR<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker(
+std::unique_ptr<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker(
cmFunctionBlocker* fb, const cmListFileFunction& lff)
{
// Find the function blocker stack barrier for the current scope.
@@ -3053,11 +3043,11 @@ CM_AUTO_PTR<cmFunctionBlocker> cmMakefile::RemoveFunctionBlocker(
}
cmFunctionBlocker* b = *pos;
this->FunctionBlockers.erase(pos);
- return CM_AUTO_PTR<cmFunctionBlocker>(b);
+ return std::unique_ptr<cmFunctionBlocker>(b);
}
}
- return CM_AUTO_PTR<cmFunctionBlocker>();
+ return std::unique_ptr<cmFunctionBlocker>();
}
const char* cmMakefile::GetHomeDirectory() const
@@ -3093,15 +3083,12 @@ void cmMakefile::SetArgcArgv(const std::vector<std::string>& args)
cmSourceFile* cmMakefile::GetSource(const std::string& sourceName) const
{
cmSourceFileLocation sfl(this, sourceName);
- for (std::vector<cmSourceFile*>::const_iterator sfi =
- this->SourceFiles.begin();
- sfi != this->SourceFiles.end(); ++sfi) {
- cmSourceFile* sf = *sfi;
+ for (cmSourceFile* sf : this->SourceFiles) {
if (sf->Matches(sfl)) {
return sf;
}
}
- return CM_NULLPTR;
+ return nullptr;
}
cmSourceFile* cmMakefile::CreateSource(const std::string& sourceName,
@@ -3147,12 +3134,11 @@ void cmMakefile::EnableLanguage(std::vector<std::string> const& lang,
std::vector<std::string> langs;
std::vector<std::string> langsRC;
langs.reserve(lang.size());
- for (std::vector<std::string>::const_iterator i = lang.begin();
- i != lang.end(); ++i) {
- if (*i == "RC") {
- langsRC.push_back(*i);
+ for (std::string const& i : lang) {
+ if (i == "RC") {
+ langsRC.push_back(i);
} else {
- langs.push_back(*i);
+ langs.push_back(i);
}
}
if (!langs.empty()) {
@@ -3200,8 +3186,8 @@ int cmMakefile::TryCompile(const std::string& srcdir,
// do a configure
cm.SetHomeDirectory(srcdir);
cm.SetHomeOutputDirectory(bindir);
- cm.SetGeneratorPlatform(this->GetCMakeInstance()->GetGeneratorPlatform());
- cm.SetGeneratorToolset(this->GetCMakeInstance()->GetGeneratorToolset());
+ cm.SetGeneratorPlatform(this->GetSafeDefinition("CMAKE_GENERATOR_PLATFORM"));
+ cm.SetGeneratorToolset(this->GetSafeDefinition("CMAKE_GENERATOR_TOOLSET"));
cm.LoadCache();
if (!gg->IsMultiConfig()) {
if (const char* config =
@@ -3302,7 +3288,7 @@ cmVariableWatch* cmMakefile::GetVariableWatch() const
this->GetCMakeInstance()->GetVariableWatch()) {
return this->GetCMakeInstance()->GetVariableWatch();
}
- return CM_NULLPTR;
+ return nullptr;
}
#endif
@@ -3346,9 +3332,7 @@ std::string cmMakefile::GetModulesFile(const char* filename) const
cmSystemTools::ExpandListArgument(cmakeModulePath, modulePath);
// Look through the possible module directories.
- for (std::vector<std::string>::iterator i = modulePath.begin();
- i != modulePath.end(); ++i) {
- std::string itempl = *i;
+ for (std::string itempl : modulePath) {
cmSystemTools::ConvertToUnixSlashes(itempl);
itempl += "/";
itempl += filename;
@@ -3365,7 +3349,7 @@ std::string cmMakefile::GetModulesFile(const char* filename) const
moduleInCMakeRoot += filename;
cmSystemTools::ConvertToUnixSlashes(moduleInCMakeRoot);
if (!cmSystemTools::FileExists(moduleInCMakeRoot.c_str())) {
- moduleInCMakeRoot = "";
+ moduleInCMakeRoot.clear();
}
// Normally, prefer the files found in CMAKE_MODULE_PATH. Only when the file
@@ -3432,18 +3416,22 @@ void cmMakefile::ConfigureString(const std::string& input, std::string& output,
// Replace #cmakedefine instances.
if (this->cmDefineRegex.find(line)) {
- const char* def = this->GetDefinition(this->cmDefineRegex.match(1));
+ const char* def = this->GetDefinition(this->cmDefineRegex.match(2));
if (!cmSystemTools::IsOff(def)) {
- cmSystemTools::ReplaceString(line, "#cmakedefine", "#define");
+ const std::string indentation = this->cmDefineRegex.match(1);
+ cmSystemTools::ReplaceString(line, "#" + indentation + "cmakedefine",
+ "#" + indentation + "define");
output += line;
} else {
output += "/* #undef ";
- output += this->cmDefineRegex.match(1);
+ output += this->cmDefineRegex.match(2);
output += " */";
}
} else if (this->cmDefine01Regex.find(line)) {
- const char* def = this->GetDefinition(this->cmDefine01Regex.match(1));
- cmSystemTools::ReplaceString(line, "#cmakedefine01", "#define");
+ const std::string indentation = this->cmDefine01Regex.match(1);
+ const char* def = this->GetDefinition(this->cmDefine01Regex.match(2));
+ cmSystemTools::ReplaceString(line, "#" + indentation + "cmakedefine01",
+ "#" + indentation + "define");
output += line;
if (!cmSystemTools::IsOff(def)) {
output += " 1";
@@ -3463,7 +3451,7 @@ void cmMakefile::ConfigureString(const std::string& input, std::string& output,
}
// Perform variable replacements.
- this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, CM_NULLPTR,
+ this->ExpandVariablesInString(output, escapeQuotes, true, atOnly, nullptr,
-1, true, true);
}
@@ -3545,7 +3533,7 @@ int cmMakefile::ConfigureFile(const char* infile, const char* outfile,
std::string inLine;
std::string outLine;
while (cmSystemTools::GetLineFromStream(fin, inLine)) {
- outLine = "";
+ outLine.clear();
this->ConfigureString(inLine, outLine, atOnly, escapeQuotes);
fout << outLine << newLineCharacters;
}
@@ -3603,7 +3591,7 @@ cmTarget* cmMakefile::FindLocalNonAliasTarget(const std::string& name) const
if (i != this->Targets.end()) {
return &i->second;
}
- return CM_NULLPTR;
+ return nullptr;
}
cmTest* cmMakefile::CreateTest(const std::string& testName)
@@ -3625,7 +3613,7 @@ cmTest* cmMakefile::GetTest(const std::string& testName) const
if (mi != this->Tests.end()) {
return mi->second;
}
- return CM_NULLPTR;
+ return nullptr;
}
void cmMakefile::AddCMakeDependFilesFromUser()
@@ -3634,14 +3622,13 @@ void cmMakefile::AddCMakeDependFilesFromUser()
if (const char* deps_str = this->GetProperty("CMAKE_CONFIGURE_DEPENDS")) {
cmSystemTools::ExpandListArgument(deps_str, deps);
}
- for (std::vector<std::string>::iterator i = deps.begin(); i != deps.end();
- ++i) {
- if (cmSystemTools::FileIsFullPath(i->c_str())) {
- this->AddCMakeDependFile(*i);
+ for (std::string const& dep : deps) {
+ if (cmSystemTools::FileIsFullPath(dep.c_str())) {
+ this->AddCMakeDependFile(dep);
} else {
std::string f = this->GetCurrentSourceDirectory();
f += "/";
- f += *i;
+ f += dep;
this->AddCMakeDependFile(f);
}
}
@@ -3717,7 +3704,7 @@ cmTarget* cmMakefile::AddImportedTarget(const std::string& name,
bool global)
{
// Create the target.
- CM_AUTO_PTR<cmTarget> target(
+ std::unique_ptr<cmTarget> target(
new cmTarget(name, type, global ? cmTarget::VisibilityImportedGlobally
: cmTarget::VisibilityImported,
this));
@@ -3896,16 +3883,6 @@ bool cmMakefile::EnforceUniqueDir(const std::string& srcPath,
return false;
}
-void cmMakefile::AddQtUiFileWithOptions(cmSourceFile* sf)
-{
- this->QtUiFilesWithOptions.push_back(sf);
-}
-
-std::vector<cmSourceFile*> cmMakefile::GetQtUiFilesWithOptions() const
-{
- return this->QtUiFilesWithOptions;
-}
-
static std::string const matchVariables[] = {
"CMAKE_MATCH_0", "CMAKE_MATCH_1", "CMAKE_MATCH_2", "CMAKE_MATCH_3",
"CMAKE_MATCH_4", "CMAKE_MATCH_5", "CMAKE_MATCH_6", "CMAKE_MATCH_7",
@@ -4093,10 +4070,10 @@ bool cmMakefile::IgnoreErrorsCMP0061() const
}
#define FEATURE_STRING(F) , #F
-static const char* const C_FEATURES[] = { CM_NULLPTR FOR_EACH_C_FEATURE(
+static const char* const C_FEATURES[] = { nullptr FOR_EACH_C_FEATURE(
FEATURE_STRING) };
-static const char* const CXX_FEATURES[] = { CM_NULLPTR FOR_EACH_CXX_FEATURE(
+static const char* const CXX_FEATURES[] = { nullptr FOR_EACH_CXX_FEATURE(
FEATURE_STRING) };
#undef FEATURE_STRING
@@ -4204,7 +4181,7 @@ const char* cmMakefile::CompileFeaturesAvailable(const std::string& lang,
this->GetCMakeInstance()->IssueMessage(cmake::FATAL_ERROR, e.str(),
this->Backtrace);
}
- return CM_NULLPTR;
+ return nullptr;
}
const char* featuresKnown =
@@ -4227,7 +4204,7 @@ const char* cmMakefile::CompileFeaturesAvailable(const std::string& lang,
this->GetCMakeInstance()->IssueMessage(cmake::FATAL_ERROR, e.str(),
this->Backtrace);
}
- return CM_NULLPTR;
+ return nullptr;
}
return featuresKnown;
}
@@ -4375,6 +4352,18 @@ bool cmMakefile::HaveCxxStandardAvailable(cmTarget const* target,
cmStrCmp(existingCxxStandard))
: cmArrayEnd(CXX_STANDARDS);
+ if (needCxx17 &&
+ existingCxxIt < std::find_if(cmArrayBegin(CXX_STANDARDS),
+ cmArrayEnd(CXX_STANDARDS),
+ cmStrCmp("17"))) {
+ return false;
+ }
+ if (needCxx14 &&
+ existingCxxIt < std::find_if(cmArrayBegin(CXX_STANDARDS),
+ cmArrayEnd(CXX_STANDARDS),
+ cmStrCmp("14"))) {
+ return false;
+ }
if (needCxx11 &&
existingCxxIt < std::find_if(cmArrayBegin(CXX_STANDARDS),
cmArrayEnd(CXX_STANDARDS),
diff --git a/Source/cmMakefile.h b/Source/cmMakefile.h
index e65ba468f..0273f5bae 100644
--- a/Source/cmMakefile.h
+++ b/Source/cmMakefile.h
@@ -3,15 +3,17 @@
#ifndef cmMakefile_h
#define cmMakefile_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmsys/RegularExpression.hxx"
#include <deque>
#include <map>
+#include <memory> // IWYU pragma: keep
#include <set>
#include <stack>
#include <stddef.h>
#include <string>
+#include <unordered_map>
#include <vector>
#include "cmAlgorithms.h"
@@ -21,8 +23,6 @@
#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmTarget.h"
-#include "cm_auto_ptr.hxx"
-#include "cm_unordered_map.hxx"
#include "cmake.h"
#if defined(CMAKE_BUILD_WITH_CMAKE)
@@ -92,7 +92,7 @@ public:
* Remove the function blocker whose scope ends with the given command.
* This returns ownership of the function blocker object.
*/
- CM_AUTO_PTR<cmFunctionBlocker> RemoveFunctionBlocker(
+ std::unique_ptr<cmFunctionBlocker> RemoveFunctionBlocker(
cmFunctionBlocker* fb, const cmListFileFunction& lff);
/**
@@ -187,24 +187,26 @@ public:
* Add a utility to the build. A utiltity target is a command that
* is run every time the target is built.
*/
- cmTarget* AddUtilityCommand(
- const std::string& utilityName, bool excludeFromAll,
- const std::vector<std::string>& depends, const char* workingDirectory,
- const char* command, const char* arg1 = CM_NULLPTR,
- const char* arg2 = CM_NULLPTR, const char* arg3 = CM_NULLPTR,
- const char* arg4 = CM_NULLPTR);
+ cmTarget* AddUtilityCommand(const std::string& utilityName,
+ bool excludeFromAll,
+ const std::vector<std::string>& depends,
+ const char* workingDirectory,
+ const char* command, const char* arg1 = nullptr,
+ const char* arg2 = nullptr,
+ const char* arg3 = nullptr,
+ const char* arg4 = nullptr);
cmTarget* AddUtilityCommand(
const std::string& utilityName, bool excludeFromAll,
const char* workingDirectory, const std::vector<std::string>& depends,
const cmCustomCommandLines& commandLines, bool escapeOldStyle = true,
- const char* comment = CM_NULLPTR, bool uses_terminal = false,
+ const char* comment = nullptr, bool uses_terminal = false,
bool command_expand_lists = false);
cmTarget* AddUtilityCommand(
const std::string& utilityName, bool excludeFromAll,
const char* workingDirectory, const std::vector<std::string>& byproducts,
const std::vector<std::string>& depends,
const cmCustomCommandLines& commandLines, bool escapeOldStyle = true,
- const char* comment = CM_NULLPTR, bool uses_terminal = false,
+ const char* comment = nullptr, bool uses_terminal = false,
bool command_expand_lists = false);
/**
@@ -268,21 +270,6 @@ public:
bool excludeFromAll = false);
void AddAlias(const std::string& libname, const std::string& tgt);
-#if defined(CMAKE_BUILD_WITH_CMAKE)
- /**
- * Add a root source group for consideration when adding a new source.
- */
- void AddSourceGroup(const std::string& name, const char* regex = CM_NULLPTR);
-
- /**
- * Add a source group for consideration when adding a new source.
- * name is tokenized.
- */
- void AddSourceGroup(const std::vector<std::string>& name,
- const char* regex = CM_NULLPTR);
-
-#endif
-
//@{
/**
* Set, Push, Pop policy values for CMake.
@@ -474,6 +461,36 @@ public:
* Get the source group
*/
cmSourceGroup* GetSourceGroup(const std::vector<std::string>& name) const;
+
+ /**
+ * Add a root source group for consideration when adding a new source.
+ */
+ void AddSourceGroup(const std::string& name, const char* regex = nullptr);
+
+ /**
+ * Add a source group for consideration when adding a new source.
+ * name is tokenized.
+ */
+ void AddSourceGroup(const std::vector<std::string>& name,
+ const char* regex = nullptr);
+
+ /**
+ * Get and existing or create a new source group.
+ */
+ cmSourceGroup* GetOrCreateSourceGroup(
+ const std::vector<std::string>& folders);
+
+ /**
+ * Get and existing or create a new source group.
+ * The name will be tokenized.
+ */
+ cmSourceGroup* GetOrCreateSourceGroup(const std::string& name);
+
+ /**
+ * find what source group this source is in
+ */
+ cmSourceGroup* FindSourceGroup(const char* source,
+ std::vector<cmSourceGroup>& groups) const;
#endif
/**
@@ -521,7 +538,7 @@ public:
const char* ExpandVariablesInString(std::string& source) const;
const char* ExpandVariablesInString(std::string& source, bool escapeQuotes,
bool noEscapes, bool atOnly = false,
- const char* filename = CM_NULLPTR,
+ const char* filename = nullptr,
long line = -1, bool removeEmpty = false,
bool replaceAt = false) const;
@@ -550,14 +567,6 @@ public:
bool atOnly, bool escapeQuotes,
cmNewLineStyle = cmNewLineStyle());
-#if defined(CMAKE_BUILD_WITH_CMAKE)
- /**
- * find what source group this source is in
- */
- cmSourceGroup* FindSourceGroup(const char* source,
- std::vector<cmSourceGroup>& groups) const;
-#endif
-
/**
* Print a command's invocation
*/
@@ -594,11 +603,11 @@ public:
*/
bool ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
std::vector<std::string>& outArgs,
- const char* filename = CM_NULLPTR) const;
+ const char* filename = nullptr) const;
bool ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
std::vector<cmExpandedCommandArgument>& outArgs,
- const char* filename = CM_NULLPTR) const;
+ const char* filename = nullptr) const;
/**
* Get the instance
@@ -614,7 +623,6 @@ public:
{
return this->SourceFiles;
}
- std::vector<cmSourceFile*>& GetSourceFiles() { return this->SourceFiles; }
/**
* Is there a source file that has the provided source file as an output?
@@ -736,9 +744,6 @@ public:
cmStringRange GetCompileDefinitionsEntries() const;
cmBacktraceRange GetCompileDefinitionsBacktraces() const;
- void AddQtUiFileWithOptions(cmSourceFile* sf);
- std::vector<cmSourceFile*> GetQtUiFilesWithOptions() const;
-
std::set<std::string> const& GetSystemIncludeDirectories() const
{
return this->SystemIncludeDirectories;
@@ -747,7 +752,7 @@ public:
bool PolicyOptionalWarningEnabled(std::string const& var);
bool AddRequiredTargetFeature(cmTarget* target, const std::string& feature,
- std::string* error = CM_NULLPTR) const;
+ std::string* error = nullptr) const;
bool CompileFeatureKnown(cmTarget const* target, const std::string& feature,
std::string& lang, std::string* error) const;
@@ -776,10 +781,11 @@ public:
void EnforceDirectoryLevelRules() const;
- void AddEvaluationFile(const std::string& inputFile,
- CM_AUTO_PTR<cmCompiledGeneratorExpression> outputName,
- CM_AUTO_PTR<cmCompiledGeneratorExpression> condition,
- bool inputIsContent);
+ void AddEvaluationFile(
+ const std::string& inputFile,
+ std::unique_ptr<cmCompiledGeneratorExpression> outputName,
+ std::unique_ptr<cmCompiledGeneratorExpression> condition,
+ bool inputIsContent);
std::vector<cmGeneratorExpressionEvaluationFile*> GetEvaluationFiles() const;
std::vector<cmExportBuildFileGenerator*> GetExportBuildFileGenerators()
@@ -871,7 +877,7 @@ private:
friend class cmParseFileScope;
std::vector<cmTarget*> ImportedTargetsOwned;
- typedef CM_UNORDERED_MAP<std::string, cmTarget*> TargetMap;
+ typedef std::unordered_map<std::string, cmTarget*> TargetMap;
TargetMap ImportedTargets;
// Internal policy stack management.
@@ -909,7 +915,7 @@ private:
cmSourceFile* LinearGetSourceFileWithOutput(const std::string& cname) const;
// A map for fast output to input look up.
- typedef CM_UNORDERED_MAP<std::string, cmSourceFile*> OutputToSourceMap;
+ typedef std::unordered_map<std::string, cmSourceFile*> OutputToSourceMap;
OutputToSourceMap OutputToSource;
void UpdateOutputToSourceMap(std::vector<std::string> const& outputs,
@@ -917,14 +923,12 @@ private:
void UpdateOutputToSourceMap(std::string const& output,
cmSourceFile* source);
- std::vector<cmSourceFile*> QtUiFilesWithOptions;
-
bool AddRequiredTargetCFeature(cmTarget* target, const std::string& feature,
- std::string* error = CM_NULLPTR) const;
+ std::string* error = nullptr) const;
bool AddRequiredTargetCxxFeature(cmTarget* target,
const std::string& feature,
- std::string* error = CM_NULLPTR) const;
+ std::string* error = nullptr) const;
void CheckNeededCLanguage(const std::string& feature, bool& needC90,
bool& needC99, bool& needC11) const;
diff --git a/Source/cmMakefileExecutableTargetGenerator.cxx b/Source/cmMakefileExecutableTargetGenerator.cxx
index 359b9fdbb..801f72ab6 100644
--- a/Source/cmMakefileExecutableTargetGenerator.cxx
+++ b/Source/cmMakefileExecutableTargetGenerator.cxx
@@ -3,6 +3,7 @@
#include "cmMakefileExecutableTargetGenerator.h"
#include <algorithm>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <string>
#include <vector>
@@ -23,7 +24,6 @@
#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
cmMakefileExecutableTargetGenerator::cmMakefileExecutableTargetGenerator(
@@ -193,7 +193,7 @@ void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule(
// Set path conversion for link script shells.
this->LocalGenerator->SetLinkScriptShell(useLinkScript);
- CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ std::unique_ptr<cmLinkLineComputer> linkLineComputer(
new cmLinkLineDeviceComputer(
this->LocalGenerator,
this->LocalGenerator->GetStateSnapshot().GetDirectory()));
@@ -251,16 +251,15 @@ void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule(
launcher += " ";
}
- CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
this->LocalGenerator->CreateRulePlaceholderExpander());
// Expand placeholders in the commands.
rulePlaceholderExpander->SetTargetImpLib(targetOutputReal);
- for (std::vector<std::string>::iterator i = real_link_commands.begin();
- i != real_link_commands.end(); ++i) {
- *i = launcher + *i;
- rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i,
- vars);
+ for (std::string& real_link_command : real_link_commands) {
+ real_link_command = launcher + real_link_command;
+ rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
+ real_link_command, vars);
}
// Restore path conversion to normal shells.
@@ -284,7 +283,7 @@ void cmMakefileExecutableTargetGenerator::WriteDeviceExecutableRule(
commands1.clear();
// Write the build rule.
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
targetOutputReal, depends, commands,
false);
@@ -449,7 +448,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
linkFlags, this->GeneratorTarget->GetProperty(linkFlagsConfig));
{
- CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ std::unique_ptr<cmLinkLineComputer> linkLineComputer(
this->CreateLinkLineComputer(
this->LocalGenerator,
this->LocalGenerator->GetStateSnapshot().GetDirectory()));
@@ -539,7 +538,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
// Set path conversion for link script shells.
this->LocalGenerator->SetLinkScriptShell(useLinkScript);
- CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ std::unique_ptr<cmLinkLineComputer> linkLineComputer(
this->CreateLinkLineComputer(
this->LocalGenerator,
this->LocalGenerator->GetStateSnapshot().GetDirectory()));
@@ -619,7 +618,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
if (this->GeneratorTarget->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
std::string cmakeCommand = this->LocalGenerator->ConvertToOutputFormat(
cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
- cmakeCommand += " -E __run_iwyu --lwyu=";
+ cmakeCommand += " -E __run_co_compile --lwyu=";
cmakeCommand += targetOutPathReal;
real_link_commands.push_back(cmakeCommand);
}
@@ -633,16 +632,15 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
launcher += " ";
}
- CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
this->LocalGenerator->CreateRulePlaceholderExpander());
// Expand placeholders in the commands.
rulePlaceholderExpander->SetTargetImpLib(targetOutPathImport);
- for (std::vector<std::string>::iterator i = real_link_commands.begin();
- i != real_link_commands.end(); ++i) {
- *i = launcher + *i;
- rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i,
- vars);
+ for (std::string& real_link_command : real_link_commands) {
+ real_link_command = launcher + real_link_command;
+ rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
+ real_link_command, vars);
}
// Restore path conversion to normal shells.
@@ -687,7 +685,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
}
// Write the build rule.
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
targetFullPathReal, depends, commands,
false);
@@ -698,7 +696,7 @@ void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink)
depends.clear();
commands.clear();
depends.push_back(targetFullPathReal);
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
targetFullPath, depends, commands,
false);
}
diff --git a/Source/cmMakefileExecutableTargetGenerator.h b/Source/cmMakefileExecutableTargetGenerator.h
index 01aa6270c..b9bbe8667 100644
--- a/Source/cmMakefileExecutableTargetGenerator.h
+++ b/Source/cmMakefileExecutableTargetGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmMakefileExecutableTargetGenerator_h
#define cmMakefileExecutableTargetGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
@@ -15,11 +15,11 @@ class cmMakefileExecutableTargetGenerator : public cmMakefileTargetGenerator
{
public:
cmMakefileExecutableTargetGenerator(cmGeneratorTarget* target);
- ~cmMakefileExecutableTargetGenerator() CM_OVERRIDE;
+ ~cmMakefileExecutableTargetGenerator() override;
/* the main entry point for this class. Writes the Makefiles associated
with this target */
- void WriteRuleFiles() CM_OVERRIDE;
+ void WriteRuleFiles() override;
protected:
virtual void WriteExecutableRule(bool relink);
diff --git a/Source/cmMakefileLibraryTargetGenerator.cxx b/Source/cmMakefileLibraryTargetGenerator.cxx
index 3d1594bdb..80c62d10f 100644
--- a/Source/cmMakefileLibraryTargetGenerator.cxx
+++ b/Source/cmMakefileLibraryTargetGenerator.cxx
@@ -3,6 +3,7 @@
#include "cmMakefileLibraryTargetGenerator.h"
#include <algorithm>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <vector>
@@ -22,7 +23,6 @@
#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
cmMakefileLibraryTargetGenerator::cmMakefileLibraryTargetGenerator(
@@ -117,7 +117,7 @@ void cmMakefileLibraryTargetGenerator::WriteObjectLibraryRules()
this->AppendObjectDepends(depends);
// Write the rule.
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
this->GeneratorTarget->GetName(),
depends, commands, true);
@@ -199,7 +199,7 @@ void cmMakefileLibraryTargetGenerator::WriteSharedLibraryRules(bool relink)
this->LocalGenerator->AddConfigVariableFlags(
extraFlags, "CMAKE_SHARED_LINKER_FLAGS", this->ConfigName);
- CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ std::unique_ptr<cmLinkLineComputer> linkLineComputer(
this->CreateLinkLineComputer(
this->LocalGenerator,
this->LocalGenerator->GetStateSnapshot().GetDirectory()));
@@ -248,7 +248,7 @@ void cmMakefileLibraryTargetGenerator::WriteModuleLibraryRules(bool relink)
this->LocalGenerator->AddConfigVariableFlags(
extraFlags, "CMAKE_MODULE_LINKER_FLAGS", this->ConfigName);
- CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ std::unique_ptr<cmLinkLineComputer> linkLineComputer(
this->CreateLinkLineComputer(
this->LocalGenerator,
this->LocalGenerator->GetStateSnapshot().GetDirectory()));
@@ -348,7 +348,7 @@ void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules(
std::string linkLibs;
if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
- CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ std::unique_ptr<cmLinkLineComputer> linkLineComputer(
new cmLinkLineDeviceComputer(
this->LocalGenerator,
this->LocalGenerator->GetStateSnapshot().GetDirectory()));
@@ -410,7 +410,7 @@ void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules(
launcher += " ";
}
- CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
this->LocalGenerator->CreateRulePlaceholderExpander());
// Construct the main link rule and expand placeholders.
@@ -419,11 +419,10 @@ void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules(
cmSystemTools::ExpandListArgument(linkRule, real_link_commands);
// Expand placeholders.
- for (std::vector<std::string>::iterator i = real_link_commands.begin();
- i != real_link_commands.end(); ++i) {
- *i = launcher + *i;
- rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i,
- vars);
+ for (std::string& real_link_command : real_link_commands) {
+ real_link_command = launcher + real_link_command;
+ rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
+ real_link_command, vars);
}
// Restore path conversion to normal shells.
this->LocalGenerator->SetLinkScriptShell(false);
@@ -454,7 +453,7 @@ void cmMakefileLibraryTargetGenerator::WriteDeviceLibraryRules(
std::vector<std::string> outputs(1, targetOutputReal);
// Write the build rule.
- this->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR, outputs, depends,
+ this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
commands, false);
// Write the main driver rule to build everything in this target.
@@ -755,7 +754,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
std::string linkLibs;
if (this->GeneratorTarget->GetType() != cmStateEnums::STATIC_LIBRARY) {
- CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ std::unique_ptr<cmLinkLineComputer> linkLineComputer(
this->CreateLinkLineComputer(
this->LocalGenerator,
this->LocalGenerator->GetStateSnapshot().GetDirectory()));
@@ -874,7 +873,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
launcher += " ";
}
- CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
this->LocalGenerator->CreateRulePlaceholderExpander());
// Construct the main link rule and expand placeholders.
rulePlaceholderExpander->SetTargetImpLib(targetOutPathImport);
@@ -897,10 +896,8 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
std::vector<std::string>::iterator osi = object_strings.begin();
{
vars.Objects = osi->c_str();
- for (std::vector<std::string>::const_iterator i =
- archiveCreateCommands.begin();
- i != archiveCreateCommands.end(); ++i) {
- std::string cmd = launcher + *i;
+ for (std::string const& acc : archiveCreateCommands) {
+ std::string cmd = launcher + acc;
rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
cmd, vars);
real_link_commands.push_back(cmd);
@@ -909,10 +906,8 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
// Append to the archive with the other object sets.
for (++osi; osi != object_strings.end(); ++osi) {
vars.Objects = osi->c_str();
- for (std::vector<std::string>::const_iterator i =
- archiveAppendCommands.begin();
- i != archiveAppendCommands.end(); ++i) {
- std::string cmd = launcher + *i;
+ for (std::string const& aac : archiveAppendCommands) {
+ std::string cmd = launcher + aac;
rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
cmd, vars);
real_link_commands.push_back(cmd);
@@ -920,10 +915,8 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
}
// Finish the archive.
vars.Objects = "";
- for (std::vector<std::string>::const_iterator i =
- archiveFinishCommands.begin();
- i != archiveFinishCommands.end(); ++i) {
- std::string cmd = launcher + *i;
+ for (std::string const& afc : archiveFinishCommands) {
+ std::string cmd = launcher + afc;
rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, cmd,
vars);
// If there is no ranlib the command will be ":". Skip it.
@@ -939,17 +932,16 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
(this->GeneratorTarget->GetType() == cmStateEnums::SHARED_LIBRARY)) {
std::string cmakeCommand = this->LocalGenerator->ConvertToOutputFormat(
cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
- cmakeCommand += " -E __run_iwyu --lwyu=";
+ cmakeCommand += " -E __run_co_compile --lwyu=";
cmakeCommand += targetOutPathReal;
real_link_commands.push_back(cmakeCommand);
}
// Expand placeholders.
- for (std::vector<std::string>::iterator i = real_link_commands.begin();
- i != real_link_commands.end(); ++i) {
- *i = launcher + *i;
- rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i,
- vars);
+ for (std::string& real_link_command : real_link_commands) {
+ real_link_command = launcher + real_link_command;
+ rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
+ real_link_command, vars);
}
}
@@ -1008,7 +1000,7 @@ void cmMakefileLibraryTargetGenerator::WriteLibraryRules(
}
// Write the build rule.
- this->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR, outputs, depends,
+ this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
commands, false);
// Write the main driver rule to build everything in this target.
diff --git a/Source/cmMakefileLibraryTargetGenerator.h b/Source/cmMakefileLibraryTargetGenerator.h
index da1d8b65c..02fa029cd 100644
--- a/Source/cmMakefileLibraryTargetGenerator.h
+++ b/Source/cmMakefileLibraryTargetGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmMakefileLibraryTargetGenerator_h
#define cmMakefileLibraryTargetGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmMakefileTargetGenerator.h"
@@ -15,11 +15,11 @@ class cmMakefileLibraryTargetGenerator : public cmMakefileTargetGenerator
{
public:
cmMakefileLibraryTargetGenerator(cmGeneratorTarget* target);
- ~cmMakefileLibraryTargetGenerator() CM_OVERRIDE;
+ ~cmMakefileLibraryTargetGenerator() override;
/* the main entry point for this class. Writes the Makefiles associated
with this target */
- void WriteRuleFiles() CM_OVERRIDE;
+ void WriteRuleFiles() override;
protected:
void WriteObjectLibraryRules();
diff --git a/Source/cmMakefileTargetGenerator.cxx b/Source/cmMakefileTargetGenerator.cxx
index a4511b63b..7db010c24 100644
--- a/Source/cmMakefileTargetGenerator.cxx
+++ b/Source/cmMakefileTargetGenerator.cxx
@@ -2,6 +2,7 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmMakefileTargetGenerator.h"
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
#include <utility>
@@ -27,17 +28,16 @@
#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
cmMakefileTargetGenerator::cmMakefileTargetGenerator(cmGeneratorTarget* target)
: cmCommonTargetGenerator(target)
- , OSXBundleGenerator(CM_NULLPTR)
- , MacOSXContentGenerator(CM_NULLPTR)
+ , OSXBundleGenerator(nullptr)
+ , MacOSXContentGenerator(nullptr)
{
- this->BuildFileStream = CM_NULLPTR;
- this->InfoFileStream = CM_NULLPTR;
- this->FlagFileStream = CM_NULLPTR;
+ this->BuildFileStream = nullptr;
+ this->InfoFileStream = nullptr;
+ this->FlagFileStream = nullptr;
this->CustomCommandDriver = OnBuild;
this->LocalGenerator =
static_cast<cmLocalUnixMakefileGenerator3*>(target->GetLocalGenerator());
@@ -60,7 +60,7 @@ cmMakefileTargetGenerator::~cmMakefileTargetGenerator()
cmMakefileTargetGenerator* cmMakefileTargetGenerator::New(
cmGeneratorTarget* tgt)
{
- cmMakefileTargetGenerator* result = CM_NULLPTR;
+ cmMakefileTargetGenerator* result = nullptr;
switch (tgt->GetType()) {
case cmStateEnums::EXECUTABLE:
@@ -134,12 +134,12 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules()
if (const char* additional_clean_files =
this->Makefile->GetProperty("ADDITIONAL_MAKE_CLEAN_FILES")) {
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
+ std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(additional_clean_files);
cmSystemTools::ExpandListArgument(
cge->Evaluate(this->LocalGenerator, config, false, this->GeneratorTarget,
- CM_NULLPTR, CM_NULLPTR),
+ nullptr, nullptr),
this->CleanFiles);
}
@@ -153,18 +153,16 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules()
this->GeneratorTarget->GetCustomCommands(customCommands, config);
std::string currentBinDir =
this->LocalGenerator->GetCurrentBinaryDirectory();
- for (std::vector<cmSourceFile const*>::const_iterator si =
- customCommands.begin();
- si != customCommands.end(); ++si) {
- cmCustomCommandGenerator ccg(*(*si)->GetCustomCommand(), this->ConfigName,
+ for (cmSourceFile const* sf : customCommands) {
+ cmCustomCommandGenerator ccg(*sf->GetCustomCommand(), this->ConfigName,
this->LocalGenerator);
this->GenerateCustomRuleFile(ccg);
if (clean) {
const std::vector<std::string>& outputs = ccg.GetOutputs();
- for (std::vector<std::string>::const_iterator o = outputs.begin();
- o != outputs.end(); ++o) {
+ for (std::string const& output : outputs) {
this->CleanFiles.push_back(
- this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, *o));
+ this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir,
+ output));
}
}
}
@@ -178,18 +176,14 @@ void cmMakefileTargetGenerator::WriteTargetBuildRules()
extraSources, this->MacOSXContentGenerator);
std::vector<cmSourceFile const*> externalObjects;
this->GeneratorTarget->GetExternalObjects(externalObjects, config);
- for (std::vector<cmSourceFile const*>::const_iterator si =
- externalObjects.begin();
- si != externalObjects.end(); ++si) {
- this->ExternalObjects.push_back((*si)->GetFullPath());
+ for (cmSourceFile const* sf : externalObjects) {
+ this->ExternalObjects.push_back(sf->GetFullPath());
}
std::vector<cmSourceFile const*> objectSources;
this->GeneratorTarget->GetObjectSources(objectSources, config);
- for (std::vector<cmSourceFile const*>::const_iterator si =
- objectSources.begin();
- si != objectSources.end(); ++si) {
+ for (cmSourceFile const* sf : objectSources) {
// Generate this object file's rule file.
- this->WriteObjectRuleFiles(**si);
+ this->WriteObjectRuleFiles(*sf);
}
}
@@ -272,28 +266,26 @@ void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
languages, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
// put the compiler in the rules.make file so that if it changes
// things rebuild
- for (std::set<std::string>::const_iterator l = languages.begin();
- l != languages.end(); ++l) {
+ for (std::string const& language : languages) {
std::string compiler = "CMAKE_";
- compiler += *l;
+ compiler += language;
compiler += "_COMPILER";
- *this->FlagFileStream << "# compile " << *l << " with "
+ *this->FlagFileStream << "# compile " << language << " with "
<< this->Makefile->GetSafeDefinition(compiler)
<< "\n";
}
- for (std::set<std::string>::const_iterator l = languages.begin();
- l != languages.end(); ++l) {
- std::string flags = this->GetFlags(*l);
- std::string defines = this->GetDefines(*l);
- std::string includes = this->GetIncludes(*l);
+ for (std::string const& language : languages) {
+ std::string flags = this->GetFlags(language);
+ std::string defines = this->GetDefines(language);
+ std::string includes = this->GetIncludes(language);
// Escape comment characters so they do not terminate assignment.
cmSystemTools::ReplaceString(flags, "#", "\\#");
cmSystemTools::ReplaceString(defines, "#", "\\#");
cmSystemTools::ReplaceString(includes, "#", "\\#");
- *this->FlagFileStream << *l << "_FLAGS = " << flags << "\n\n";
- *this->FlagFileStream << *l << "_DEFINES = " << defines << "\n\n";
- *this->FlagFileStream << *l << "_INCLUDES = " << includes << "\n\n";
+ *this->FlagFileStream << language << "_FLAGS = " << flags << "\n\n";
+ *this->FlagFileStream << language << "_DEFINES = " << defines << "\n\n";
+ *this->FlagFileStream << language << "_INCLUDES = " << includes << "\n\n";
}
}
@@ -337,7 +329,7 @@ void cmMakefileTargetGenerator::MacOSXContentGeneratorType::operator()(
output, cmOutputConverter::SHELL);
commands.push_back(copyCommand);
this->Generator->LocalGenerator->WriteMakeRule(
- *this->Generator->BuildFileStream, CM_NULLPTR, output, depends, commands,
+ *this->Generator->BuildFileStream, nullptr, output, depends, commands,
false);
this->Generator->ExtraFiles.insert(output);
}
@@ -442,7 +434,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
// Add flags from source file properties.
if (const char* cflags = source.GetProperty("COMPILE_FLAGS")) {
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(cflags);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(cflags);
const char* evaluatedFlags = cge->Evaluate(this->LocalGenerator, config,
false, this->GeneratorTarget);
this->LocalGenerator->AppendFlags(flags, evaluatedFlags);
@@ -578,7 +570,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
bool const lang_has_assembly = lang_has_preprocessor;
bool const lang_can_export_cmds = lang_has_preprocessor;
- CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
this->LocalGenerator->CreateRulePlaceholderExpander());
// Construct the compile rules.
@@ -633,8 +625,11 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
const char* tidy = this->GeneratorTarget->GetProperty(tidy_prop);
std::string const cpplint_prop = lang + "_CPPLINT";
const char* cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
- if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint)) {
- std::string run_iwyu = "$(CMAKE_COMMAND) -E __run_iwyu";
+ std::string const cppcheck_prop = lang + "_CPPCHECK";
+ const char* cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
+ if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint) ||
+ (cppcheck && *cppcheck)) {
+ std::string run_iwyu = "$(CMAKE_COMMAND) -E __run_co_compile";
if (iwyu && *iwyu) {
run_iwyu += " --iwyu=";
run_iwyu += this->LocalGenerator->EscapeForShell(iwyu);
@@ -647,7 +642,12 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
run_iwyu += " --cpplint=";
run_iwyu += this->LocalGenerator->EscapeForShell(cpplint);
}
- if ((tidy && *tidy) || (cpplint && *cpplint)) {
+ if (cppcheck && *cppcheck) {
+ run_iwyu += " --cppcheck=";
+ run_iwyu += this->LocalGenerator->EscapeForShell(cppcheck);
+ }
+ if ((tidy && *tidy) || (cpplint && *cpplint) ||
+ (cppcheck && *cppcheck)) {
run_iwyu += " --source=";
run_iwyu += sourceFile;
}
@@ -657,17 +657,16 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
}
// Maybe insert a compiler launcher like ccache or distcc
- if (!compileCommands.empty() && (lang == "C" || lang == "CXX")) {
+ if (!compileCommands.empty() &&
+ (lang == "C" || lang == "CXX" || lang == "CUDA")) {
std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER";
const char* clauncher =
this->GeneratorTarget->GetProperty(clauncher_prop);
if (clauncher && *clauncher) {
std::vector<std::string> launcher_cmd;
cmSystemTools::ExpandListArgument(clauncher, launcher_cmd, true);
- for (std::vector<std::string>::iterator i = launcher_cmd.begin(),
- e = launcher_cmd.end();
- i != e; ++i) {
- *i = this->LocalGenerator->EscapeForShell(*i);
+ for (std::string& i : launcher_cmd) {
+ i = this->LocalGenerator->EscapeForShell(i);
}
std::string const& run_launcher = cmJoin(launcher_cmd, " ") + " ";
compileCommands.front().insert(0, run_launcher);
@@ -685,11 +684,10 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
}
// Expand placeholders in the commands.
- for (std::vector<std::string>::iterator i = compileCommands.begin();
- i != compileCommands.end(); ++i) {
- *i = launcher + *i;
- rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator, *i,
- vars);
+ for (std::string& compileCommand : compileCommands) {
+ compileCommand = launcher + compileCommand;
+ rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
+ compileCommand, vars);
}
// Change the command working directory to the local build tree.
@@ -710,7 +708,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
}
// Write the rule.
- this->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR, outputs, depends,
+ this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs, depends,
commands);
bool do_preprocess_rules = lang_has_preprocessor &&
@@ -750,11 +748,10 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
vars.PreprocessedSource = shellObjI.c_str();
// Expand placeholders in the commands.
- for (std::vector<std::string>::iterator i = preprocessCommands.begin();
- i != preprocessCommands.end(); ++i) {
+ for (std::string& preprocessCommand : preprocessCommands) {
// no launcher for preprocessor commands
- rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
- *i, vars);
+ rulePlaceholderExpander->ExpandRuleVariables(
+ this->LocalGenerator, preprocessCommand, vars);
}
this->LocalGenerator->CreateCDCommand(
@@ -769,7 +766,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
commands.push_back(cmd);
}
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
relativeObjI, force_depends,
commands, false);
}
@@ -799,11 +796,10 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
vars.AssemblySource = shellObjS.c_str();
// Expand placeholders in the commands.
- for (std::vector<std::string>::iterator i = assemblyCommands.begin();
- i != assemblyCommands.end(); ++i) {
+ for (std::string& assemblyCommand : assemblyCommands) {
// no launcher for assembly commands
rulePlaceholderExpander->ExpandRuleVariables(this->LocalGenerator,
- *i, vars);
+ assemblyCommand, vars);
}
this->LocalGenerator->CreateCDCommand(
@@ -817,7 +813,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
commands.push_back(cmd);
}
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
relativeObjS, force_depends,
commands, false);
}
@@ -829,7 +825,7 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
objectRequires += ".requires";
std::vector<std::string> p_depends;
// always provide an empty requires target
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
objectRequires, p_depends, no_commands,
true);
@@ -847,14 +843,14 @@ void cmMakefileTargetGenerator::WriteObjectBuildFile(
p_depends.clear();
p_depends.push_back(objectRequires);
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
objectProvides, p_depends, r_commands,
true);
// write the provides.build rule dependency on the obj file
p_depends.clear();
p_depends.push_back(relativeObj);
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR, temp,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr, temp,
p_depends, no_commands, false);
}
@@ -871,16 +867,15 @@ void cmMakefileTargetGenerator::WriteTargetRequiresRules()
// This target drives dependency generation for all object files.
std::string relPath = this->LocalGenerator->GetHomeRelativeOutputPath();
std::string objTarget;
- for (std::vector<std::string>::const_iterator obj = this->Objects.begin();
- obj != this->Objects.end(); ++obj) {
+ for (std::string const& obj : this->Objects) {
objTarget = relPath;
- objTarget += *obj;
+ objTarget += obj;
objTarget += ".requires";
depends.push_back(objTarget);
}
// Write the rule.
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
depTarget, depends, no_commands, true);
}
@@ -902,7 +897,7 @@ void cmMakefileTargetGenerator::WriteTargetCleanRules()
this->LocalGenerator->GetBinaryDirectory());
// Write the rule.
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
cleanTarget, depends, commands, true);
}
@@ -959,7 +954,7 @@ bool cmMakefileTargetGenerator::WriteMakeRule(
if (!o_symbolic) {
output_commands.push_back("@$(CMAKE_COMMAND) -E touch_nocreate " + out);
}
- this->LocalGenerator->WriteMakeRule(os, CM_NULLPTR, *o, output_depends,
+ this->LocalGenerator->WriteMakeRule(os, nullptr, *o, output_depends,
output_commands, o_symbolic, in_help);
if (!o_symbolic) {
@@ -998,12 +993,10 @@ void cmMakefileTargetGenerator::WriteTargetDependRules()
<< "# Pairs of files generated by the same build rule.\n"
<< "set(CMAKE_MULTIPLE_OUTPUT_PAIRS\n";
/* clang-format on */
- for (MultipleOutputPairsType::const_iterator pi =
- this->MultipleOutputPairs.begin();
- pi != this->MultipleOutputPairs.end(); ++pi) {
+ for (auto const& pi : this->MultipleOutputPairs) {
*this->InfoFileStream
- << " " << cmOutputConverter::EscapeForCMake(pi->first) << " "
- << cmOutputConverter::EscapeForCMake(pi->second) << "\n";
+ << " " << cmOutputConverter::EscapeForCMake(pi.first) << " "
+ << cmOutputConverter::EscapeForCMake(pi.second) << "\n";
}
*this->InfoFileStream << " )\n\n";
}
@@ -1017,9 +1010,8 @@ void cmMakefileTargetGenerator::WriteTargetDependRules()
<< "set(CMAKE_TARGET_LINKED_INFO_FILES\n";
/* clang-format on */
std::vector<std::string> dirs = this->GetLinkedTargetDirectories();
- for (std::vector<std::string>::iterator i = dirs.begin(); i != dirs.end();
- ++i) {
- *this->InfoFileStream << " \"" << *i << "/DependInfo.cmake\"\n";
+ for (std::string const& d : dirs) {
+ *this->InfoFileStream << " \"" << d << "/DependInfo.cmake\"\n";
}
*this->InfoFileStream << " )\n";
}
@@ -1106,7 +1098,7 @@ void cmMakefileTargetGenerator::WriteTargetDependRules()
}
// Write the rule.
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
depTarget, depends, commands, true);
}
@@ -1117,9 +1109,8 @@ void cmMakefileTargetGenerator::DriveCustomCommands(
std::vector<cmSourceFile*> sources;
this->GeneratorTarget->GetSourceFiles(
sources, this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
- for (std::vector<cmSourceFile*>::const_iterator source = sources.begin();
- source != sources.end(); ++source) {
- if (cmCustomCommand* cc = (*source)->GetCustomCommand()) {
+ for (cmSourceFile* source : sources) {
+ if (cmCustomCommand* cc = source->GetCustomCommand()) {
cmCustomCommandGenerator ccg(*cc, this->ConfigName,
this->LocalGenerator);
const std::vector<std::string>& outputs = ccg.GetOutputs();
@@ -1169,8 +1160,8 @@ void cmMakefileTargetGenerator::GenerateCustomRuleFile(
// Write the rule.
const std::vector<std::string>& outputs = ccg.GetOutputs();
- bool symbolic = this->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
- outputs, depends, commands);
+ bool symbolic = this->WriteMakeRule(*this->BuildFileStream, nullptr, outputs,
+ depends, commands);
// If the rule has changed make sure the output is rebuilt.
if (!symbolic) {
@@ -1178,12 +1169,10 @@ void cmMakefileTargetGenerator::GenerateCustomRuleFile(
}
// Setup implicit dependency scanning.
- for (cmCustomCommand::ImplicitDependsList::const_iterator idi =
- ccg.GetCC().GetImplicitDepends().begin();
- idi != ccg.GetCC().GetImplicitDepends().end(); ++idi) {
+ for (auto const& idi : ccg.GetCC().GetImplicitDepends()) {
std::string objFullPath = cmSystemTools::CollapseFullPath(outputs[0]);
- std::string srcFullPath = cmSystemTools::CollapseFullPath(idi->second);
- this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, idi->first,
+ std::string srcFullPath = cmSystemTools::CollapseFullPath(idi.second);
+ this->LocalGenerator->AddImplicitDepends(this->GeneratorTarget, idi.first,
objFullPath.c_str(),
srcFullPath.c_str());
}
@@ -1216,11 +1205,10 @@ void cmMakefileTargetGenerator::WriteObjectsVariable(
if (!lineContinue) {
lineContinue = "\\";
}
- for (std::vector<std::string>::const_iterator i = this->Objects.begin();
- i != this->Objects.end(); ++i) {
+ for (std::string const& obj : this->Objects) {
*this->BuildFileStream << " " << lineContinue << "\n";
*this->BuildFileStream << this->LocalGenerator->ConvertToQuotedOutputPath(
- i->c_str(), useWatcomQuote);
+ obj.c_str(), useWatcomQuote);
}
*this->BuildFileStream << "\n";
@@ -1237,14 +1225,12 @@ void cmMakefileTargetGenerator::WriteObjectsVariable(
/* clang-format on */
std::string currentBinDir =
this->LocalGenerator->GetCurrentBinaryDirectory();
- for (std::vector<std::string>::const_iterator i =
- this->ExternalObjects.begin();
- i != this->ExternalObjects.end(); ++i) {
+ for (std::string const& obj : this->ExternalObjects) {
object =
- this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, *i);
+ this->LocalGenerator->MaybeConvertToRelativePath(currentBinDir, obj);
*this->BuildFileStream << " " << lineContinue << "\n";
*this->BuildFileStream << this->LocalGenerator->ConvertToQuotedOutputPath(
- i->c_str(), useWatcomQuote);
+ obj.c_str(), useWatcomQuote);
}
*this->BuildFileStream << "\n"
<< "\n";
@@ -1275,7 +1261,7 @@ public:
(this->CurrentString.length() + 1 + this->NextObject.length() >
this->LengthLimit)) {
this->Strings.push_back(this->CurrentString);
- this->CurrentString = "";
+ this->CurrentString.clear();
this->Space = "";
}
@@ -1314,14 +1300,11 @@ void cmMakefileTargetGenerator::WriteObjectsStrings(
cmMakefileTargetGeneratorObjectStrings helper(
objStrings, this->LocalGenerator,
this->LocalGenerator->GetStateSnapshot().GetDirectory(), limit);
- for (std::vector<std::string>::const_iterator i = this->Objects.begin();
- i != this->Objects.end(); ++i) {
- helper.Feed(*i);
+ for (std::string const& obj : this->Objects) {
+ helper.Feed(obj);
}
- for (std::vector<std::string>::const_iterator i =
- this->ExternalObjects.begin();
- i != this->ExternalObjects.end(); ++i) {
- helper.Feed(*i);
+ for (std::string const& obj : this->ExternalObjects) {
+ helper.Feed(obj);
}
helper.Done();
}
@@ -1341,7 +1324,7 @@ void cmMakefileTargetGenerator::WriteTargetDriverRule(
std::vector<std::string> depends;
depends.push_back(main_output);
- const char* comment = CM_NULLPTR;
+ const char* comment = nullptr;
if (relink) {
// Setup the comment for the preinstall driver.
comment = "Rule to relink during preinstall.";
@@ -1389,10 +1372,9 @@ void cmMakefileTargetGenerator::AppendObjectDepends(
// Add dependencies on the compiled object files.
std::string relPath = this->LocalGenerator->GetHomeRelativeOutputPath();
std::string objTarget;
- for (std::vector<std::string>::const_iterator obj = this->Objects.begin();
- obj != this->Objects.end(); ++obj) {
+ for (std::string const& obj : this->Objects) {
objTarget = relPath;
- objTarget += *obj;
+ objTarget += obj;
depends.push_back(objTarget);
}
@@ -1417,19 +1399,16 @@ void cmMakefileTargetGenerator::AppendLinkDepends(
if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
this->GeneratorTarget->GetModuleDefinitionInfo(
this->GetConfigName())) {
- for (std::vector<cmSourceFile const*>::const_iterator i =
- mdi->Sources.begin();
- i != mdi->Sources.end(); ++i) {
- depends.push_back((*i)->GetFullPath());
+ for (cmSourceFile const* src : mdi->Sources) {
+ depends.push_back(src->GetFullPath());
}
}
// Add a dependency on user-specified manifest files, if any.
std::vector<cmSourceFile const*> manifest_srcs;
this->GeneratorTarget->GetManifests(manifest_srcs, this->ConfigName);
- for (std::vector<cmSourceFile const*>::iterator mi = manifest_srcs.begin();
- mi != manifest_srcs.end(); ++mi) {
- depends.push_back((*mi)->GetFullPath());
+ for (cmSourceFile const* manifest_src : manifest_srcs) {
+ depends.push_back(manifest_src->GetFullPath());
}
// Add user-specified dependencies.
@@ -1472,12 +1451,11 @@ void cmMakefileTargetGenerator::CreateLinkScript(
linkScriptName += name;
cmGeneratedFileStream linkScriptStream(linkScriptName.c_str());
linkScriptStream.SetCopyIfDifferent(true);
- for (std::vector<std::string>::const_iterator cmd = link_commands.begin();
- cmd != link_commands.end(); ++cmd) {
+ for (std::string const& link_command : link_commands) {
// Do not write out empty commands or commands beginning in the
// shell no-op ":".
- if (!cmd->empty() && (*cmd)[0] != ':') {
- linkScriptStream << *cmd << "\n";
+ if (!link_command.empty() && link_command[0] != ':') {
+ linkScriptStream << link_command << "\n";
}
}
@@ -1512,14 +1490,11 @@ bool cmMakefileTargetGenerator::CheckUseResponseFileForObjects(
// actual list will likely be much shorter than this. However, in the
// worst case all objects will remain as absolute paths.
size_t length = 0;
- for (std::vector<std::string>::const_iterator i = this->Objects.begin();
- i != this->Objects.end(); ++i) {
- length += i->size() + 3;
+ for (std::string const& obj : this->Objects) {
+ length += obj.size() + 3;
}
- for (std::vector<std::string>::const_iterator i =
- this->ExternalObjects.begin();
- i != this->ExternalObjects.end(); ++i) {
- length += i->size() + 3;
+ for (std::string const& ext_obj : this->ExternalObjects) {
+ length += ext_obj.size() + 3;
}
// We need to guarantee room for both objects and libraries, so
@@ -1742,22 +1717,17 @@ void cmMakefileTargetGenerator::GenDefFile(
cmGeneratedFileStream fout(objlist_file.c_str());
if (mdi->WindowsExportAllSymbols) {
- for (std::vector<std::string>::const_iterator i = this->Objects.begin();
- i != this->Objects.end(); ++i) {
- if (cmHasLiteralSuffix(*i, ".obj")) {
- fout << *i << "\n";
+ for (std::string const& obj : this->Objects) {
+ if (cmHasLiteralSuffix(obj, ".obj")) {
+ fout << obj << "\n";
}
}
- for (std::vector<std::string>::const_iterator i =
- this->ExternalObjects.begin();
- i != this->ExternalObjects.end(); ++i) {
- fout << *i << "\n";
+ for (std::string const& obj : this->ExternalObjects) {
+ fout << obj << "\n";
}
}
- for (std::vector<cmSourceFile const*>::const_iterator i =
- mdi->Sources.begin();
- i != mdi->Sources.end(); ++i) {
- fout << (*i)->GetFullPath() << "\n";
+ for (cmSourceFile const* src : mdi->Sources) {
+ fout << src->GetFullPath() << "\n";
}
}
diff --git a/Source/cmMakefileTargetGenerator.h b/Source/cmMakefileTargetGenerator.h
index 92c9f60b0..5ab7e36b0 100644
--- a/Source/cmMakefileTargetGenerator.h
+++ b/Source/cmMakefileTargetGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmMakefileTargetGenerator_h
#define cmMakefileTargetGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <map>
@@ -33,7 +33,7 @@ class cmMakefileTargetGenerator : public cmCommonTargetGenerator
public:
// constructor to set the ivars
cmMakefileTargetGenerator(cmGeneratorTarget* target);
- ~cmMakefileTargetGenerator() CM_OVERRIDE;
+ ~cmMakefileTargetGenerator() override;
// construct using this factory call
static cmMakefileTargetGenerator* New(cmGeneratorTarget* tgt);
@@ -81,8 +81,7 @@ protected:
{
}
- void operator()(cmSourceFile const& source,
- const char* pkgloc) CM_OVERRIDE;
+ void operator()(cmSourceFile const& source, const char* pkgloc) override;
private:
cmMakefileTargetGenerator* Generator;
@@ -168,8 +167,7 @@ protected:
/** Add commands for generate def files */
void GenDefFile(std::vector<std::string>& real_link_commands);
- void AddIncludeFlags(std::string& flags,
- const std::string& lang) CM_OVERRIDE;
+ void AddIncludeFlags(std::string& flags, const std::string& lang) override;
virtual void CloseFileStreams();
cmLocalUnixMakefileGenerator3* LocalGenerator;
diff --git a/Source/cmMakefileUtilityTargetGenerator.cxx b/Source/cmMakefileUtilityTargetGenerator.cxx
index a7c5d27f2..46df0d89c 100644
--- a/Source/cmMakefileUtilityTargetGenerator.cxx
+++ b/Source/cmMakefileUtilityTargetGenerator.cxx
@@ -95,7 +95,7 @@ void cmMakefileUtilityTargetGenerator::WriteRuleFiles()
}
// Write the rule.
- this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, CM_NULLPTR,
+ this->LocalGenerator->WriteMakeRule(*this->BuildFileStream, nullptr,
this->GeneratorTarget->GetName(),
depends, commands, true);
diff --git a/Source/cmMakefileUtilityTargetGenerator.h b/Source/cmMakefileUtilityTargetGenerator.h
index 8df5dd46f..be243a7f5 100644
--- a/Source/cmMakefileUtilityTargetGenerator.h
+++ b/Source/cmMakefileUtilityTargetGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmMakefileUtilityTargetGenerator_h
#define cmMakefileUtilityTargetGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmMakefileTargetGenerator.h"
@@ -13,11 +13,11 @@ class cmMakefileUtilityTargetGenerator : public cmMakefileTargetGenerator
{
public:
cmMakefileUtilityTargetGenerator(cmGeneratorTarget* target);
- ~cmMakefileUtilityTargetGenerator() CM_OVERRIDE;
+ ~cmMakefileUtilityTargetGenerator() override;
/* the main entry point for this class. Writes the Makefiles associated
with this target */
- void WriteRuleFiles() CM_OVERRIDE;
+ void WriteRuleFiles() override;
protected:
};
diff --git a/Source/cmMarkAsAdvancedCommand.cxx b/Source/cmMarkAsAdvancedCommand.cxx
index 14fd96f08..45c59b999 100644
--- a/Source/cmMarkAsAdvancedCommand.cxx
+++ b/Source/cmMarkAsAdvancedCommand.cxx
@@ -34,7 +34,7 @@ bool cmMarkAsAdvancedCommand::InitialPass(std::vector<std::string> const& args,
cmState* state = this->Makefile->GetState();
if (!state->GetCacheEntryValue(variable)) {
this->Makefile->GetCMakeInstance()->AddCacheEntry(
- variable, CM_NULLPTR, CM_NULLPTR, cmStateEnums::UNINITIALIZED);
+ variable, nullptr, nullptr, cmStateEnums::UNINITIALIZED);
overwrite = true;
}
if (!state->GetCacheEntryValue(variable)) {
diff --git a/Source/cmMarkAsAdvancedCommand.h b/Source/cmMarkAsAdvancedCommand.h
index a7791a932..5dd198f62 100644
--- a/Source/cmMarkAsAdvancedCommand.h
+++ b/Source/cmMarkAsAdvancedCommand.h
@@ -3,7 +3,7 @@
#ifndef cmMarkAsAdvancedCommand_h
#define cmMarkAsAdvancedCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmMarkAsAdvancedCommand; }
+ cmCommand* Clone() override { return new cmMarkAsAdvancedCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmMathCommand.h b/Source/cmMathCommand.h
index 67dbdda37..0c6c76bb1 100644
--- a/Source/cmMathCommand.h
+++ b/Source/cmMathCommand.h
@@ -3,7 +3,7 @@
#ifndef cmMathCommand_h
#define cmMathCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -19,14 +19,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmMathCommand; }
+ cmCommand* Clone() override { return new cmMathCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
protected:
bool HandleExprCommand(std::vector<std::string> const& args);
diff --git a/Source/cmMessageCommand.h b/Source/cmMessageCommand.h
index 96939e514..819ebdacf 100644
--- a/Source/cmMessageCommand.h
+++ b/Source/cmMessageCommand.h
@@ -3,7 +3,7 @@
#ifndef cmMessageCommand_h
#define cmMessageCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -22,14 +22,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmMessageCommand; }
+ cmCommand* Clone() override { return new cmMessageCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmNinjaLinkLineComputer.h b/Source/cmNinjaLinkLineComputer.h
index 13f05a838..0ed53f45a 100644
--- a/Source/cmNinjaLinkLineComputer.h
+++ b/Source/cmNinjaLinkLineComputer.h
@@ -4,7 +4,7 @@
#ifndef cmNinjaLinkLineComputer_h
#define cmNinjaLinkLineComputer_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
@@ -23,8 +23,7 @@ public:
cmStateDirectory const& stateDir,
cmGlobalNinjaGenerator const* gg);
- std::string ConvertToLinkReference(std::string const& input) const
- CM_OVERRIDE;
+ std::string ConvertToLinkReference(std::string const& input) const override;
private:
cmGlobalNinjaGenerator const* GG;
diff --git a/Source/cmNinjaNormalTargetGenerator.cxx b/Source/cmNinjaNormalTargetGenerator.cxx
index 14a4ef824..e0cc35a15 100644
--- a/Source/cmNinjaNormalTargetGenerator.cxx
+++ b/Source/cmNinjaNormalTargetGenerator.cxx
@@ -6,11 +6,11 @@
#include <assert.h>
#include <iterator>
#include <map>
+#include <memory> // IWYU pragma: keep
#include <set>
#include <sstream>
#include "cmAlgorithms.h"
-#include "cmCustomCommand.h"
#include "cmCustomCommandGenerator.h"
#include "cmGeneratedFileStream.h"
#include "cmGeneratorTarget.h"
@@ -30,9 +30,10 @@
#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
+class cmCustomCommand;
+
cmNinjaNormalTargetGenerator::cmNinjaNormalTargetGenerator(
cmGeneratorTarget* target)
: cmNinjaTargetGenerator(target)
@@ -112,17 +113,14 @@ void cmNinjaNormalTargetGenerator::WriteLanguagesRules()
std::vector<cmSourceFile const*> sourceFiles;
this->GetGeneratorTarget()->GetObjectSources(
sourceFiles, this->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE"));
- for (std::vector<cmSourceFile const*>::const_iterator i =
- sourceFiles.begin();
- i != sourceFiles.end(); ++i) {
- const std::string& lang = (*i)->GetLanguage();
+ for (cmSourceFile const* sf : sourceFiles) {
+ std::string const lang = sf->GetLanguage();
if (!lang.empty()) {
languages.insert(lang);
}
}
- for (std::set<std::string>::const_iterator l = languages.begin();
- l != languages.end(); ++l) {
- this->WriteLanguageRules(*l);
+ for (std::string const& language : languages) {
+ this->WriteLanguageRules(language);
}
}
@@ -142,7 +140,7 @@ const char* cmNinjaNormalTargetGenerator::GetVisibleTypeName() const
case cmStateEnums::EXECUTABLE:
return "executable";
default:
- return CM_NULLPTR;
+ return nullptr;
}
}
@@ -243,16 +241,15 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkRule(bool useResponseFile)
launcher += " ";
}
- CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
this->GetLocalGenerator()->CreateRulePlaceholderExpander());
// Rule for linking library/executable.
std::vector<std::string> linkCmds = this->ComputeDeviceLinkCmd();
- for (std::vector<std::string>::iterator i = linkCmds.begin();
- i != linkCmds.end(); ++i) {
- *i = launcher + *i;
+ for (std::string& linkCmd : linkCmds) {
+ linkCmd = launcher + linkCmd;
rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
- *i, vars);
+ linkCmd, vars);
}
// If there is no ranlib the command will be ":". Skip it.
@@ -368,16 +365,15 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
launcher += " ";
}
- CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
this->GetLocalGenerator()->CreateRulePlaceholderExpander());
// Rule for linking library/executable.
std::vector<std::string> linkCmds = this->ComputeLinkCmd();
- for (std::vector<std::string>::iterator i = linkCmds.begin();
- i != linkCmds.end(); ++i) {
- *i = launcher + *i;
+ for (std::string& linkCmd : linkCmds) {
+ linkCmd = launcher + linkCmd;
rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
- *i, vars);
+ linkCmd, vars);
}
// If there is no ranlib the command will be ":". Skip it.
@@ -409,10 +405,14 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
this->GetLocalGenerator()->ConvertToOutputFormat(
cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
if (targetType == cmStateEnums::EXECUTABLE) {
+ std::vector<std::string> commandLines;
+ commandLines.push_back(cmakeCommand +
+ " -E cmake_symlink_executable $in $out");
+ commandLines.push_back("$POST_BUILD");
+
this->GetGlobalGenerator()->AddRule(
"CMAKE_SYMLINK_EXECUTABLE",
- cmakeCommand + " -E cmake_symlink_executable"
- " $in $out && $POST_BUILD",
+ this->GetLocalGenerator()->BuildCommandLine(commandLines),
"Creating executable symlink $out", "Rule for creating "
"executable symlink.",
/*depfile*/ "",
@@ -422,10 +422,14 @@ void cmNinjaNormalTargetGenerator::WriteLinkRule(bool useResponseFile)
/*restat*/ "",
/*generator*/ false);
} else {
+ std::vector<std::string> commandLines;
+ commandLines.push_back(cmakeCommand +
+ " -E cmake_symlink_library $in $SONAME $out");
+ commandLines.push_back("$POST_BUILD");
+
this->GetGlobalGenerator()->AddRule(
"CMAKE_SYMLINK_LIBRARY",
- cmakeCommand + " -E cmake_symlink_library"
- " $in $SONAME $out && $POST_BUILD",
+ this->GetLocalGenerator()->BuildCommandLine(commandLines),
"Creating library symlink $out", "Rule for creating "
"library symlink.",
/*depfile*/ "",
@@ -477,12 +481,21 @@ std::vector<std::string> cmNinjaNormalTargetGenerator::ComputeLinkCmd()
this->TargetLinkLanguage, this->GetConfigName());
const char* linkCmd = mf->GetDefinition(linkCmdVar);
if (linkCmd) {
- cmSystemTools::ExpandListArgument(linkCmd, linkCmds);
+ std::string linkCmdStr = linkCmd;
+ if (this->GetGeneratorTarget()->HasImplibGNUtoMS()) {
+ std::string ruleVar = "CMAKE_";
+ ruleVar += this->GeneratorTarget->GetLinkerLanguage(this->ConfigName);
+ ruleVar += "_GNUtoMS_RULE";
+ if (const char* rule = this->Makefile->GetDefinition(ruleVar)) {
+ linkCmdStr += rule;
+ }
+ }
+ cmSystemTools::ExpandListArgument(linkCmdStr, linkCmds);
if (this->GetGeneratorTarget()->GetPropertyAsBool("LINK_WHAT_YOU_USE")) {
std::string cmakeCommand =
this->GetLocalGenerator()->ConvertToOutputFormat(
cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
- cmakeCommand += " -E __run_iwyu --lwyu=";
+ cmakeCommand += " -E __run_co_compile --lwyu=";
cmGeneratorTarget& gt = *this->GetGeneratorTarget();
const std::string cfgName = this->GetConfigName();
std::string targetOutput = ConvertToNinjaPath(gt.GetFullPath(cfgName));
@@ -623,7 +636,7 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement()
vars["TARGET_FILE"] =
localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
- CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ std::unique_ptr<cmLinkLineComputer> linkLineComputer(
new cmNinjaLinkLineDeviceComputer(
this->GetLocalGenerator(),
this->GetLocalGenerator()->GetStateSnapshot().GetDirectory(),
@@ -654,7 +667,7 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement()
std::string t = vars["ARCH_FLAGS"];
localGen.AddArchitectureFlags(t, &genTarget, cudaLinkLanguage, cfgName);
vars["ARCH_FLAGS"] = t;
- t = "";
+ t.clear();
localGen.AddLanguageFlagsForLinking(t, &genTarget, cudaLinkLanguage,
cfgName);
vars["LANGUAGE_COMPILE_FLAGS"] = t;
@@ -714,10 +727,8 @@ void cmNinjaNormalTargetGenerator::WriteDeviceLinkStatement()
&postBuildCmdLines };
for (unsigned i = 0; i != 3; ++i) {
- for (std::vector<cmCustomCommand>::const_iterator ci =
- cmdLists[i]->begin();
- ci != cmdLists[i]->end(); ++ci) {
- cmCustomCommandGenerator ccg(*ci, cfgName, this->GetLocalGenerator());
+ for (cmCustomCommand const& cc : *cmdLists[i]) {
+ cmCustomCommandGenerator ccg(cc, cfgName, this->GetLocalGenerator());
localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
std::transform(ccByproducts.begin(), ccByproducts.end(),
@@ -828,7 +839,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
vars["TARGET_FILE"] =
localGen.ConvertToOutputFormat(targetOutputReal, cmOutputConverter::SHELL);
- CM_AUTO_PTR<cmLinkLineComputer> linkLineComputer(
+ std::unique_ptr<cmLinkLineComputer> linkLineComputer(
this->GetGlobalGenerator()->CreateLinkLineComputer(
this->GetLocalGenerator(),
this->GetLocalGenerator()->GetStateSnapshot().GetDirectory()));
@@ -873,7 +884,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
std::string t = vars["ARCH_FLAGS"];
localGen.AddArchitectureFlags(t, &genTarget, TargetLinkLanguage, cfgName);
vars["ARCH_FLAGS"] = t;
- t = "";
+ t.clear();
t += lwyuFlags;
localGen.AddLanguageFlagsForLinking(t, &genTarget, TargetLinkLanguage,
cfgName);
@@ -943,10 +954,8 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
&postBuildCmdLines };
for (unsigned i = 0; i != 3; ++i) {
- for (std::vector<cmCustomCommand>::const_iterator ci =
- cmdLists[i]->begin();
- ci != cmdLists[i]->end(); ++ci) {
- cmCustomCommandGenerator ccg(*ci, cfgName, this->GetLocalGenerator());
+ for (cmCustomCommand const& cc : *cmdLists[i]) {
+ cmCustomCommandGenerator ccg(cc, cfgName, this->GetLocalGenerator());
localGen.AppendCustomCommandLines(ccg, *cmdLineLists[i]);
std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
std::transform(ccByproducts.begin(), ccByproducts.end(),
@@ -976,17 +985,15 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
if (mdi->WindowsExportAllSymbols) {
cmNinjaDeps objs = this->GetObjects();
- for (cmNinjaDeps::iterator i = objs.begin(); i != objs.end(); ++i) {
- if (cmHasLiteralSuffix(*i, ".obj")) {
- fout << *i << "\n";
+ for (std::string const& obj : objs) {
+ if (cmHasLiteralSuffix(obj, ".obj")) {
+ fout << obj << "\n";
}
}
}
- for (std::vector<cmSourceFile const*>::const_iterator i =
- mdi->Sources.begin();
- i != mdi->Sources.end(); ++i) {
- fout << (*i)->GetFullPath() << "\n";
+ for (cmSourceFile const* src : mdi->Sources) {
+ fout << src->GetFullPath() << "\n";
}
}
// If we have any PRE_LINK commands, we need to go back to CMAKE_BINARY_DIR
@@ -1033,11 +1040,9 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
// Ninja should restat after linking if and only if there are byproducts.
vars["RESTAT"] = byproducts.empty() ? "" : "1";
- for (cmNinjaDeps::const_iterator oi = byproducts.begin(),
- oe = byproducts.end();
- oi != oe; ++oi) {
- this->GetGlobalGenerator()->SeenCustomCommandOutput(*oi);
- outputs.push_back(*oi);
+ for (std::string const& o : byproducts) {
+ this->GetGlobalGenerator()->SeenCustomCommandOutput(o);
+ outputs.push_back(o);
}
// Write the build statement for this target.
@@ -1065,7 +1070,7 @@ void cmNinjaNormalTargetGenerator::WriteLinkStatement()
if (targetOutputReal == soName || targetOutput == soName) {
symlinkVars["SONAME"] = soName;
} else {
- symlinkVars["SONAME"] = "";
+ symlinkVars["SONAME"].clear();
symlinks.push_back(soName);
}
symlinks.push_back(targetOutput);
diff --git a/Source/cmNinjaNormalTargetGenerator.h b/Source/cmNinjaNormalTargetGenerator.h
index 677b1c666..01cc8816e 100644
--- a/Source/cmNinjaNormalTargetGenerator.h
+++ b/Source/cmNinjaNormalTargetGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmNinjaNormalTargetGenerator_h
#define cmNinjaNormalTargetGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmNinjaTargetGenerator.h"
@@ -16,9 +16,9 @@ class cmNinjaNormalTargetGenerator : public cmNinjaTargetGenerator
{
public:
cmNinjaNormalTargetGenerator(cmGeneratorTarget* target);
- ~cmNinjaNormalTargetGenerator() CM_OVERRIDE;
+ ~cmNinjaNormalTargetGenerator() override;
- void Generate() CM_OVERRIDE;
+ void Generate() override;
private:
std::string LanguageLinkerRule() const;
diff --git a/Source/cmNinjaTargetGenerator.cxx b/Source/cmNinjaTargetGenerator.cxx
index d38dbcb09..5805259a5 100644
--- a/Source/cmNinjaTargetGenerator.cxx
+++ b/Source/cmNinjaTargetGenerator.cxx
@@ -8,6 +8,7 @@
#include <assert.h>
#include <iterator>
#include <map>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <string.h>
@@ -29,7 +30,6 @@
#include "cmState.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
cmNinjaTargetGenerator* cmNinjaTargetGenerator::New(cmGeneratorTarget* target)
@@ -47,14 +47,14 @@ cmNinjaTargetGenerator* cmNinjaTargetGenerator::New(cmGeneratorTarget* target)
return new cmNinjaUtilityTargetGenerator(target);
default:
- return CM_NULLPTR;
+ return nullptr;
}
}
cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target)
: cmCommonTargetGenerator(target)
- , MacOSXContentGenerator(CM_NULLPTR)
- , OSXBundleGenerator(CM_NULLPTR)
+ , MacOSXContentGenerator(nullptr)
+ , OSXBundleGenerator(nullptr)
, MacContentFolders()
, LocalGenerator(
static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator()))
@@ -138,7 +138,7 @@ std::string cmNinjaTargetGenerator::ComputeFlagsForObject(
if (const char* cflags = source->GetProperty("COMPILE_FLAGS")) {
std::string config = this->LocalGenerator->GetConfigName();
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(cflags);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(cflags);
const char* evaluatedFlags = cge->Evaluate(this->LocalGenerator, config,
false, this->GeneratorTarget);
this->LocalGenerator->AppendFlags(flags, evaluatedFlags);
@@ -215,19 +215,16 @@ cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps() const
if (cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
this->GeneratorTarget->GetModuleDefinitionInfo(
this->GetConfigName())) {
- for (std::vector<cmSourceFile const*>::const_iterator i =
- mdi->Sources.begin();
- i != mdi->Sources.end(); ++i) {
- result.push_back(this->ConvertToNinjaPath((*i)->GetFullPath()));
+ for (cmSourceFile const* src : mdi->Sources) {
+ result.push_back(this->ConvertToNinjaPath(src->GetFullPath()));
}
}
// Add a dependency on user-specified manifest files, if any.
std::vector<cmSourceFile const*> manifest_srcs;
this->GeneratorTarget->GetManifests(manifest_srcs, this->ConfigName);
- for (std::vector<cmSourceFile const*>::iterator mi = manifest_srcs.begin();
- mi != manifest_srcs.end(); ++mi) {
- result.push_back(this->ConvertToNinjaPath((*mi)->GetFullPath()));
+ for (cmSourceFile const* manifest_src : manifest_srcs) {
+ result.push_back(this->ConvertToNinjaPath(manifest_src->GetFullPath()));
}
// Add user-specified dependencies.
@@ -428,7 +425,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
// The explicit preprocessing step will handle dependency scanning.
} else if (this->NeedDepTypeMSVC(lang)) {
deptype = "msvc";
- depfile = "";
+ depfile.clear();
flags += " /showIncludes";
} else if (mf->IsOn("CMAKE_NINJA_CMCLDEPS_" + lang)) {
// For the MS resource compiler we need cmcldeps, but skip dependencies
@@ -441,7 +438,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
: mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
cldeps = "\"";
cldeps += cmSystemTools::GetCMClDepsCommand();
- cldeps += "\" " + lang + " " + vars.Source + " \"$DEP_FILE\" $out \"";
+ cldeps += "\" " + lang + " " + vars.Source + " $DEP_FILE $out \"";
cldeps += mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
cldeps += "\" \"" + cl + "\" ";
}
@@ -466,7 +463,7 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
vars.Flags = flags.c_str();
vars.DependencyFile = depfile.c_str();
- CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
this->GetLocalGenerator()->CreateRulePlaceholderExpander());
std::string const tdi = this->GetLocalGenerator()->ConvertToOutputFormat(
@@ -519,11 +516,10 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
std::vector<std::string> ppCmds;
cmSystemTools::ExpandListArgument(ppCmd, ppCmds);
- for (std::vector<std::string>::iterator i = ppCmds.begin();
- i != ppCmds.end(); ++i) {
- *i = launcher + *i;
+ for (std::string& i : ppCmds) {
+ i = launcher + i;
rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(),
- *i, ppVars);
+ i, ppVars);
}
// Run CMake dependency scanner on preprocessed output.
@@ -557,17 +553,11 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
// Write the rule for ninja dyndep file generation.
std::vector<std::string> ddCmds;
-#ifdef _WIN32
- // Windows command line length is limited -> use response file for dyndep
- // rules
+ // Command line length is almost always limited -> use response file for
+ // dyndep rules
std::string ddRspFile = "$out.rsp";
std::string ddRspContent = "$in";
std::string ddInput = "@" + ddRspFile;
-#else
- std::string ddRspFile;
- std::string ddRspContent;
- std::string ddInput = "$in";
-#endif
// Run CMake dependency scanner on preprocessed output.
std::string const cmake = this->GetLocalGenerator()->ConvertToOutputFormat(
@@ -623,10 +613,13 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
const char* tidy = this->GeneratorTarget->GetProperty(tidy_prop);
std::string const cpplint_prop = lang + "_CPPLINT";
const char* cpplint = this->GeneratorTarget->GetProperty(cpplint_prop);
- if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint)) {
+ std::string const cppcheck_prop = lang + "_CPPCHECK";
+ const char* cppcheck = this->GeneratorTarget->GetProperty(cppcheck_prop);
+ if ((iwyu && *iwyu) || (tidy && *tidy) || (cpplint && *cpplint) ||
+ (cppcheck && *cppcheck)) {
std::string run_iwyu = this->GetLocalGenerator()->ConvertToOutputFormat(
cmSystemTools::GetCMakeCommand(), cmOutputConverter::SHELL);
- run_iwyu += " -E __run_iwyu";
+ run_iwyu += " -E __run_co_compile";
if (iwyu && *iwyu) {
run_iwyu += " --iwyu=";
run_iwyu += this->GetLocalGenerator()->EscapeForShell(iwyu);
@@ -639,7 +632,12 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
run_iwyu += " --cpplint=";
run_iwyu += this->GetLocalGenerator()->EscapeForShell(cpplint);
}
- if ((tidy && *tidy) || (cpplint && *cpplint)) {
+ if (cppcheck && *cppcheck) {
+ run_iwyu += " --cppcheck=";
+ run_iwyu += this->GetLocalGenerator()->EscapeForShell(cppcheck);
+ }
+ if ((tidy && *tidy) || (cpplint && *cpplint) ||
+ (cppcheck && *cppcheck)) {
run_iwyu += " --source=$in";
}
run_iwyu += " -- ";
@@ -648,16 +646,15 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
}
// Maybe insert a compiler launcher like ccache or distcc
- if (!compileCmds.empty() && (lang == "C" || lang == "CXX")) {
+ if (!compileCmds.empty() &&
+ (lang == "C" || lang == "CXX" || lang == "CUDA")) {
std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER";
const char* clauncher = this->GeneratorTarget->GetProperty(clauncher_prop);
if (clauncher && *clauncher) {
std::vector<std::string> launcher_cmd;
cmSystemTools::ExpandListArgument(clauncher, launcher_cmd, true);
- for (std::vector<std::string>::iterator i = launcher_cmd.begin(),
- e = launcher_cmd.end();
- i != e; ++i) {
- *i = this->LocalGenerator->EscapeForShell(*i);
+ for (std::string& i : launcher_cmd) {
+ i = this->LocalGenerator->EscapeForShell(i);
}
std::string const& run_launcher = cmJoin(launcher_cmd, " ") + " ";
compileCmds.front().insert(0, run_launcher);
@@ -668,10 +665,9 @@ void cmNinjaTargetGenerator::WriteCompileRule(const std::string& lang)
compileCmds.front().insert(0, cldeps);
}
- for (std::vector<std::string>::iterator i = compileCmds.begin();
- i != compileCmds.end(); ++i) {
- *i = launcher + *i;
- rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), *i,
+ for (std::string& i : compileCmds) {
+ i = launcher + i;
+ rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
vars);
}
@@ -702,10 +698,8 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements()
std::string config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
std::vector<cmSourceFile const*> customCommands;
this->GeneratorTarget->GetCustomCommands(customCommands, config);
- for (std::vector<cmSourceFile const*>::const_iterator si =
- customCommands.begin();
- si != customCommands.end(); ++si) {
- cmCustomCommand const* cc = (*si)->GetCustomCommand();
+ for (cmSourceFile const* sf : customCommands) {
+ cmCustomCommand const* cc = sf->GetCustomCommand();
this->GetLocalGenerator()->AddCustomCommandTarget(
cc, this->GetGeneratorTarget());
// Record the custom commands for this target. The container is used
@@ -722,10 +716,8 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements()
extraSources, this->MacOSXContentGenerator);
std::vector<cmSourceFile const*> externalObjects;
this->GeneratorTarget->GetExternalObjects(externalObjects, config);
- for (std::vector<cmSourceFile const*>::const_iterator si =
- externalObjects.begin();
- si != externalObjects.end(); ++si) {
- this->Objects.push_back(this->GetSourceFilePath(*si));
+ for (cmSourceFile const* sf : externalObjects) {
+ this->Objects.push_back(this->GetSourceFilePath(sf));
}
cmNinjaDeps orderOnlyDeps;
@@ -737,10 +729,7 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements()
this->ExtraFiles.end());
// Add order-only dependencies on custom command outputs.
- for (std::vector<cmCustomCommand const*>::const_iterator cci =
- this->CustomCommands.begin();
- cci != this->CustomCommands.end(); ++cci) {
- cmCustomCommand const* cc = *cci;
+ for (cmCustomCommand const* cc : this->CustomCommands) {
cmCustomCommandGenerator ccg(*cc, this->GetConfigName(),
this->GetLocalGenerator());
const std::vector<std::string>& ccoutputs = ccg.GetOutputs();
@@ -765,10 +754,8 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatements()
}
std::vector<cmSourceFile const*> objectSources;
this->GeneratorTarget->GetObjectSources(objectSources, config);
- for (std::vector<cmSourceFile const*>::const_iterator si =
- objectSources.begin();
- si != objectSources.end(); ++si) {
- this->WriteObjectBuildStatement(*si);
+ for (cmSourceFile const* sf : objectSources) {
+ this->WriteObjectBuildStatement(sf);
}
if (!this->DDIFiles.empty()) {
@@ -845,10 +832,9 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement(
if (const char* objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
std::vector<std::string> depList;
cmSystemTools::ExpandListArgument(objectDeps, depList);
- for (std::vector<std::string>::iterator odi = depList.begin();
- odi != depList.end(); ++odi) {
- if (cmSystemTools::FileIsFullPath(*odi)) {
- *odi = cmSystemTools::CollapseFullPath(*odi);
+ for (std::string& odi : depList) {
+ if (cmSystemTools::FileIsFullPath(odi)) {
+ odi = cmSystemTools::CollapseFullPath(odi);
}
}
std::transform(depList.begin(), depList.end(),
@@ -896,9 +882,15 @@ void cmNinjaTargetGenerator::WriteObjectBuildStatement(
// The actual compilation will now use the preprocessed source.
explicitDeps.push_back(ppFileName);
- // Preprocessing and compilation use the same flags.
+ // Preprocessing and compilation generally use the same flags.
ppVars["FLAGS"] = vars["FLAGS"];
+ // In case compilation requires flags that are incompatible with
+ // preprocessing, include them here.
+ std::string const postFlag =
+ this->Makefile->GetSafeDefinition("CMAKE_Fortran_POSTPROCESS_FLAG");
+ this->LocalGenerator->AppendFlags(vars["FLAGS"], postFlag);
+
// Move preprocessor definitions to the preprocessor build statement.
std::swap(ppVars["DEFINES"], vars["DEFINES"]);
@@ -1010,19 +1002,17 @@ void cmNinjaTargetGenerator::WriteTargetDependInfo(std::string const& lang)
std::vector<std::string> includes;
this->LocalGenerator->GetIncludeDirectories(includes, this->GeneratorTarget,
lang, this->GetConfigName());
- for (std::vector<std::string>::iterator i = includes.begin();
- i != includes.end(); ++i) {
+ for (std::string const& i : includes) {
// Convert the include directories the same way we do for -I flags.
// See upstream ninja issue 1251.
- tdi_include_dirs.append(this->ConvertToNinjaPath(*i));
+ tdi_include_dirs.append(this->ConvertToNinjaPath(i));
}
Json::Value& tdi_linked_target_dirs = tdi["linked-target-dirs"] =
Json::arrayValue;
std::vector<std::string> linked = this->GetLinkedTargetDirectories();
- for (std::vector<std::string>::iterator i = linked.begin();
- i != linked.end(); ++i) {
- tdi_linked_target_dirs.append(*i);
+ for (std::string const& l : linked) {
+ tdi_linked_target_dirs.append(l);
}
std::string const tdin = this->GetTargetDependInfoPath(lang);
@@ -1087,13 +1077,12 @@ void cmNinjaTargetGenerator::ExportObjectCompileCommand(
cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
}
- CM_AUTO_PTR<cmRulePlaceholderExpander> rulePlaceholderExpander(
+ std::unique_ptr<cmRulePlaceholderExpander> rulePlaceholderExpander(
this->GetLocalGenerator()->CreateRulePlaceholderExpander());
- for (std::vector<std::string>::iterator i = compileCmds.begin();
- i != compileCmds.end(); ++i) {
+ for (std::string& i : compileCmds) {
// no launcher for CMAKE_EXPORT_COMPILE_COMMANDS
- rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), *i,
+ rulePlaceholderExpander->ExpandRuleVariables(this->GetLocalGenerator(), i,
compileObjectVars);
}
diff --git a/Source/cmNinjaTargetGenerator.h b/Source/cmNinjaTargetGenerator.h
index 5eb7a9a49..770a99d7f 100644
--- a/Source/cmNinjaTargetGenerator.h
+++ b/Source/cmNinjaTargetGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmNinjaTargetGenerator_h
#define cmNinjaTargetGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmCommonTargetGenerator.h"
#include "cmGlobalNinjaGenerator.h"
@@ -31,7 +31,7 @@ public:
cmNinjaTargetGenerator(cmGeneratorTarget* target);
/// Destructor.
- ~cmNinjaTargetGenerator() CM_OVERRIDE;
+ ~cmNinjaTargetGenerator() override;
virtual void Generate() = 0;
@@ -77,8 +77,7 @@ protected:
std::string ComputeFlagsForObject(cmSourceFile const* source,
const std::string& language);
- void AddIncludeFlags(std::string& flags,
- std::string const& lang) CM_OVERRIDE;
+ void AddIncludeFlags(std::string& flags, std::string const& lang) override;
std::string ComputeDefines(cmSourceFile const* source,
const std::string& language);
@@ -142,8 +141,7 @@ protected:
{
}
- void operator()(cmSourceFile const& source,
- const char* pkgloc) CM_OVERRIDE;
+ void operator()(cmSourceFile const& source, const char* pkgloc) override;
private:
cmNinjaTargetGenerator* Generator;
diff --git a/Source/cmNinjaTypes.h b/Source/cmNinjaTypes.h
index ec435d9dd..9e962f135 100644
--- a/Source/cmNinjaTypes.h
+++ b/Source/cmNinjaTypes.h
@@ -6,6 +6,7 @@
#include "cmConfigure.h" // IWYU pragma: keep
#include <map>
+#include <set>
#include <string>
#include <vector>
@@ -16,6 +17,7 @@ enum cmNinjaTargetDepends
};
typedef std::vector<std::string> cmNinjaDeps;
+typedef std::set<std::string> cmNinjaOuts;
typedef std::map<std::string, std::string> cmNinjaVars;
#endif // ! cmNinjaTypes_h
diff --git a/Source/cmNinjaUtilityTargetGenerator.cxx b/Source/cmNinjaUtilityTargetGenerator.cxx
index 500ff4a45..7adeb8e2b 100644
--- a/Source/cmNinjaUtilityTargetGenerator.cxx
+++ b/Source/cmNinjaUtilityTargetGenerator.cxx
@@ -51,17 +51,15 @@ void cmNinjaUtilityTargetGenerator::Generate()
bool uses_terminal = false;
for (unsigned i = 0; i != 2; ++i) {
- for (std::vector<cmCustomCommand>::const_iterator ci =
- cmdLists[i]->begin();
- ci != cmdLists[i]->end(); ++ci) {
- cmCustomCommandGenerator ccg(*ci, this->GetConfigName(),
+ for (cmCustomCommand const& ci : *cmdLists[i]) {
+ cmCustomCommandGenerator ccg(ci, this->GetConfigName(),
this->GetLocalGenerator());
this->GetLocalGenerator()->AppendCustomCommandDeps(ccg, deps);
this->GetLocalGenerator()->AppendCustomCommandLines(ccg, commands);
std::vector<std::string> const& ccByproducts = ccg.GetByproducts();
std::transform(ccByproducts.begin(), ccByproducts.end(),
std::back_inserter(util_outputs), MapToNinjaPath());
- if (ci->GetUsesTerminal()) {
+ if (ci.GetUsesTerminal()) {
uses_terminal = true;
}
}
@@ -71,9 +69,8 @@ void cmNinjaUtilityTargetGenerator::Generate()
std::string config =
this->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE");
this->GetGeneratorTarget()->GetSourceFiles(sources, config);
- for (std::vector<cmSourceFile*>::const_iterator source = sources.begin();
- source != sources.end(); ++source) {
- if (cmCustomCommand* cc = (*source)->GetCustomCommand()) {
+ for (cmSourceFile const* source : sources) {
+ if (cmCustomCommand const* cc = source->GetCustomCommand()) {
cmCustomCommandGenerator ccg(*cc, this->GetConfigName(),
this->GetLocalGenerator());
this->GetLocalGenerator()->AddCustomCommandTarget(
@@ -132,10 +129,8 @@ void cmNinjaUtilityTargetGenerator::Generate()
return;
}
- for (cmNinjaDeps::const_iterator oi = util_outputs.begin(),
- oe = util_outputs.end();
- oi != oe; ++oi) {
- this->GetGlobalGenerator()->SeenCustomCommandOutput(*oi);
+ for (std::string const& util_output : util_outputs) {
+ this->GetGlobalGenerator()->SeenCustomCommandOutput(util_output);
}
this->GetGlobalGenerator()->WriteCustomCommandBuild(
diff --git a/Source/cmNinjaUtilityTargetGenerator.h b/Source/cmNinjaUtilityTargetGenerator.h
index 9256e369c..01cc4595f 100644
--- a/Source/cmNinjaUtilityTargetGenerator.h
+++ b/Source/cmNinjaUtilityTargetGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmNinjaUtilityTargetGenerator_h
#define cmNinjaUtilityTargetGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmNinjaTargetGenerator.h"
@@ -13,9 +13,9 @@ class cmNinjaUtilityTargetGenerator : public cmNinjaTargetGenerator
{
public:
cmNinjaUtilityTargetGenerator(cmGeneratorTarget* target);
- ~cmNinjaUtilityTargetGenerator() CM_OVERRIDE;
+ ~cmNinjaUtilityTargetGenerator() override;
- void Generate() CM_OVERRIDE;
+ void Generate() override;
};
#endif // ! cmNinjaUtilityTargetGenerator_h
diff --git a/Source/cmOSXBundleGenerator.cxx b/Source/cmOSXBundleGenerator.cxx
index beddc6e6d..c85c82d84 100644
--- a/Source/cmOSXBundleGenerator.cxx
+++ b/Source/cmOSXBundleGenerator.cxx
@@ -2,8 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmOSXBundleGenerator.h"
-#include "cmConfigure.h"
-
#include "cmGeneratorTarget.h"
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
@@ -21,7 +19,7 @@ cmOSXBundleGenerator::cmOSXBundleGenerator(cmGeneratorTarget* target,
, Makefile(target->Target->GetMakefile())
, LocalGenerator(target->GetLocalGenerator())
, ConfigName(configName)
- , MacContentFolders(CM_NULLPTR)
+ , MacContentFolders(nullptr)
{
if (this->MustSkip()) {
return;
@@ -197,12 +195,11 @@ void cmOSXBundleGenerator::GenerateMacOSXContentStatements(
return;
}
- for (std::vector<cmSourceFile const*>::const_iterator si = sources.begin();
- si != sources.end(); ++si) {
+ for (cmSourceFile const* source : sources) {
cmGeneratorTarget::SourceFileFlags tsFlags =
- this->GT->GetTargetSourceFileFlags(*si);
+ this->GT->GetTargetSourceFileFlags(source);
if (tsFlags.Type != cmGeneratorTarget::SourceFileTypeNormal) {
- (*generator)(**si, tsFlags.MacFolder);
+ (*generator)(*source, tsFlags.MacFolder);
}
}
}
diff --git a/Source/cmOptionCommand.h b/Source/cmOptionCommand.h
index 634e3a824..34e0e6f01 100644
--- a/Source/cmOptionCommand.h
+++ b/Source/cmOptionCommand.h
@@ -3,7 +3,7 @@
#ifndef cmOptionCommand_h
#define cmOptionCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmOptionCommand; }
+ cmCommand* Clone() override { return new cmOptionCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmOrderDirectories.cxx b/Source/cmOrderDirectories.cxx
index 333e3134c..27ad71037 100644
--- a/Source/cmOrderDirectories.cxx
+++ b/Source/cmOrderDirectories.cxx
@@ -75,9 +75,8 @@ public:
void FindImplicitConflicts(std::ostringstream& w)
{
bool first = true;
- for (unsigned int i = 0; i < this->OD->OriginalDirectories.size(); ++i) {
+ for (std::string const& dir : this->OD->OriginalDirectories) {
// Check if this directory conflicts with the entry.
- std::string const& dir = this->OD->OriginalDirectories[i];
if (dir != this->Directory &&
cmSystemTools::GetRealPath(dir) !=
cmSystemTools::GetRealPath(this->Directory) &&
@@ -150,7 +149,7 @@ public:
}
}
- void Report(std::ostream& e) CM_OVERRIDE
+ void Report(std::ostream& e) override
{
e << "runtime library [";
if (this->SOName.empty()) {
@@ -161,7 +160,7 @@ public:
e << "]";
}
- bool FindConflict(std::string const& dir) CM_OVERRIDE;
+ bool FindConflict(std::string const& dir) override;
private:
// The soname of the shared library if it is known.
@@ -205,12 +204,12 @@ public:
{
}
- void Report(std::ostream& e) CM_OVERRIDE
+ void Report(std::ostream& e) override
{
e << "link library [" << this->FileName << "]";
}
- bool FindConflict(std::string const& dir) CM_OVERRIDE;
+ bool FindConflict(std::string const& dir) override;
};
bool cmOrderDirectoriesConstraintLibrary::FindConflict(std::string const& dir)
@@ -226,12 +225,10 @@ bool cmOrderDirectoriesConstraintLibrary::FindConflict(std::string const& dir)
this->OD->RemoveLibraryExtension.find(this->FileName)) {
std::string lib = this->OD->RemoveLibraryExtension.match(1);
std::string ext = this->OD->RemoveLibraryExtension.match(2);
- for (std::vector<std::string>::iterator i =
- this->OD->LinkExtensions.begin();
- i != this->OD->LinkExtensions.end(); ++i) {
- if (*i != ext) {
+ for (std::string const& LinkExtension : this->OD->LinkExtensions) {
+ if (LinkExtension != ext) {
std::string fname = lib;
- fname += *i;
+ fname += LinkExtension;
if (this->FileMayConflict(dir, fname)) {
return true;
}
@@ -346,9 +343,8 @@ void cmOrderDirectories::SetImplicitDirectories(
std::set<std::string> const& implicitDirs)
{
this->ImplicitDirectories.clear();
- for (std::set<std::string>::const_iterator i = implicitDirs.begin();
- i != implicitDirs.end(); ++i) {
- this->ImplicitDirectories.insert(this->GetRealPath(*i));
+ for (std::string const& implicitDir : implicitDirs) {
+ this->ImplicitDirectories.insert(this->GetRealPath(implicitDir));
}
}
@@ -375,8 +371,8 @@ void cmOrderDirectories::CollectOriginalDirectories()
this->AddOriginalDirectories(this->UserDirectories);
// Add directories containing constraints.
- for (unsigned int i = 0; i < this->ConstraintEntries.size(); ++i) {
- this->ConstraintEntries[i]->AddDirectory();
+ for (cmOrderDirectoriesConstraint* entry : this->ConstraintEntries) {
+ entry->AddDirectory();
}
// Add language runtime directories last.
@@ -400,20 +396,19 @@ int cmOrderDirectories::AddOriginalDirectory(std::string const& dir)
void cmOrderDirectories::AddOriginalDirectories(
std::vector<std::string> const& dirs)
{
- for (std::vector<std::string>::const_iterator di = dirs.begin();
- di != dirs.end(); ++di) {
+ for (std::string const& dir : dirs) {
// We never explicitly specify implicit link directories.
- if (this->IsImplicitDirectory(*di)) {
+ if (this->IsImplicitDirectory(dir)) {
continue;
}
// Skip the empty string.
- if (di->empty()) {
+ if (dir.empty()) {
continue;
}
// Add this directory.
- this->AddOriginalDirectory(*di);
+ this->AddOriginalDirectory(dir);
}
}
@@ -442,16 +437,15 @@ void cmOrderDirectories::FindConflicts()
}
// Clean up the conflict graph representation.
- for (std::vector<ConflictList>::iterator i = this->ConflictGraph.begin();
- i != this->ConflictGraph.end(); ++i) {
+ for (ConflictList& cl : this->ConflictGraph) {
// Sort the outgoing edges for each graph node so that the
// original order will be preserved as much as possible.
- std::sort(i->begin(), i->end());
+ std::sort(cl.begin(), cl.end());
// Make the edge list unique so cycle detection will be reliable.
ConflictList::iterator last =
- std::unique(i->begin(), i->end(), cmOrderDirectoriesCompare());
- i->erase(last, i->end());
+ std::unique(cl.begin(), cl.end(), cmOrderDirectoriesCompare());
+ cl.erase(last, cl.end());
}
// Check items in implicit link directories.
@@ -463,12 +457,12 @@ void cmOrderDirectories::FindImplicitConflicts()
// Check for items in implicit link directories that have conflicts
// in the explicit directories.
std::ostringstream conflicts;
- for (unsigned int i = 0; i < this->ImplicitDirEntries.size(); ++i) {
- this->ImplicitDirEntries[i]->FindImplicitConflicts(conflicts);
+ for (cmOrderDirectoriesConstraint* entry : this->ImplicitDirEntries) {
+ entry->FindImplicitConflicts(conflicts);
}
// Skip warning if there were no conflicts.
- std::string text = conflicts.str();
+ std::string const text = conflicts.str();
if (text.empty()) {
return;
}
@@ -515,8 +509,8 @@ void cmOrderDirectories::VisitDirectory(unsigned int i)
// Visit the neighbors of the node first.
ConflictList const& clist = this->ConflictGraph[i];
- for (ConflictList::const_iterator j = clist.begin(); j != clist.end(); ++j) {
- this->VisitDirectory(j->first);
+ for (ConflictPair const& j : clist) {
+ this->VisitDirectory(j.first);
}
// Now that all directories required to come before this one have
@@ -542,10 +536,9 @@ void cmOrderDirectories::DiagnoseCycle()
for (unsigned int i = 0; i < this->ConflictGraph.size(); ++i) {
ConflictList const& clist = this->ConflictGraph[i];
e << " dir " << i << " is [" << this->OriginalDirectories[i] << "]\n";
- for (ConflictList::const_iterator j = clist.begin(); j != clist.end();
- ++j) {
- e << " dir " << j->first << " must precede it due to ";
- this->ConstraintEntries[j->second]->Report(e);
+ for (ConflictPair const& j : clist) {
+ e << " dir " << j.first << " must precede it due to ";
+ this->ConstraintEntries[j.second]->Report(e);
e << "\n";
}
}
diff --git a/Source/cmOrderDirectories.h b/Source/cmOrderDirectories.h
index 3a0637afb..5916f7ab4 100644
--- a/Source/cmOrderDirectories.h
+++ b/Source/cmOrderDirectories.h
@@ -3,7 +3,7 @@
#ifndef cmOrderDirectories_h
#define cmOrderDirectories_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmsys/RegularExpression.hxx"
#include <map>
@@ -26,7 +26,7 @@ public:
const char* purpose);
~cmOrderDirectories();
void AddRuntimeLibrary(std::string const& fullPath,
- const char* soname = CM_NULLPTR);
+ const char* soname = nullptr);
void AddLinkLibrary(std::string const& fullPath);
void AddUserDirectories(std::vector<std::string> const& extra);
void AddLanguageDirectories(std::vector<std::string> const& dirs);
diff --git a/Source/cmOutputConverter.cxx b/Source/cmOutputConverter.cxx
index 14c986dd8..dac656912 100644
--- a/Source/cmOutputConverter.cxx
+++ b/Source/cmOutputConverter.cxx
@@ -285,12 +285,11 @@ cmOutputConverter::FortranFormat cmOutputConverter::GetFortranFormat(
if (value && *value) {
std::vector<std::string> fmt;
cmSystemTools::ExpandListArgument(value, fmt);
- for (std::vector<std::string>::iterator fi = fmt.begin(); fi != fmt.end();
- ++fi) {
- if (*fi == "FIXED") {
+ for (std::string const& fi : fmt) {
+ if (fi == "FIXED") {
format = FortranFormatFixed;
}
- if (*fi == "FREE") {
+ if (fi == "FREE") {
format = FortranFormatFree;
}
}
@@ -389,7 +388,7 @@ int cmOutputConverter::Shell__CharNeedsQuotes(char c, int flags)
int cmOutputConverter::Shell__CharIsMakeVariableName(char c)
{
- return c && (c == '_' || isalpha(((int)c)));
+ return c && (c == '_' || isalpha((static_cast<int>(c))));
}
const char* cmOutputConverter::Shell__SkipMakeVariables(const char* c)
diff --git a/Source/cmOutputRequiredFilesCommand.cxx b/Source/cmOutputRequiredFilesCommand.cxx
index 2339d6876..cde90375f 100644
--- a/Source/cmOutputRequiredFilesCommand.cxx
+++ b/Source/cmOutputRequiredFilesCommand.cxx
@@ -13,7 +13,6 @@
#include "cmSourceFile.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
-#include "cm_unordered_map.hxx"
class cmExecutionStatus;
@@ -31,7 +30,7 @@ public:
*/
cmDependInformation()
: DependDone(false)
- , SourceFile(CM_NULLPTR)
+ , SourceFile(nullptr)
{
}
@@ -114,8 +113,9 @@ public:
std::set<std::string> uniqueIncludes;
std::vector<std::string> orderedAndUniqueIncludes;
cmTargets& targets = this->Makefile->GetTargets();
- for (cmTargets::iterator l = targets.begin(); l != targets.end(); ++l) {
- const char* incDirProp = l->second.GetProperty("INCLUDE_DIRECTORIES");
+ for (auto const& target : targets) {
+ const char* incDirProp =
+ target.second.GetProperty("INCLUDE_DIRECTORIES");
if (!incDirProp) {
continue;
}
@@ -126,9 +126,7 @@ public:
std::vector<std::string> includes;
cmSystemTools::ExpandListArgument(incDirs, includes);
- for (std::vector<std::string>::const_iterator j = includes.begin();
- j != includes.end(); ++j) {
- std::string path = *j;
+ for (std::string& path : includes) {
this->Makefile->ExpandVariablesInString(path);
if (uniqueIncludes.insert(path).second) {
orderedAndUniqueIncludes.push_back(path);
@@ -136,10 +134,8 @@ public:
}
}
- for (std::vector<std::string>::const_iterator it =
- orderedAndUniqueIncludes.begin();
- it != orderedAndUniqueIncludes.end(); ++it) {
- this->AddSearchPath(*it);
+ for (std::string const& inc : orderedAndUniqueIncludes) {
+ this->AddSearchPath(inc);
}
}
@@ -157,7 +153,7 @@ public:
*/
const cmDependInformation* FindDependencies(const char* file)
{
- cmDependInformation* info = this->GetDependInformation(file, CM_NULLPTR);
+ cmDependInformation* info = this->GetDependInformation(file, nullptr);
this->GenerateDependInformation(info);
return info;
}
@@ -202,7 +198,7 @@ protected:
message += includeFile;
message += " for file ";
message += info->FullPath;
- cmSystemTools::Error(message.c_str(), CM_NULLPTR);
+ cmSystemTools::Error(message.c_str(), nullptr);
}
continue;
}
@@ -220,10 +216,7 @@ protected:
if (cmSystemTools::FileExists(cxxFile.c_str())) {
found = true;
}
- for (std::vector<std::string>::iterator i =
- this->IncludeDirectories.begin();
- i != this->IncludeDirectories.end(); ++i) {
- std::string path = *i;
+ for (std::string path : this->IncludeDirectories) {
path = path + "/";
path = path + cxxFile;
if (cmSystemTools::FileExists(path.c_str())) {
@@ -235,10 +228,7 @@ protected:
if (cmSystemTools::FileExists(cxxFile.c_str())) {
found = true;
}
- for (std::vector<std::string>::iterator i =
- this->IncludeDirectories.begin();
- i != this->IncludeDirectories.end(); ++i) {
- std::string path = *i;
+ for (std::string path : this->IncludeDirectories) {
path = path + "/";
path = path + cxxFile;
if (cmSystemTools::FileExists(path.c_str())) {
@@ -251,10 +241,7 @@ protected:
if (cmSystemTools::FileExists(cxxFile.c_str())) {
found = true;
}
- for (std::vector<std::string>::iterator i =
- this->IncludeDirectories.begin();
- i != this->IncludeDirectories.end(); ++i) {
- std::string path = *i;
+ for (std::string path : this->IncludeDirectories) {
path = path + "/";
path = path + cxxFile;
if (cmSystemTools::FileExists(path.c_str())) {
@@ -267,10 +254,7 @@ protected:
if (cmSystemTools::FileExists(cxxFile.c_str())) {
found = true;
}
- for (std::vector<std::string>::iterator i =
- this->IncludeDirectories.begin();
- i != this->IncludeDirectories.end(); ++i) {
- std::string path = *i;
+ for (std::string path : this->IncludeDirectories) {
path = path + "/";
path = path + cxxFile;
if (cmSystemTools::FileExists(path.c_str())) {
@@ -328,7 +312,7 @@ protected:
// See if the cmSourceFile for it has any files specified as
// dependency hints.
- if (info->SourceFile != CM_NULLPTR) {
+ if (info->SourceFile != nullptr) {
// Get the cmSourceFile corresponding to this.
const cmSourceFile& cFile = *(info->SourceFile);
@@ -337,10 +321,8 @@ protected:
if (!cFile.GetDepends().empty()) {
// Dependency hints have been given. Use them to begin the
// recursion.
- for (std::vector<std::string>::const_iterator file =
- cFile.GetDepends().begin();
- file != cFile.GetDepends().end(); ++file) {
- this->AddDependency(info, file->c_str());
+ for (std::string const& file : cFile.GetDepends()) {
+ this->AddDependency(info, file.c_str());
}
// Found dependency information. We are done.
@@ -357,10 +339,7 @@ protected:
found = true;
} else {
// try to guess which include path to use
- for (std::vector<std::string>::iterator t =
- this->IncludeDirectories.begin();
- t != this->IncludeDirectories.end(); ++t) {
- std::string incpath = *t;
+ for (std::string incpath : this->IncludeDirectories) {
if (!incpath.empty() && incpath[incpath.size() - 1] != '/') {
incpath = incpath + "/";
}
@@ -383,7 +362,7 @@ protected:
} else {
// Destroy the name of the file so that it won't be output as a
// dependency.
- info->FullPath = "";
+ info->FullPath.clear();
}
}
}
@@ -442,10 +421,7 @@ protected:
return fp;
}
- for (std::vector<std::string>::iterator i =
- this->IncludeDirectories.begin();
- i != this->IncludeDirectories.end(); ++i) {
- std::string path = *i;
+ for (std::string path : this->IncludeDirectories) {
if (!path.empty() && path[path.size() - 1] != '/') {
path = path + "/";
}
@@ -532,19 +508,17 @@ void cmOutputRequiredFilesCommand::ListDependencies(
// add info to the visited set
visited->insert(info);
// now recurse with info's dependencies
- for (cmDependInformation::DependencySetType::const_iterator d =
- info->DependencySet.begin();
- d != info->DependencySet.end(); ++d) {
- if (visited->find(*d) == visited->end()) {
- if (info->FullPath != "") {
- std::string tmp = (*d)->FullPath;
+ for (cmDependInformation* d : info->DependencySet) {
+ if (visited->find(d) == visited->end()) {
+ if (!info->FullPath.empty()) {
+ std::string tmp = d->FullPath;
std::string::size_type pos = tmp.rfind('.');
if (pos != std::string::npos && (tmp.substr(pos) != ".h")) {
tmp = tmp.substr(0, pos);
- fprintf(fout, "%s\n", (*d)->FullPath.c_str());
+ fprintf(fout, "%s\n", d->FullPath.c_str());
}
}
- this->ListDependencies(*d, fout, visited);
+ this->ListDependencies(d, fout, visited);
}
}
}
diff --git a/Source/cmOutputRequiredFilesCommand.h b/Source/cmOutputRequiredFilesCommand.h
index d20bfbdc1..09e622b41 100644
--- a/Source/cmOutputRequiredFilesCommand.h
+++ b/Source/cmOutputRequiredFilesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmOutputRequiredFilesCommand_h
#define cmOutputRequiredFilesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <set>
#include <stdio.h>
@@ -18,9 +18,9 @@ class cmExecutionStatus;
class cmOutputRequiredFilesCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmOutputRequiredFilesCommand; }
+ cmCommand* Clone() override { return new cmOutputRequiredFilesCommand; }
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
void ListDependencies(cmDependInformation const* info, FILE* fout,
std::set<cmDependInformation const*>* visited);
diff --git a/Source/cmParseArgumentsCommand.cxx b/Source/cmParseArgumentsCommand.cxx
index d75ee8e86..0922e6e24 100644
--- a/Source/cmParseArgumentsCommand.cxx
+++ b/Source/cmParseArgumentsCommand.cxx
@@ -5,7 +5,6 @@
#include <map>
#include <set>
#include <sstream>
-#include <stddef.h>
#include <utility>
#include "cmAlgorithms.h"
@@ -19,11 +18,11 @@ static std::string escape_arg(const std::string& arg)
{
// replace ";" with "\;" so output argument lists will split correctly
std::string escapedArg;
- for (size_t i = 0; i < arg.size(); ++i) {
- if (arg[i] == ';') {
+ for (char i : arg) {
+ if (i == ';') {
escapedArg += '\\';
}
- escapedArg += arg[i];
+ escapedArg += i;
}
return escapedArg;
}
@@ -70,7 +69,7 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args,
// options, single values and multi values
typedef std::map<std::string, bool> options_map;
typedef std::map<std::string, std::string> single_map;
- typedef std::map<std::string, std::vector<std::string> > multi_map;
+ typedef std::map<std::string, std::vector<std::string>> multi_map;
options_map options;
single_map single;
multi_map multi;
@@ -85,37 +84,31 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args,
// the second argument is a (cmake) list of options without argument
std::vector<std::string> list;
cmSystemTools::ExpandListArgument(*argIter++, list);
- for (std::vector<std::string>::const_iterator iter = list.begin(),
- end = list.end();
- iter != end; ++iter) {
- if (!used_keywords.insert(*iter).second) {
- this->GetMakefile()->IssueMessage(cmake::WARNING, dup_warning + *iter);
+ for (std::string const& iter : list) {
+ if (!used_keywords.insert(iter).second) {
+ this->GetMakefile()->IssueMessage(cmake::WARNING, dup_warning + iter);
}
- options[*iter]; // default initialize
+ options[iter]; // default initialize
}
// the third argument is a (cmake) list of single argument options
list.clear();
cmSystemTools::ExpandListArgument(*argIter++, list);
- for (std::vector<std::string>::const_iterator iter = list.begin(),
- end = list.end();
- iter != end; ++iter) {
- if (!used_keywords.insert(*iter).second) {
- this->GetMakefile()->IssueMessage(cmake::WARNING, dup_warning + *iter);
+ for (std::string const& iter : list) {
+ if (!used_keywords.insert(iter).second) {
+ this->GetMakefile()->IssueMessage(cmake::WARNING, dup_warning + iter);
}
- single[*iter]; // default initialize
+ single[iter]; // default initialize
}
// the fourth argument is a (cmake) list of multi argument options
list.clear();
cmSystemTools::ExpandListArgument(*argIter++, list);
- for (std::vector<std::string>::const_iterator iter = list.begin(),
- end = list.end();
- iter != end; ++iter) {
- if (!used_keywords.insert(*iter).second) {
- this->GetMakefile()->IssueMessage(cmake::WARNING, dup_warning + *iter);
+ for (std::string const& iter : list) {
+ if (!used_keywords.insert(iter).second) {
+ this->GetMakefile()->IssueMessage(cmake::WARNING, dup_warning + iter);
}
- multi[*iter]; // default initialize
+ multi[iter]; // default initialize
}
enum insideValues
@@ -160,46 +153,45 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args,
}
// iterate over the arguments list and fill in the values where applicable
- for (argIter = list.begin(), argEnd = list.end(); argIter != argEnd;
- ++argIter) {
- const options_map::iterator optIter = options.find(*argIter);
+ for (std::string const& arg : list) {
+ const options_map::iterator optIter = options.find(arg);
if (optIter != options.end()) {
insideValues = NONE;
optIter->second = true;
continue;
}
- const single_map::iterator singleIter = single.find(*argIter);
+ const single_map::iterator singleIter = single.find(arg);
if (singleIter != single.end()) {
insideValues = SINGLE;
- currentArgName = *argIter;
+ currentArgName = arg;
continue;
}
- const multi_map::iterator multiIter = multi.find(*argIter);
+ const multi_map::iterator multiIter = multi.find(arg);
if (multiIter != multi.end()) {
insideValues = MULTI;
- currentArgName = *argIter;
+ currentArgName = arg;
continue;
}
switch (insideValues) {
case SINGLE:
- single[currentArgName] = *argIter;
+ single[currentArgName] = arg;
insideValues = NONE;
break;
case MULTI:
if (parseFromArgV) {
- multi[currentArgName].push_back(escape_arg(*argIter));
+ multi[currentArgName].push_back(escape_arg(arg));
} else {
- multi[currentArgName].push_back(*argIter);
+ multi[currentArgName].push_back(arg);
}
break;
default:
if (parseFromArgV) {
- unparsed.push_back(escape_arg(*argIter));
+ unparsed.push_back(escape_arg(arg));
} else {
- unparsed.push_back(*argIter);
+ unparsed.push_back(arg);
}
break;
}
@@ -208,28 +200,24 @@ bool cmParseArgumentsCommand::InitialPass(std::vector<std::string> const& args,
// now iterate over the collected values and update their definition
// within the current scope. undefine if necessary.
- for (options_map::const_iterator iter = options.begin(), end = options.end();
- iter != end; ++iter) {
- this->Makefile->AddDefinition(prefix + iter->first,
- iter->second ? "TRUE" : "FALSE");
+ for (auto const& iter : options) {
+ this->Makefile->AddDefinition(prefix + iter.first,
+ iter.second ? "TRUE" : "FALSE");
}
- for (single_map::const_iterator iter = single.begin(), end = single.end();
- iter != end; ++iter) {
- if (!iter->second.empty()) {
- this->Makefile->AddDefinition(prefix + iter->first,
- iter->second.c_str());
+ for (auto const& iter : single) {
+ if (!iter.second.empty()) {
+ this->Makefile->AddDefinition(prefix + iter.first, iter.second.c_str());
} else {
- this->Makefile->RemoveDefinition(prefix + iter->first);
+ this->Makefile->RemoveDefinition(prefix + iter.first);
}
}
- for (multi_map::const_iterator iter = multi.begin(), end = multi.end();
- iter != end; ++iter) {
- if (!iter->second.empty()) {
+ for (auto const& iter : multi) {
+ if (!iter.second.empty()) {
this->Makefile->AddDefinition(
- prefix + iter->first, cmJoin(cmMakeRange(iter->second), ";").c_str());
+ prefix + iter.first, cmJoin(cmMakeRange(iter.second), ";").c_str());
} else {
- this->Makefile->RemoveDefinition(prefix + iter->first);
+ this->Makefile->RemoveDefinition(prefix + iter.first);
}
}
diff --git a/Source/cmParseArgumentsCommand.h b/Source/cmParseArgumentsCommand.h
index 359fb85b9..b8ba61d21 100644
--- a/Source/cmParseArgumentsCommand.h
+++ b/Source/cmParseArgumentsCommand.h
@@ -3,7 +3,7 @@
#ifndef cmParseArgumentsCommand_h
#define cmParseArgumentsCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -21,14 +21,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmParseArgumentsCommand; }
+ cmCommand* Clone() override { return new cmParseArgumentsCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmPathLabel.cxx b/Source/cmPathLabel.cxx
index 30ba08151..4793206f9 100644
--- a/Source/cmPathLabel.cxx
+++ b/Source/cmPathLabel.cxx
@@ -2,15 +2,13 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmPathLabel.h"
-#include <stddef.h>
-
cmPathLabel::cmPathLabel(const std::string& label)
: Label(label)
, Hash(0)
{
// Use a Jenkins one-at-a-time hash with under/over-flow protection
- for (size_t i = 0; i < this->Label.size(); ++i) {
- this->Hash += this->Label[i];
+ for (char i : this->Label) {
+ this->Hash += i;
this->Hash += ((this->Hash & 0x003FFFFF) << 10);
this->Hash ^= ((this->Hash & 0xFFFFFFC0) >> 6);
}
diff --git a/Source/cmPipeConnection.cxx b/Source/cmPipeConnection.cxx
new file mode 100644
index 000000000..9e565f60a
--- /dev/null
+++ b/Source/cmPipeConnection.cxx
@@ -0,0 +1,82 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmPipeConnection.h"
+
+#include "cmServer.h"
+
+cmPipeConnection::cmPipeConnection(const std::string& name,
+ cmConnectionBufferStrategy* bufferStrategy)
+ : cmEventBasedConnection(bufferStrategy)
+ , PipeName(name)
+{
+}
+
+void cmPipeConnection::Connect(uv_stream_t* server)
+{
+ if (this->ClientPipe) {
+ // Accept and close all pipes but the first:
+ uv_pipe_t* rejectPipe = new uv_pipe_t();
+
+ uv_pipe_init(this->Server->GetLoop(), rejectPipe, 0);
+ uv_accept(server, reinterpret_cast<uv_stream_t*>(rejectPipe));
+ uv_close(reinterpret_cast<uv_handle_t*>(rejectPipe),
+ &on_close_delete<uv_pipe_t>);
+ return;
+ }
+
+ this->ClientPipe = new uv_pipe_t();
+ uv_pipe_init(this->Server->GetLoop(), this->ClientPipe, 0);
+ this->ClientPipe->data = static_cast<cmEventBasedConnection*>(this);
+ auto client = reinterpret_cast<uv_stream_t*>(this->ClientPipe);
+ if (uv_accept(server, client) != 0) {
+ uv_close(reinterpret_cast<uv_handle_t*>(client),
+ &on_close_delete<uv_pipe_t>);
+ this->ClientPipe = nullptr;
+ return;
+ }
+ this->ReadStream = client;
+ this->WriteStream = client;
+
+ uv_read_start(this->ReadStream, on_alloc_buffer, on_read);
+ Server->OnConnected(this);
+}
+
+bool cmPipeConnection::OnServeStart(std::string* errorMessage)
+{
+ this->ServerPipe = new uv_pipe_t();
+ uv_pipe_init(this->Server->GetLoop(), this->ServerPipe, 0);
+ this->ServerPipe->data = static_cast<cmEventBasedConnection*>(this);
+
+ int r;
+ if ((r = uv_pipe_bind(this->ServerPipe, this->PipeName.c_str())) != 0) {
+ *errorMessage = std::string("Internal Error with ") + this->PipeName +
+ ": " + uv_err_name(r);
+ return false;
+ }
+ auto serverStream = reinterpret_cast<uv_stream_t*>(this->ServerPipe);
+ if ((r = uv_listen(serverStream, 1, on_new_connection)) != 0) {
+ *errorMessage = std::string("Internal Error listening on ") +
+ this->PipeName + ": " + uv_err_name(r);
+ return false;
+ }
+
+ return cmConnection::OnServeStart(errorMessage);
+}
+
+bool cmPipeConnection::OnConnectionShuttingDown()
+{
+ if (this->ClientPipe) {
+ uv_close(reinterpret_cast<uv_handle_t*>(this->ClientPipe),
+ &on_close_delete<uv_pipe_t>);
+ this->WriteStream->data = nullptr;
+ }
+ uv_close(reinterpret_cast<uv_handle_t*>(this->ServerPipe),
+ &on_close_delete<uv_pipe_t>);
+
+ this->ClientPipe = nullptr;
+ this->ServerPipe = nullptr;
+ this->WriteStream = nullptr;
+ this->ReadStream = nullptr;
+
+ return cmEventBasedConnection::OnConnectionShuttingDown();
+}
diff --git a/Source/cmPipeConnection.h b/Source/cmPipeConnection.h
new file mode 100644
index 000000000..7b8984296
--- /dev/null
+++ b/Source/cmPipeConnection.h
@@ -0,0 +1,28 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#pragma once
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <string>
+
+#include "cmConnection.h"
+#include "cm_uv.h"
+
+class cmPipeConnection : public cmEventBasedConnection
+{
+public:
+ cmPipeConnection(const std::string& name,
+ cmConnectionBufferStrategy* bufferStrategy = nullptr);
+
+ bool OnServeStart(std::string* pString) override;
+
+ bool OnConnectionShuttingDown() override;
+
+ void Connect(uv_stream_t* server) override;
+
+private:
+ const std::string PipeName;
+ uv_pipe_t* ServerPipe = nullptr;
+ uv_pipe_t* ClientPipe = nullptr;
+};
diff --git a/Source/cmPolicies.cxx b/Source/cmPolicies.cxx
index da3edd427..e7d1b7218 100644
--- a/Source/cmPolicies.cxx
+++ b/Source/cmPolicies.cxx
@@ -8,7 +8,6 @@
#include "cmVersion.h"
#include "cmake.h"
-#include "cmConfigure.h"
#include <assert.h>
#include <ctype.h>
#include <sstream>
@@ -62,9 +61,9 @@ static const char* idToString(cmPolicies::PolicyID id)
CM_FOR_EACH_POLICY_ID(POLICY_CASE)
#undef POLICY_CASE
case cmPolicies::CMPCOUNT:
- return CM_NULLPTR;
+ return nullptr;
}
- return CM_NULLPTR;
+ return nullptr;
}
static const char* idToVersion(cmPolicies::PolicyID id)
@@ -76,9 +75,9 @@ static const char* idToVersion(cmPolicies::PolicyID id)
CM_FOR_EACH_POLICY_ID_VERSION(POLICY_CASE)
#undef POLICY_CASE
case cmPolicies::CMPCOUNT:
- return CM_NULLPTR;
+ return nullptr;
}
- return CM_NULLPTR;
+ return nullptr;
}
static bool isPolicyNewerThan(cmPolicies::PolicyID id, unsigned int majorV,
@@ -108,9 +107,9 @@ const char* idToShortDescription(cmPolicies::PolicyID id)
CM_FOR_EACH_POLICY_ID_DOC(POLICY_CASE)
#undef POLICY_CASE
case cmPolicies::CMPCOUNT:
- return CM_NULLPTR;
+ return nullptr;
}
- return CM_NULLPTR;
+ return nullptr;
}
static void DiagnoseAncientPolicies(
@@ -121,9 +120,8 @@ static void DiagnoseAncientPolicies(
e << "The project requests behavior compatible with CMake version \""
<< majorVer << "." << minorVer << "." << patchVer
<< "\", which requires the OLD behavior for some policies:\n";
- for (std::vector<cmPolicies::PolicyID>::const_iterator i = ancient.begin();
- i != ancient.end(); ++i) {
- e << " " << idToString(*i) << ": " << idToShortDescription(*i) << "\n";
+ for (cmPolicies::PolicyID i : ancient) {
+ e << " " << idToString(i) << ": " << idToShortDescription(i) << "\n";
}
e << "However, this version of CMake no longer supports the OLD "
<< "behavior for these policies. "
@@ -142,7 +140,7 @@ static bool GetPolicyDefault(cmMakefile* mf, std::string const& policy,
*defaultSetting = cmPolicies::NEW;
} else if (defaultValue == "OLD") {
*defaultSetting = cmPolicies::OLD;
- } else if (defaultValue == "") {
+ } else if (defaultValue.empty()) {
*defaultSetting = cmPolicies::WARN;
} else {
std::ostringstream e;
diff --git a/Source/cmPolicies.h b/Source/cmPolicies.h
index 69cbc1844..6c33e2b0f 100644
--- a/Source/cmPolicies.h
+++ b/Source/cmPolicies.h
@@ -126,7 +126,7 @@ class cmMakefile;
3, 0, 0, cmPolicies::WARN) \
SELECT(POLICY, CMP0040, \
"The target in the TARGET signature of add_custom_command() must " \
- "exist.", \
+ "exist and must be defined in the current directory.", \
3, 0, 0, cmPolicies::WARN) \
SELECT(POLICY, CMP0041, \
"Error on relative include with generator expression.", 3, 0, 0, \
@@ -206,7 +206,12 @@ class cmMakefile;
cmPolicies::WARN) \
SELECT(POLICY, CMP0069, \
"INTERPROCEDURAL_OPTIMIZATION is enforced when enabled.", 3, 9, 0, \
- cmPolicies::WARN)
+ cmPolicies::WARN) \
+ SELECT(POLICY, CMP0070, \
+ "Define file(GENERATE) behavior for relative paths.", 3, 10, 0, \
+ cmPolicies::WARN) \
+ SELECT(POLICY, CMP0071, "Let AUTOMOC and AUTOUIC process GENERATED files.", \
+ 3, 10, 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/cmProcessTools.cxx b/Source/cmProcessTools.cxx
index de7b06126..7ab1fa3fc 100644
--- a/Source/cmProcessTools.cxx
+++ b/Source/cmProcessTools.cxx
@@ -10,22 +10,22 @@ void cmProcessTools::RunProcess(struct cmsysProcess_s* cp, OutputParser* out,
OutputParser* err, Encoding encoding)
{
cmsysProcess_Execute(cp);
- char* data = CM_NULLPTR;
+ char* data = nullptr;
int length = 0;
int p;
cmProcessOutput processOutput(encoding);
std::string strdata;
while ((out || err) &&
- (p = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR), p)) {
+ (p = cmsysProcess_WaitForData(cp, &data, &length, nullptr), p)) {
if (out && p == cmsysProcess_Pipe_STDOUT) {
processOutput.DecodeText(data, length, strdata, 1);
if (!out->Process(strdata.c_str(), int(strdata.size()))) {
- out = CM_NULLPTR;
+ out = nullptr;
}
} else if (err && p == cmsysProcess_Pipe_STDERR) {
processOutput.DecodeText(data, length, strdata, 2);
if (!err->Process(strdata.c_str(), int(strdata.size()))) {
- err = CM_NULLPTR;
+ err = nullptr;
}
}
}
@@ -38,15 +38,15 @@ void cmProcessTools::RunProcess(struct cmsysProcess_s* cp, OutputParser* out,
if (err) {
processOutput.DecodeText(std::string(), strdata, 2);
if (!strdata.empty()) {
- out->Process(strdata.c_str(), int(strdata.size()));
+ err->Process(strdata.c_str(), int(strdata.size()));
}
}
- cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ cmsysProcess_WaitForExit(cp, nullptr);
}
cmProcessTools::LineParser::LineParser(char sep, bool ignoreCR)
- : Log(CM_NULLPTR)
- , Prefix(CM_NULLPTR)
+ : Log(nullptr)
+ , Prefix(nullptr)
, Separator(sep)
, LineEnd('\0')
, IgnoreCR(ignoreCR)
@@ -73,11 +73,11 @@ bool cmProcessTools::LineParser::ProcessChunk(const char* first, int length)
// Hand this line to the subclass implementation.
if (!this->ProcessLine()) {
- this->Line = "";
+ this->Line.clear();
return false;
}
- this->Line = "";
+ this->Line.clear();
} else if (*c != '\r' || !this->IgnoreCR) {
// Append this character to the line under construction.
this->Line.append(1, *c);
diff --git a/Source/cmProcessTools.h b/Source/cmProcessTools.h
index e7d9a10eb..23fa74e85 100644
--- a/Source/cmProcessTools.h
+++ b/Source/cmProcessTools.h
@@ -3,7 +3,7 @@
#ifndef cmProcessTools_h
#define cmProcessTools_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmProcessOutput.h"
#include <iosfwd>
@@ -59,7 +59,7 @@ public:
char Separator;
char LineEnd;
bool IgnoreCR;
- bool ProcessChunk(const char* data, int length) CM_OVERRIDE;
+ bool ProcessChunk(const char* data, int length) override;
/** Implement in a subclass to process one line of input. It
should return true only if it is interested in more data. */
@@ -70,18 +70,18 @@ public:
class OutputLogger : public LineParser
{
public:
- OutputLogger(std::ostream& log, const char* prefix = CM_NULLPTR)
+ OutputLogger(std::ostream& log, const char* prefix = nullptr)
{
this->SetLog(&log, prefix);
}
private:
- bool ProcessLine() CM_OVERRIDE { return true; }
+ bool ProcessLine() override { return true; }
};
/** Run a process and send output to given parsers. */
static void RunProcess(struct cmsysProcess_s* cp, OutputParser* out,
- OutputParser* err = CM_NULLPTR,
+ OutputParser* err = nullptr,
Encoding encoding = cmProcessOutput::Auto);
};
diff --git a/Source/cmProjectCommand.cxx b/Source/cmProjectCommand.cxx
index d72c7909c..fea8a9dde 100644
--- a/Source/cmProjectCommand.cxx
+++ b/Source/cmProjectCommand.cxx
@@ -195,15 +195,14 @@ bool cmProjectCommand::InitialPass(std::vector<std::string> const& args,
vv.push_back(projectName + "_VERSION_PATCH");
vv.push_back(projectName + "_VERSION_TWEAK");
std::string vw;
- for (std::vector<std::string>::iterator i = vv.begin(); i != vv.end();
- ++i) {
- const char* v = this->Makefile->GetDefinition(*i);
+ for (std::string const& i : vv) {
+ const char* v = this->Makefile->GetDefinition(i);
if (v && *v) {
if (cmp0048 == cmPolicies::WARN) {
vw += "\n ";
- vw += *i;
+ vw += i;
} else {
- this->Makefile->AddDefinition(*i, "");
+ this->Makefile->AddDefinition(i, "");
}
}
}
diff --git a/Source/cmProjectCommand.h b/Source/cmProjectCommand.h
index 3c579ac9d..80fa235e2 100644
--- a/Source/cmProjectCommand.h
+++ b/Source/cmProjectCommand.h
@@ -3,7 +3,7 @@
#ifndef cmProjectCommand_h
#define cmProjectCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -26,14 +26,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmProjectCommand; }
+ cmCommand* Clone() override { return new cmProjectCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmProperty.cxx b/Source/cmProperty.cxx
index 222afb497..27f0ecd71 100644
--- a/Source/cmProperty.cxx
+++ b/Source/cmProperty.cxx
@@ -2,8 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmProperty.h"
-#include "cmConfigure.h"
-
void cmProperty::Set(const char* value)
{
this->Value = value;
@@ -24,5 +22,5 @@ const char* cmProperty::GetValue() const
if (this->ValueHasBeenSet) {
return this->Value.c_str();
}
- return CM_NULLPTR;
+ return nullptr;
}
diff --git a/Source/cmPropertyMap.cxx b/Source/cmPropertyMap.cxx
index 1e089d1c8..3f6d7c8a9 100644
--- a/Source/cmPropertyMap.cxx
+++ b/Source/cmPropertyMap.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmPropertyMap.h"
-#include "cmConfigure.h"
#include <algorithm>
#include <assert.h>
#include <utility>
@@ -22,9 +21,8 @@ cmProperty* cmPropertyMap::GetOrCreateProperty(const std::string& name)
std::vector<std::string> cmPropertyMap::GetPropertyList() const
{
std::vector<std::string> keyList;
- for (cmPropertyMap::const_iterator i = this->begin(), e = this->end();
- i != e; ++i) {
- keyList.push_back(i->first);
+ for (auto const& i : *this) {
+ keyList.push_back(i.first);
}
std::sort(keyList.begin(), keyList.end());
return keyList;
@@ -59,7 +57,7 @@ const char* cmPropertyMap::GetPropertyValue(const std::string& name) const
cmPropertyMap::const_iterator it = this->find(name);
if (it == this->end()) {
- return CM_NULLPTR;
+ return nullptr;
}
return it->second.GetValue();
}
diff --git a/Source/cmQTWrapCPPCommand.cxx b/Source/cmQTWrapCPPCommand.cxx
index de9e54505..ae1fdfae2 100644
--- a/Source/cmQTWrapCPPCommand.cxx
+++ b/Source/cmQTWrapCPPCommand.cxx
@@ -78,7 +78,7 @@ bool cmQTWrapCPPCommand::InitialPass(std::vector<std::string> const& args,
depends.push_back(hname);
std::string no_main_dependency;
- const char* no_working_dir = CM_NULLPTR;
+ const char* no_working_dir = nullptr;
this->Makefile->AddCustomCommandToOutput(
newName, depends, no_main_dependency, commandLines, "Qt Wrapped File",
no_working_dir);
diff --git a/Source/cmQTWrapCPPCommand.h b/Source/cmQTWrapCPPCommand.h
index ad1ccf38d..c1dcd545e 100644
--- a/Source/cmQTWrapCPPCommand.h
+++ b/Source/cmQTWrapCPPCommand.h
@@ -3,7 +3,7 @@
#ifndef cmQTWrapCPPCommand_h
#define cmQTWrapCPPCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmQTWrapCPPCommand; }
+ cmCommand* Clone() override { return new cmQTWrapCPPCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmQTWrapUICommand.cxx b/Source/cmQTWrapUICommand.cxx
index d3c663176..3d586d6bd 100644
--- a/Source/cmQTWrapUICommand.cxx
+++ b/Source/cmQTWrapUICommand.cxx
@@ -109,8 +109,8 @@ bool cmQTWrapUICommand::InitialPass(std::vector<std::string> const& args,
std::vector<std::string> depends;
depends.push_back(uiName);
std::string no_main_dependency;
- const char* no_comment = CM_NULLPTR;
- const char* no_working_dir = CM_NULLPTR;
+ const char* no_comment = nullptr;
+ const char* no_working_dir = nullptr;
this->Makefile->AddCustomCommandToOutput(
hName, depends, no_main_dependency, hCommandLines, no_comment,
no_working_dir);
diff --git a/Source/cmQTWrapUICommand.h b/Source/cmQTWrapUICommand.h
index ac7ab01c7..15cab406f 100644
--- a/Source/cmQTWrapUICommand.h
+++ b/Source/cmQTWrapUICommand.h
@@ -3,7 +3,7 @@
#ifndef cmQTWrapUICommand_h
#define cmQTWrapUICommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmQTWrapUICommand; }
+ cmCommand* Clone() override { return new cmQTWrapUICommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmQtAutoGen.cxx b/Source/cmQtAutoGen.cxx
new file mode 100644
index 000000000..5e89978b9
--- /dev/null
+++ b/Source/cmQtAutoGen.cxx
@@ -0,0 +1,374 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmQtAutoGen.h"
+#include "cmAlgorithms.h"
+#include "cmProcessOutput.h"
+#include "cmSystemTools.h"
+
+#include "cmsys/FStream.hxx"
+#include "cmsys/RegularExpression.hxx"
+
+#include <algorithm>
+#include <sstream>
+#include <stddef.h>
+
+// - Static variables
+
+std::string const genNameGen = "AutoGen";
+std::string const genNameMoc = "AutoMoc";
+std::string const genNameUic = "AutoUic";
+std::string const genNameRcc = "AutoRcc";
+
+std::string const mcNameSingle = "SINGLE";
+std::string const mcNameWrap = "WRAP";
+std::string const mcNameFull = "FULL";
+
+// - Static functions
+
+/// @brief Merges newOpts into baseOpts
+/// @arg valueOpts list of options that accept a value
+void MergeOptions(std::vector<std::string>& baseOpts,
+ std::vector<std::string> const& newOpts,
+ std::vector<std::string> const& valueOpts, bool isQt5)
+{
+ typedef std::vector<std::string>::iterator Iter;
+ typedef std::vector<std::string>::const_iterator CIter;
+ if (newOpts.empty()) {
+ return;
+ }
+ if (baseOpts.empty()) {
+ baseOpts = newOpts;
+ return;
+ }
+
+ std::vector<std::string> extraOpts;
+ for (CIter fit = newOpts.begin(), fitEnd = newOpts.end(); fit != fitEnd;
+ ++fit) {
+ std::string const& newOpt = *fit;
+ Iter existIt = std::find(baseOpts.begin(), baseOpts.end(), newOpt);
+ if (existIt != baseOpts.end()) {
+ if (newOpt.size() >= 2) {
+ // Acquire the option name
+ std::string optName;
+ {
+ auto oit = newOpt.begin();
+ if (*oit == '-') {
+ ++oit;
+ if (isQt5 && (*oit == '-')) {
+ ++oit;
+ }
+ optName.assign(oit, newOpt.end());
+ }
+ }
+ // Test if this is a value option and change the existing value
+ if (!optName.empty() && (std::find(valueOpts.begin(), valueOpts.end(),
+ optName) != valueOpts.end())) {
+ const Iter existItNext(existIt + 1);
+ const CIter fitNext(fit + 1);
+ if ((existItNext != baseOpts.end()) && (fitNext != fitEnd)) {
+ *existItNext = *fitNext;
+ ++fit;
+ }
+ }
+ }
+ } else {
+ extraOpts.push_back(newOpt);
+ }
+ }
+ // Append options
+ baseOpts.insert(baseOpts.end(), extraOpts.begin(), extraOpts.end());
+}
+
+static std::string utilStripCR(std::string const& line)
+{
+ // Strip CR characters rcc may have printed (possibly more than one!).
+ std::string::size_type cr = line.find('\r');
+ if (cr != std::string::npos) {
+ return line.substr(0, cr);
+ }
+ return line;
+}
+
+/// @brief Reads the resource files list from from a .qrc file - Qt4 version
+/// @return True if the .qrc file was successfully parsed
+static bool RccListInputsQt4(std::string const& fileName,
+ std::vector<std::string>& files,
+ std::string* errorMessage)
+{
+ bool allGood = true;
+ // Read qrc file content into string
+ std::string qrcContents;
+ {
+ cmsys::ifstream ifs(fileName.c_str());
+ if (ifs) {
+ std::ostringstream osst;
+ osst << ifs.rdbuf();
+ qrcContents = osst.str();
+ } else {
+ if (errorMessage != nullptr) {
+ std::ostringstream ost;
+ ost << "rcc file not readable:\n"
+ << " " << cmQtAutoGen::Quoted(fileName) << "\n";
+ *errorMessage = ost.str();
+ }
+ allGood = false;
+ }
+ }
+ if (allGood) {
+ // qrc file directory
+ std::string qrcDir(cmSystemTools::GetFilenamePath(fileName));
+ if (!qrcDir.empty()) {
+ qrcDir += '/';
+ }
+
+ cmsys::RegularExpression fileMatchRegex("(<file[^<]+)");
+ cmsys::RegularExpression fileReplaceRegex("(^<file[^>]*>)");
+
+ size_t offset = 0;
+ while (fileMatchRegex.find(qrcContents.c_str() + offset)) {
+ std::string qrcEntry = fileMatchRegex.match(1);
+ offset += qrcEntry.size();
+ {
+ fileReplaceRegex.find(qrcEntry);
+ std::string tag = fileReplaceRegex.match(1);
+ qrcEntry = qrcEntry.substr(tag.size());
+ }
+ if (!cmSystemTools::FileIsFullPath(qrcEntry.c_str())) {
+ qrcEntry = qrcDir + qrcEntry;
+ }
+ files.push_back(qrcEntry);
+ }
+ }
+ return allGood;
+}
+
+/// @brief Reads the resource files list from from a .qrc file - Qt5 version
+/// @return True if the .qrc file was successfully parsed
+static bool RccListInputsQt5(std::string const& rccCommand,
+ std::string const& fileName,
+ std::vector<std::string>& files,
+ std::string* errorMessage)
+{
+ if (rccCommand.empty()) {
+ cmSystemTools::Error("rcc executable not available");
+ return false;
+ }
+
+ // Read rcc features
+ bool hasDashDashList = false;
+ {
+ std::vector<std::string> command;
+ command.push_back(rccCommand);
+ command.push_back("--help");
+ std::string rccStdOut;
+ std::string rccStdErr;
+ int retVal = 0;
+ bool result = cmSystemTools::RunSingleCommand(
+ command, &rccStdOut, &rccStdErr, &retVal, nullptr,
+ cmSystemTools::OUTPUT_NONE, 0.0, cmProcessOutput::Auto);
+ if (result && retVal == 0 &&
+ rccStdOut.find("--list") != std::string::npos) {
+ hasDashDashList = true;
+ }
+ }
+
+ std::string const fileDir = cmSystemTools::GetFilenamePath(fileName);
+ std::string const fileNameName = cmSystemTools::GetFilenameName(fileName);
+
+ // Run rcc list command
+ bool result = false;
+ int retVal = 0;
+ std::string rccStdOut;
+ std::string rccStdErr;
+ {
+ std::vector<std::string> command;
+ command.push_back(rccCommand);
+ command.push_back(hasDashDashList ? "--list" : "-list");
+ command.push_back(fileNameName);
+ result = cmSystemTools::RunSingleCommand(
+ command, &rccStdOut, &rccStdErr, &retVal, fileDir.c_str(),
+ cmSystemTools::OUTPUT_NONE, 0.0, cmProcessOutput::Auto);
+ }
+ if (!result || retVal) {
+ if (errorMessage != nullptr) {
+ std::ostringstream ost;
+ ost << "rcc list process failed for\n " << cmQtAutoGen::Quoted(fileName)
+ << "\n"
+ << rccStdOut << "\n"
+ << rccStdErr << "\n";
+ *errorMessage = ost.str();
+ }
+ return false;
+ }
+
+ // Parse rcc std output
+ {
+ std::istringstream ostr(rccStdOut);
+ std::string oline;
+ while (std::getline(ostr, oline)) {
+ oline = utilStripCR(oline);
+ if (!oline.empty()) {
+ files.push_back(oline);
+ }
+ }
+ }
+ // Parse rcc error output
+ {
+ std::istringstream estr(rccStdErr);
+ std::string eline;
+ while (std::getline(estr, eline)) {
+ eline = utilStripCR(eline);
+ if (cmHasLiteralPrefix(eline, "RCC: Error in")) {
+ static std::string searchString = "Cannot find file '";
+
+ std::string::size_type pos = eline.find(searchString);
+ if (pos == std::string::npos) {
+ if (errorMessage != nullptr) {
+ std::ostringstream ost;
+ ost << "rcc lists unparsable output:\n"
+ << cmQtAutoGen::Quoted(eline) << "\n";
+ *errorMessage = ost.str();
+ }
+ return false;
+ }
+ pos += searchString.length();
+ std::string::size_type sz = eline.size() - pos - 1;
+ files.push_back(eline.substr(pos, sz));
+ }
+ }
+ }
+
+ // Convert relative paths to absolute paths
+ for (std::string& resFile : files) {
+ resFile = cmSystemTools::CollapseCombinedPath(fileDir, resFile);
+ }
+
+ return true;
+}
+
+// - Class definitions
+
+std::string const cmQtAutoGen::listSep = "@LSEP@";
+
+std::string const& cmQtAutoGen::GeneratorName(Generator type)
+{
+ switch (type) {
+ case Generator::GEN:
+ return genNameGen;
+ case Generator::MOC:
+ return genNameMoc;
+ case Generator::UIC:
+ return genNameUic;
+ case Generator::RCC:
+ return genNameRcc;
+ }
+ return genNameGen;
+}
+
+std::string cmQtAutoGen::GeneratorNameUpper(Generator genType)
+{
+ return cmSystemTools::UpperCase(cmQtAutoGen::GeneratorName(genType));
+}
+
+std::string const& cmQtAutoGen::MultiConfigName(MultiConfig config)
+{
+ switch (config) {
+ case MultiConfig::SINGLE:
+ return mcNameSingle;
+ case MultiConfig::WRAP:
+ return mcNameWrap;
+ case MultiConfig::FULL:
+ return mcNameFull;
+ }
+ return mcNameWrap;
+}
+
+cmQtAutoGen::MultiConfig cmQtAutoGen::MultiConfigType(std::string const& name)
+{
+ if (name == mcNameSingle) {
+ return MultiConfig::SINGLE;
+ }
+ if (name == mcNameFull) {
+ return MultiConfig::FULL;
+ }
+ return MultiConfig::WRAP;
+}
+
+std::string cmQtAutoGen::Quoted(std::string const& text)
+{
+ static const char* rep[18] = { "\\", "\\\\", "\"", "\\\"", "\a", "\\a",
+ "\b", "\\b", "\f", "\\f", "\n", "\\n",
+ "\r", "\\r", "\t", "\\t", "\v", "\\v" };
+
+ std::string res = text;
+ for (const char* const* it = cmArrayBegin(rep); it != cmArrayEnd(rep);
+ it += 2) {
+ cmSystemTools::ReplaceString(res, *it, *(it + 1));
+ }
+ res = '"' + res;
+ res += '"';
+ return res;
+}
+
+std::string cmQtAutoGen::AppendFilenameSuffix(std::string const& filename,
+ std::string const& suffix)
+{
+ std::string res;
+ auto pos = filename.rfind('.');
+ if (pos != std::string::npos) {
+ const auto it_dot = filename.begin() + pos;
+ res.assign(filename.begin(), it_dot);
+ res.append(suffix);
+ res.append(it_dot, filename.end());
+ } else {
+ res = filename;
+ res.append(suffix);
+ }
+ return res;
+}
+
+void cmQtAutoGen::UicMergeOptions(std::vector<std::string>& baseOpts,
+ std::vector<std::string> const& newOpts,
+ bool isQt5)
+{
+ static std::vector<std::string> const valueOpts = {
+ "tr", "translate", "postfix", "generator",
+ "include", // Since Qt 5.3
+ "g"
+ };
+ MergeOptions(baseOpts, newOpts, valueOpts, isQt5);
+}
+
+void cmQtAutoGen::RccMergeOptions(std::vector<std::string>& baseOpts,
+ std::vector<std::string> const& newOpts,
+ bool isQt5)
+{
+ static std::vector<std::string> const valueOpts = { "name", "root",
+ "compress",
+ "threshold" };
+ MergeOptions(baseOpts, newOpts, valueOpts, isQt5);
+}
+
+bool cmQtAutoGen::RccListInputs(std::string const& qtMajorVersion,
+ std::string const& rccCommand,
+ std::string const& fileName,
+ std::vector<std::string>& files,
+ std::string* errorMessage)
+{
+ bool allGood = false;
+ if (cmSystemTools::FileExists(fileName.c_str())) {
+ if (qtMajorVersion == "4") {
+ allGood = RccListInputsQt4(fileName, files, errorMessage);
+ } else {
+ allGood = RccListInputsQt5(rccCommand, fileName, files, errorMessage);
+ }
+ } else {
+ if (errorMessage != nullptr) {
+ std::ostringstream ost;
+ ost << "rcc file does not exist:\n"
+ << " " << cmQtAutoGen::Quoted(fileName) << "\n";
+ *errorMessage = ost.str();
+ }
+ }
+ return allGood;
+}
diff --git a/Source/cmQtAutoGen.h b/Source/cmQtAutoGen.h
new file mode 100644
index 000000000..acc092fb3
--- /dev/null
+++ b/Source/cmQtAutoGen.h
@@ -0,0 +1,72 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmQtAutoGen_h
+#define cmQtAutoGen_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <string>
+#include <vector>
+
+/** \class cmQtAutoGen
+ * \brief Class used as namespace for QtAutogen related types and functions
+ */
+class cmQtAutoGen
+{
+public:
+ static std::string const listSep;
+
+ enum Generator
+ {
+ GEN, // General
+ MOC,
+ UIC,
+ RCC
+ };
+
+ enum MultiConfig
+ {
+ SINGLE, // Single configuration
+ WRAP, // Multi configuration using wrapper files
+ FULL // Full multi configuration using per config sources
+ };
+
+public:
+ /// @brief Returns the generator name
+ static std::string const& GeneratorName(Generator genType);
+ /// @brief Returns the generator name in upper case
+ static std::string GeneratorNameUpper(Generator genType);
+
+ /// @brief Returns the multi configuration name string
+ static std::string const& MultiConfigName(MultiConfig config);
+ /// @brief Returns the multi configuration type
+ static MultiConfig MultiConfigType(std::string const& name);
+
+ /// @brief Returns a the string escaped and enclosed in quotes
+ static std::string Quoted(std::string const& text);
+
+ /// @brief Appends the suffix to the filename before the last dot
+ static std::string AppendFilenameSuffix(std::string const& filename,
+ std::string const& suffix);
+
+ /// @brief Merges newOpts into baseOpts
+ static void UicMergeOptions(std::vector<std::string>& baseOpts,
+ std::vector<std::string> const& newOpts,
+ bool isQt5);
+
+ /// @brief Merges newOpts into baseOpts
+ static void RccMergeOptions(std::vector<std::string>& baseOpts,
+ std::vector<std::string> const& newOpts,
+ bool isQt5);
+
+ /// @brief Reads the resource files list from from a .qrc file
+ /// @arg fileName Must be the absolute path of the .qrc file
+ /// @return True if the rcc file was successfully parsed
+ static bool RccListInputs(std::string const& qtMajorVersion,
+ std::string const& rccCommand,
+ std::string const& fileName,
+ std::vector<std::string>& files,
+ std::string* errorMessage = nullptr);
+};
+
+#endif
diff --git a/Source/cmQtAutoGenDigest.h b/Source/cmQtAutoGenDigest.h
new file mode 100644
index 000000000..677c39792
--- /dev/null
+++ b/Source/cmQtAutoGenDigest.h
@@ -0,0 +1,64 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+ file Copyright.txt or https://cmake.org/licensing for details. */
+#ifndef cmQtAutoGenDigest_h
+#define cmQtAutoGenDigest_h
+
+#include "cmConfigure.h" // IWYU pragma: keep
+
+#include <memory>
+#include <string>
+#include <vector>
+
+class cmGeneratorTarget;
+
+class cmQtAutoGenDigestQrc
+{
+public:
+ cmQtAutoGenDigestQrc()
+ : Generated(false)
+ , Unique(false)
+ {
+ }
+
+public:
+ std::string QrcFile;
+ std::string QrcName;
+ std::string PathChecksum;
+ std::string RccFile;
+ bool Generated;
+ bool Unique;
+ std::vector<std::string> Options;
+ std::vector<std::string> Resources;
+};
+
+/** \class cmQtAutoGenDigest
+ * \brief Filtered set of QtAutogen variables for a specific target
+ */
+class cmQtAutoGenDigest
+{
+public:
+ cmQtAutoGenDigest(cmGeneratorTarget* target)
+ : Target(target)
+ , MocEnabled(false)
+ , UicEnabled(false)
+ , RccEnabled(false)
+ {
+ }
+
+public:
+ cmGeneratorTarget* Target;
+ std::string QtVersionMajor;
+ std::string QtVersionMinor;
+ bool MocEnabled;
+ bool UicEnabled;
+ bool RccEnabled;
+ std::vector<std::string> Headers;
+ std::vector<std::string> Sources;
+ std::vector<cmQtAutoGenDigestQrc> Qrcs;
+};
+
+// Utility types
+typedef std::unique_ptr<cmQtAutoGenDigest> cmQtAutoGenDigestUP;
+typedef std::vector<cmQtAutoGenDigestUP> cmQtAutoGenDigestUPV;
+
+#endif
diff --git a/Source/cmQtAutoGeneratorCommon.cxx b/Source/cmQtAutoGeneratorCommon.cxx
deleted file mode 100644
index 3e1b58caa..000000000
--- a/Source/cmQtAutoGeneratorCommon.cxx
+++ /dev/null
@@ -1,216 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmQtAutoGeneratorCommon.h"
-#include "cmAlgorithms.h"
-#include "cmSystemTools.h"
-
-#include "cmsys/FStream.hxx"
-#include "cmsys/RegularExpression.hxx"
-
-#include <sstream>
-#include <stddef.h>
-
-// - Static functions
-
-static std::string utilStripCR(std::string const& line)
-{
- // Strip CR characters rcc may have printed (possibly more than one!).
- std::string::size_type cr = line.find('\r');
- if (cr != std::string::npos) {
- return line.substr(0, cr);
- }
- return line;
-}
-
-/// @brief Reads the resource files list from from a .qrc file - Qt4 version
-/// @return True if the .qrc file was successfully parsed
-static bool RccListInputsQt4(const std::string& fileName,
- std::vector<std::string>& files,
- std::string* errorMessage)
-{
- bool allGood = true;
- // Read qrc file content into string
- std::string qrcContents;
- {
- cmsys::ifstream ifs(fileName.c_str());
- if (ifs) {
- std::ostringstream osst;
- osst << ifs.rdbuf();
- qrcContents = osst.str();
- } else {
- if (errorMessage != CM_NULLPTR) {
- std::ostringstream ost;
- ost << "AutoRcc: Error: Rcc file not readable:\n"
- << cmQtAutoGeneratorCommon::Quoted(fileName) << "\n";
- *errorMessage = ost.str();
- }
- allGood = false;
- }
- }
- if (allGood) {
- // qrc file directory
- std::string qrcDir(cmsys::SystemTools::GetFilenamePath(fileName));
- if (!qrcDir.empty()) {
- qrcDir += '/';
- }
-
- cmsys::RegularExpression fileMatchRegex("(<file[^<]+)");
- cmsys::RegularExpression fileReplaceRegex("(^<file[^>]*>)");
-
- size_t offset = 0;
- while (fileMatchRegex.find(qrcContents.c_str() + offset)) {
- std::string qrcEntry = fileMatchRegex.match(1);
- offset += qrcEntry.size();
- {
- fileReplaceRegex.find(qrcEntry);
- std::string tag = fileReplaceRegex.match(1);
- qrcEntry = qrcEntry.substr(tag.size());
- }
- if (!cmSystemTools::FileIsFullPath(qrcEntry.c_str())) {
- qrcEntry = qrcDir + qrcEntry;
- }
- files.push_back(qrcEntry);
- }
- }
- return allGood;
-}
-
-/// @brief Reads the resource files list from from a .qrc file - Qt5 version
-/// @return True if the .qrc file was successfully parsed
-static bool RccListInputsQt5(const std::string& rccCommand,
- const std::string& fileName,
- std::vector<std::string>& files,
- std::string* errorMessage)
-{
- if (rccCommand.empty()) {
- cmSystemTools::Error("AutoRcc: Error: rcc executable not available\n");
- return false;
- }
-
- // Read rcc features
- bool hasDashDashList = false;
- {
- std::vector<std::string> command;
- command.push_back(rccCommand);
- command.push_back("--help");
- std::string rccStdOut;
- std::string rccStdErr;
- int retVal = 0;
- bool result =
- cmSystemTools::RunSingleCommand(command, &rccStdOut, &rccStdErr, &retVal,
- CM_NULLPTR, cmSystemTools::OUTPUT_NONE);
- if (result && retVal == 0 &&
- rccStdOut.find("--list") != std::string::npos) {
- hasDashDashList = true;
- }
- }
-
- // Run rcc list command
- bool result = false;
- int retVal = 0;
- std::string rccStdOut;
- std::string rccStdErr;
- {
- std::vector<std::string> command;
- command.push_back(rccCommand);
- command.push_back(hasDashDashList ? "--list" : "-list");
- command.push_back(fileName);
- result =
- cmSystemTools::RunSingleCommand(command, &rccStdOut, &rccStdErr, &retVal,
- CM_NULLPTR, cmSystemTools::OUTPUT_NONE);
- }
- if (!result || retVal) {
- if (errorMessage != CM_NULLPTR) {
- std::ostringstream ost;
- ost << "AutoRcc: Error: Rcc list process for " << fileName
- << " failed:\n"
- << rccStdOut << "\n"
- << rccStdErr << "\n";
- *errorMessage = ost.str();
- }
- return false;
- }
-
- // Parse rcc std output
- {
- std::istringstream ostr(rccStdOut);
- std::string oline;
- while (std::getline(ostr, oline)) {
- oline = utilStripCR(oline);
- if (!oline.empty()) {
- files.push_back(oline);
- }
- }
- }
- // Parse rcc error output
- {
- std::istringstream estr(rccStdErr);
- std::string eline;
- while (std::getline(estr, eline)) {
- eline = utilStripCR(eline);
- if (cmHasLiteralPrefix(eline, "RCC: Error in")) {
- static std::string searchString = "Cannot find file '";
-
- std::string::size_type pos = eline.find(searchString);
- if (pos == std::string::npos) {
- if (errorMessage != CM_NULLPTR) {
- std::ostringstream ost;
- ost << "AutoRcc: Error: Rcc lists unparsable output:\n"
- << cmQtAutoGeneratorCommon::Quoted(eline) << "\n";
- *errorMessage = ost.str();
- }
- return false;
- }
- pos += searchString.length();
- std::string::size_type sz = eline.size() - pos - 1;
- files.push_back(eline.substr(pos, sz));
- }
- }
- }
-
- return true;
-}
-
-// - Class definitions
-
-const char* cmQtAutoGeneratorCommon::listSep = "@LSEP@";
-
-std::string cmQtAutoGeneratorCommon::Quoted(const std::string& text)
-{
- static const char* rep[18] = { "\\", "\\\\", "\"", "\\\"", "\a", "\\a",
- "\b", "\\b", "\f", "\\f", "\n", "\\n",
- "\r", "\\r", "\t", "\\t", "\v", "\\v" };
-
- std::string res = text;
- for (const char* const* it = cmArrayBegin(rep); it != cmArrayEnd(rep);
- it += 2) {
- cmSystemTools::ReplaceString(res, *it, *(it + 1));
- }
- res = '"' + res;
- res += '"';
- return res;
-}
-
-bool cmQtAutoGeneratorCommon::RccListInputs(const std::string& qtMajorVersion,
- const std::string& rccCommand,
- const std::string& fileName,
- std::vector<std::string>& files,
- std::string* errorMessage)
-{
- bool allGood = false;
- if (cmsys::SystemTools::FileExists(fileName.c_str())) {
- if (qtMajorVersion == "4") {
- allGood = RccListInputsQt4(fileName, files, errorMessage);
- } else {
- allGood = RccListInputsQt5(rccCommand, fileName, files, errorMessage);
- }
- } else {
- if (errorMessage != CM_NULLPTR) {
- std::ostringstream ost;
- ost << "AutoRcc: Error: Rcc file does not exist:\n"
- << cmQtAutoGeneratorCommon::Quoted(fileName) << "\n";
- *errorMessage = ost.str();
- }
- }
- return allGood;
-}
diff --git a/Source/cmQtAutoGeneratorCommon.h b/Source/cmQtAutoGeneratorCommon.h
deleted file mode 100644
index a131baf20..000000000
--- a/Source/cmQtAutoGeneratorCommon.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#ifndef cmQtAutoGeneratorCommon_h
-#define cmQtAutoGeneratorCommon_h
-
-#include "cmConfigure.h"
-
-#include <string>
-#include <vector>
-
-class cmQtAutoGeneratorCommon
-{
- // - Types and statics
-public:
- static const char* listSep;
-
- enum GeneratorType
- {
- MOC,
- UIC,
- RCC
- };
-
-public:
- /// @brief Returns a the string escaped and enclosed in quotes
- ///
- static std::string Quoted(const std::string& text);
-
- /// @brief Reads the resource files list from from a .qrc file
- /// @arg fileName Must be the absolute path of the .qrc file
- /// @return True if the rcc file was successfully parsed
- static bool RccListInputs(const std::string& qtMajorVersion,
- const std::string& rccCommand,
- const std::string& fileName,
- std::vector<std::string>& files,
- std::string* errorMessage = CM_NULLPTR);
-};
-
-#endif
diff --git a/Source/cmQtAutoGeneratorInitializer.cxx b/Source/cmQtAutoGeneratorInitializer.cxx
index 3e3be54d1..c7550e60e 100644
--- a/Source/cmQtAutoGeneratorInitializer.cxx
+++ b/Source/cmQtAutoGeneratorInitializer.cxx
@@ -1,57 +1,76 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmQtAutoGen.h"
#include "cmQtAutoGeneratorInitializer.h"
-#include "cmQtAutoGeneratorCommon.h"
#include "cmAlgorithms.h"
+#include "cmCustomCommand.h"
#include "cmCustomCommandLines.h"
#include "cmFilePathChecksum.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalGenerator.h"
+#include "cmLinkItem.h"
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
#include "cmOutputConverter.h"
+#include "cmPolicies.h"
#include "cmSourceFile.h"
#include "cmSourceGroup.h"
#include "cmState.h"
+#include "cmStateTypes.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
#include "cm_sys_stat.h"
#include "cmake.h"
-
-#if defined(_WIN32) && !defined(__CYGWIN__)
-#include "cmGlobalVisualStudioGenerator.h"
-#endif
-
-#include "cmConfigure.h"
#include "cmsys/FStream.hxx"
+
#include <algorithm>
+#include <array>
+#include <deque>
#include <map>
#include <set>
+#include <sstream>
#include <string>
#include <utility>
#include <vector>
-static void utilCopyTargetProperty(cmTarget* destinationTarget,
- cmTarget* sourceTarget,
- const std::string& propertyName)
+inline static const char* SafeString(const char* value)
{
- const char* propertyValue = sourceTarget->GetProperty(propertyName);
- if (propertyValue) {
- destinationTarget->SetProperty(propertyName, propertyValue);
- }
+ return (value != nullptr) ? value : "";
}
-inline static bool PropertyEnabled(cmSourceFile* sourceFile, const char* key)
+inline static std::string GetSafeProperty(cmGeneratorTarget const* target,
+ const char* key)
{
- return cmSystemTools::IsOn(sourceFile->GetPropertyForUser(key));
+ return std::string(SafeString(target->GetProperty(key)));
}
-static std::string GetSafeProperty(cmGeneratorTarget const* target,
- const char* key)
+inline static std::string GetSafeProperty(cmSourceFile const* sf,
+ const char* key)
{
- const char* tmp = target->GetProperty(key);
- return std::string((tmp != CM_NULLPTR) ? tmp : "");
+ return std::string(SafeString(sf->GetProperty(key)));
+}
+
+static cmQtAutoGen::MultiConfig AutogenMultiConfig(
+ cmGlobalGenerator* globalGen)
+{
+ if (!globalGen->IsMultiConfig()) {
+ return cmQtAutoGen::SINGLE;
+ }
+
+ // FIXME: Xcode does not support per-config sources, yet.
+ // (EXCLUDED_SOURCE_FILE_NAMES)
+ // if (globalGen->GetName().find("Xcode") != std::string::npos) {
+ // return cmQtAutoGen::FULL;
+ //}
+
+ // FIXME: Visual Studio does not support per-config sources, yet.
+ // (EXCLUDED_SOURCE_FILE_NAMES)
+ // if (globalGen->GetName().find("Visual Studio") != std::string::npos) {
+ // return cmQtAutoGen::FULL;
+ //}
+
+ return cmQtAutoGen::WRAP;
}
static std::string GetAutogenTargetName(cmGeneratorTarget const* target)
@@ -84,43 +103,44 @@ static std::string GetAutogenTargetBuildDir(cmGeneratorTarget const* target)
return targetDir;
}
-static std::string GetQtMajorVersion(cmGeneratorTarget const* target)
+std::string cmQtAutoGeneratorInitializer::GetQtMajorVersion(
+ cmGeneratorTarget const* target)
{
cmMakefile* makefile = target->Target->GetMakefile();
- std::string qtMajorVersion = makefile->GetSafeDefinition("QT_VERSION_MAJOR");
- if (qtMajorVersion.empty()) {
- qtMajorVersion = makefile->GetSafeDefinition("Qt5Core_VERSION_MAJOR");
+ std::string qtMajor = makefile->GetSafeDefinition("QT_VERSION_MAJOR");
+ if (qtMajor.empty()) {
+ qtMajor = makefile->GetSafeDefinition("Qt5Core_VERSION_MAJOR");
}
const char* targetQtVersion =
target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION", "");
- if (targetQtVersion != CM_NULLPTR) {
- qtMajorVersion = targetQtVersion;
+ if (targetQtVersion != nullptr) {
+ qtMajor = targetQtVersion;
}
- return qtMajorVersion;
+ return qtMajor;
}
-static std::string GetQtMinorVersion(cmGeneratorTarget const* target,
- const std::string& qtMajorVersion)
+std::string cmQtAutoGeneratorInitializer::GetQtMinorVersion(
+ cmGeneratorTarget const* target, std::string const& qtVersionMajor)
{
cmMakefile* makefile = target->Target->GetMakefile();
- std::string qtMinorVersion;
- if (qtMajorVersion == "5") {
- qtMinorVersion = makefile->GetSafeDefinition("Qt5Core_VERSION_MINOR");
+ std::string qtMinor;
+ if (qtVersionMajor == "5") {
+ qtMinor = makefile->GetSafeDefinition("Qt5Core_VERSION_MINOR");
}
- if (qtMinorVersion.empty()) {
- qtMinorVersion = makefile->GetSafeDefinition("QT_VERSION_MINOR");
+ if (qtMinor.empty()) {
+ qtMinor = makefile->GetSafeDefinition("QT_VERSION_MINOR");
}
const char* targetQtVersion =
target->GetLinkInterfaceDependentStringProperty("QT_MINOR_VERSION", "");
- if (targetQtVersion != CM_NULLPTR) {
- qtMinorVersion = targetQtVersion;
+ if (targetQtVersion != nullptr) {
+ qtMinor = targetQtVersion;
}
- return qtMinorVersion;
+ return qtMinor;
}
-static bool QtVersionGreaterOrEqual(const std::string& major,
- const std::string& minor,
+static bool QtVersionGreaterOrEqual(std::string const& major,
+ std::string const& minor,
unsigned long requestMajor,
unsigned long requestMinor)
{
@@ -134,76 +154,17 @@ static bool QtVersionGreaterOrEqual(const std::string& major,
return false;
}
-static void GetCompileDefinitionsAndDirectories(
- cmGeneratorTarget const* target, const std::string& config,
- std::string& incs, std::string& defs)
-{
- cmLocalGenerator* localGen = target->GetLocalGenerator();
- {
- std::vector<std::string> includeDirs;
- // Get the include dirs for this target, without stripping the implicit
- // include dirs off, see
- // https://gitlab.kitware.com/cmake/cmake/issues/13667
- localGen->GetIncludeDirectories(includeDirs, target, "CXX", config, false);
- incs = cmJoin(includeDirs, ";");
- }
- {
- std::set<std::string> defines;
- localGen->AddCompileDefinitions(defines, target, config, "CXX");
- defs += cmJoin(defines, ";");
- }
-}
-
-static bool IsMultiConfig(cmGlobalGenerator* globalGen)
-{
- // FIXME: Xcode does not support per-config sources, yet.
- // (EXCLUDED_SOURCE_FILE_NAMES)
- // Treat it as a single configuration generator meanwhile.
- if (globalGen->GetName().find("Xcode") != std::string::npos) {
- return false;
- }
- // FIXME: Visual Studio does not fully support per-config sources yet.
- if (globalGen->GetName().find("Visual Studio") != std::string::npos) {
- return false;
- }
- return globalGen->IsMultiConfig();
-}
-
-static std::vector<std::string> GetConfigurations(
- cmMakefile* makefile, std::string* config = CM_NULLPTR)
-{
- std::vector<std::string> configs;
- {
- std::string cfg = makefile->GetConfigurations(configs);
- if (config != CM_NULLPTR) {
- *config = cfg;
- }
- }
- // Add empty configuration on demand
- if (configs.empty()) {
- configs.push_back("");
- }
- return configs;
-}
-
-static std::vector<std::string> GetConfigurationSuffixes(cmMakefile* makefile)
+static void GetConfigs(cmMakefile* makefile, std::string& configDefault,
+ std::vector<std::string>& configsList)
{
- std::vector<std::string> suffixes;
- if (IsMultiConfig(makefile->GetGlobalGenerator())) {
- makefile->GetConfigurations(suffixes);
- for (std::vector<std::string>::iterator it = suffixes.begin();
- it != suffixes.end(); ++it) {
- it->insert(0, "_");
- }
+ configDefault = makefile->GetConfigurations(configsList);
+ if (configsList.empty()) {
+ configsList.push_back(configDefault);
}
- if (suffixes.empty()) {
- suffixes.push_back("");
- }
- return suffixes;
}
static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
- const std::string& value)
+ std::string const& value)
{
makefile->AddDefinition(key,
cmOutputConverter::EscapeForCMake(value).c_str());
@@ -216,290 +177,389 @@ static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
key, cmOutputConverter::EscapeForCMake(cmJoin(values, ";")).c_str());
}
-static bool AddToSourceGroup(cmMakefile* makefile, const std::string& fileName,
- cmQtAutoGeneratorCommon::GeneratorType genType)
+static void AddDefinitionEscaped(cmMakefile* makefile, const char* key,
+ const std::set<std::string>& values)
{
- cmSourceGroup* sourceGroup = CM_NULLPTR;
+ makefile->AddDefinition(
+ key, cmOutputConverter::EscapeForCMake(cmJoin(values, ";")).c_str());
+}
+
+static void AddDefinitionEscaped(
+ cmMakefile* makefile, const char* key,
+ const std::vector<std::vector<std::string>>& lists)
+{
+ std::vector<std::string> seplist;
+ for (const std::vector<std::string>& list : lists) {
+ std::string blist = "{";
+ blist += cmJoin(list, ";");
+ blist += "}";
+ seplist.push_back(std::move(blist));
+ }
+ makefile->AddDefinition(key, cmOutputConverter::EscapeForCMake(
+ cmJoin(seplist, cmQtAutoGen::listSep))
+ .c_str());
+}
+
+static bool AddToSourceGroup(cmMakefile* makefile, std::string const& fileName,
+ cmQtAutoGen::Generator genType)
+{
+ cmSourceGroup* sourceGroup = nullptr;
// Acquire source group
{
- const char* groupName = CM_NULLPTR;
- // Use generator specific group name
- switch (genType) {
- case cmQtAutoGeneratorCommon::MOC:
- groupName =
- makefile->GetState()->GetGlobalProperty("AUTOMOC_SOURCE_GROUP");
- break;
- case cmQtAutoGeneratorCommon::RCC:
- groupName =
- makefile->GetState()->GetGlobalProperty("AUTORCC_SOURCE_GROUP");
- break;
- default:
- break;
- }
- // Use default group name on demand
- if ((groupName == CM_NULLPTR) || (*groupName == 0)) {
- groupName =
- makefile->GetState()->GetGlobalProperty("AUTOGEN_SOURCE_GROUP");
- }
- // Generate a source group on demand
- if ((groupName != CM_NULLPTR) && (*groupName != 0)) {
- {
- const char* delimiter =
- makefile->GetDefinition("SOURCE_GROUP_DELIMITER");
- if (delimiter == CM_NULLPTR) {
- delimiter = "\\";
- }
- std::vector<std::string> folders =
- cmSystemTools::tokenize(groupName, delimiter);
- sourceGroup = makefile->GetSourceGroup(folders);
- if (sourceGroup == CM_NULLPTR) {
- makefile->AddSourceGroup(folders);
- sourceGroup = makefile->GetSourceGroup(folders);
+ std::string property;
+ std::string groupName;
+ {
+ std::array<std::string, 2> props;
+ // Use generator specific group name
+ switch (genType) {
+ case cmQtAutoGen::MOC:
+ props[0] = "AUTOMOC_SOURCE_GROUP";
+ break;
+ case cmQtAutoGen::RCC:
+ props[0] = "AUTORCC_SOURCE_GROUP";
+ break;
+ default:
+ props[0] = "AUTOGEN_SOURCE_GROUP";
+ break;
+ }
+ props[1] = "AUTOGEN_SOURCE_GROUP";
+ for (std::string& prop : props) {
+ const char* propName = makefile->GetState()->GetGlobalProperty(prop);
+ if ((propName != nullptr) && (*propName != '\0')) {
+ groupName = propName;
+ property = std::move(prop);
+ break;
}
}
- if (sourceGroup == CM_NULLPTR) {
- cmSystemTools::Error(
- "Autogen: Could not create or find source group: ",
- cmQtAutoGeneratorCommon::Quoted(groupName).c_str());
+ }
+ // Generate a source group on demand
+ if (!groupName.empty()) {
+ sourceGroup = makefile->GetOrCreateSourceGroup(groupName);
+ if (sourceGroup == nullptr) {
+ std::ostringstream ost;
+ ost << cmQtAutoGen::GeneratorNameUpper(genType);
+ ost << ": " << property;
+ ost << ": Could not find or create the source group ";
+ ost << cmQtAutoGen::Quoted(groupName);
+ cmSystemTools::Error(ost.str().c_str());
return false;
}
}
}
- if (sourceGroup != CM_NULLPTR) {
+ if (sourceGroup != nullptr) {
sourceGroup->AddGroupFile(fileName);
}
return true;
}
-static void AddGeneratedSource(cmMakefile* makefile,
- const std::string& filename,
- cmQtAutoGeneratorCommon::GeneratorType genType)
+static void AddCleanFile(cmMakefile* makefile, std::string const& fileName)
{
- cmSourceFile* gFile = makefile->GetOrCreateSource(filename, true);
- gFile->SetProperty("GENERATED", "1");
- gFile->SetProperty("SKIP_AUTOGEN", "On");
-
- AddToSourceGroup(makefile, filename, genType);
+ makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES", fileName.c_str(),
+ false);
}
-static void AcquireScanFiles(cmGeneratorTarget const* target,
- std::vector<std::string>& mocUicSources,
- std::vector<std::string>& mocUicHeaders,
- std::vector<std::string>& mocSkipList,
- std::vector<std::string>& uicSkipList)
+static std::vector<std::string> AddGeneratedSource(
+ cmGeneratorTarget* target, std::string const& filename,
+ cmQtAutoGen::MultiConfig multiConfig,
+ const std::vector<std::string>& configsList, cmQtAutoGen::Generator genType)
{
- const bool mocTarget = target->GetPropertyAsBool("AUTOMOC");
- const bool uicTarget = target->GetPropertyAsBool("AUTOUIC");
-
- std::vector<cmSourceFile*> srcFiles;
- target->GetConfigCommonSourceFiles(srcFiles);
- for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin();
- fileIt != srcFiles.end(); ++fileIt) {
- cmSourceFile* sf = *fileIt;
- const cmSystemTools::FileFormat fileType =
- cmSystemTools::GetFileFormat(sf->GetExtension().c_str());
-
- if (!(fileType == cmSystemTools::CXX_FILE_FORMAT) &&
- !(fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
- continue;
+ std::vector<std::string> genFiles;
+ // Register source file in makefile and source group
+ if (multiConfig != cmQtAutoGen::FULL) {
+ genFiles.push_back(filename);
+ } else {
+ for (std::string const& cfg : configsList) {
+ genFiles.push_back(
+ cmQtAutoGen::AppendFilenameSuffix(filename, "_" + cfg));
}
- if (PropertyEnabled(sf, "GENERATED") &&
- !target->GetPropertyAsBool("__UNDOCUMENTED_AUTOGEN_GENERATED_FILES")) {
- // FIXME: Add a policy whose NEW behavior allows generated files.
- // The implementation already works. We disable it here to avoid
- // changing behavior for existing projects that do not expect it.
- continue;
+ }
+ {
+ cmMakefile* makefile = target->Target->GetMakefile();
+ for (std::string const& genFile : genFiles) {
+ {
+ cmSourceFile* gFile = makefile->GetOrCreateSource(genFile, true);
+ gFile->SetProperty("GENERATED", "1");
+ gFile->SetProperty("SKIP_AUTOGEN", "On");
+ }
+ AddToSourceGroup(makefile, genFile, genType);
}
- const std::string absFile =
- cmsys::SystemTools::GetRealPath(sf->GetFullPath());
- // Skip flags
- const bool skipAll = PropertyEnabled(sf, "SKIP_AUTOGEN");
- const bool mocSkip = skipAll || PropertyEnabled(sf, "SKIP_AUTOMOC");
- const bool uicSkip = skipAll || PropertyEnabled(sf, "SKIP_AUTOUIC");
- // Add file name to skip lists.
- // Do this even when the file is not added to the sources/headers lists
- // because the file name may be extracted from an other file when
- // processing
- if (mocSkip) {
- mocSkipList.push_back(absFile);
+ }
+
+ // Add source file to target
+ if (multiConfig != cmQtAutoGen::FULL) {
+ target->AddSource(filename);
+ } else {
+ for (std::string const& cfg : configsList) {
+ std::string src = "$<$<CONFIG:";
+ src += cfg;
+ src += ">:";
+ src += cmQtAutoGen::AppendFilenameSuffix(filename, "_" + cfg);
+ src += ">";
+ target->AddSource(src);
}
- if (uicSkip) {
- uicSkipList.push_back(absFile);
+ }
+
+ return genFiles;
+}
+
+/* @brief Tests if targetDepend is a STATIC_LIBRARY and if any of its
+ * recursive STATIC_LIBRARY dependencies depends on targetOrigin
+ * (STATIC_LIBRARY cycle).
+ */
+static bool StaticLibraryCycle(cmGeneratorTarget const* targetOrigin,
+ cmGeneratorTarget const* targetDepend,
+ std::string const& config)
+{
+ bool cycle = false;
+ if ((targetOrigin->GetType() == cmStateEnums::STATIC_LIBRARY) &&
+ (targetDepend->GetType() == cmStateEnums::STATIC_LIBRARY)) {
+ std::set<cmGeneratorTarget const*> knownLibs;
+ std::deque<cmGeneratorTarget const*> testLibs;
+
+ // Insert initial static_library dependency
+ knownLibs.insert(targetDepend);
+ testLibs.push_back(targetDepend);
+
+ while (!testLibs.empty()) {
+ cmGeneratorTarget const* testTarget = testLibs.front();
+ testLibs.pop_front();
+ // Check if the test target is the origin target (cycle)
+ if (testTarget == targetOrigin) {
+ cycle = true;
+ break;
+ }
+ // Collect all static_library dependencies from the test target
+ cmLinkImplementationLibraries const* libs =
+ testTarget->GetLinkImplementationLibraries(config);
+ if (libs != nullptr) {
+ for (cmLinkItem const& item : libs->Libraries) {
+ cmGeneratorTarget const* depTarget = item.Target;
+ if ((depTarget != nullptr) &&
+ (depTarget->GetType() == cmStateEnums::STATIC_LIBRARY) &&
+ knownLibs.insert(depTarget).second) {
+ testLibs.push_back(depTarget);
+ }
+ }
+ }
}
+ }
+ return cycle;
+}
- if ((mocTarget && !mocSkip) || (uicTarget && !uicSkip)) {
- // Add file name to sources or headers list
- switch (fileType) {
- case cmSystemTools::CXX_FILE_FORMAT:
- mocUicSources.push_back(absFile);
- break;
- case cmSystemTools::HEADER_FILE_FORMAT:
- mocUicHeaders.push_back(absFile);
- break;
- default:
- break;
+struct cmQtAutoGenSetup
+{
+ std::set<std::string> MocSkip;
+ std::set<std::string> UicSkip;
+
+ std::map<std::string, std::string> ConfigMocIncludes;
+ std::map<std::string, std::string> ConfigMocDefines;
+ std::map<std::string, std::string> ConfigUicOptions;
+};
+
+static void SetupAcquireSkipFiles(cmQtAutoGenDigest const& digest,
+ cmQtAutoGenSetup& setup)
+{
+ // Read skip files from makefile sources
+ {
+ const std::vector<cmSourceFile*>& allSources =
+ digest.Target->Makefile->GetSourceFiles();
+ for (cmSourceFile* sf : allSources) {
+ // sf->GetExtension() is only valid after sf->GetFullPath() ...
+ std::string const& fPath = sf->GetFullPath();
+ cmSystemTools::FileFormat const fileType =
+ cmSystemTools::GetFileFormat(sf->GetExtension().c_str());
+ if (!(fileType == cmSystemTools::CXX_FILE_FORMAT) &&
+ !(fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
+ continue;
+ }
+ const bool skipAll = sf->GetPropertyAsBool("SKIP_AUTOGEN");
+ const bool mocSkip = digest.MocEnabled &&
+ (skipAll || sf->GetPropertyAsBool("SKIP_AUTOMOC"));
+ const bool uicSkip = digest.UicEnabled &&
+ (skipAll || sf->GetPropertyAsBool("SKIP_AUTOUIC"));
+ if (mocSkip || uicSkip) {
+ std::string const absFile = cmSystemTools::GetRealPath(fPath);
+ if (mocSkip) {
+ setup.MocSkip.insert(absFile);
+ }
+ if (uicSkip) {
+ setup.UicSkip.insert(absFile);
+ }
}
}
}
}
-static void MocSetupAutoTarget(
- cmGeneratorTarget const* target, const std::string& autogenTargetName,
- std::string const& qtMajorVersion, std::string const& config,
- std::vector<std::string> const& configs,
- std::vector<std::string> const& mocSkipList,
- std::map<std::string, std::string>& configMocIncludes,
- std::map<std::string, std::string>& configMocDefines)
+static void SetupAutoTargetMoc(cmQtAutoGenDigest const& digest,
+ std::string const& configDefault,
+ std::vector<std::string> const& configsList,
+ cmQtAutoGenSetup& setup)
{
- cmLocalGenerator* lg = target->GetLocalGenerator();
+ cmGeneratorTarget const* target = digest.Target;
+ cmLocalGenerator* localGen = target->GetLocalGenerator();
cmMakefile* makefile = target->Target->GetMakefile();
+ AddDefinitionEscaped(makefile, "_moc_skip", setup.MocSkip);
AddDefinitionEscaped(makefile, "_moc_options",
GetSafeProperty(target, "AUTOMOC_MOC_OPTIONS"));
- AddDefinitionEscaped(makefile, "_moc_skip", mocSkipList);
AddDefinitionEscaped(makefile, "_moc_relaxed_mode",
makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE") ? "TRUE"
: "FALSE");
+ AddDefinitionEscaped(makefile, "_moc_macro_names",
+ GetSafeProperty(target, "AUTOMOC_MACRO_NAMES"));
AddDefinitionEscaped(makefile, "_moc_depend_filters",
GetSafeProperty(target, "AUTOMOC_DEPEND_FILTERS"));
- if (QtVersionGreaterOrEqual(
- qtMajorVersion, GetQtMinorVersion(target, qtMajorVersion), 5, 8)) {
- AddDefinitionEscaped(
- makefile, "_moc_predefs_cmd",
- makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND"));
+ // Compiler predefines
+ if (target->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES")) {
+ if (QtVersionGreaterOrEqual(digest.QtVersionMajor, digest.QtVersionMinor,
+ 5, 8)) {
+ AddDefinitionEscaped(
+ makefile, "_moc_predefs_cmd",
+ makefile->GetSafeDefinition("CMAKE_CXX_COMPILER_PREDEFINES_COMMAND"));
+ }
}
// Moc includes and compile definitions
{
- // Default settings
- std::string incs;
- std::string compileDefs;
- GetCompileDefinitionsAndDirectories(target, config, incs, compileDefs);
- AddDefinitionEscaped(makefile, "_moc_incs", incs);
- AddDefinitionEscaped(makefile, "_moc_compile_defs", compileDefs);
-
- // Configuration specific settings
- for (std::vector<std::string>::const_iterator li = configs.begin();
- li != configs.end(); ++li) {
- std::string configIncs;
- std::string configCompileDefs;
- GetCompileDefinitionsAndDirectories(target, *li, configIncs,
- configCompileDefs);
- if (configIncs != incs) {
- configMocIncludes[*li] = cmOutputConverter::EscapeForCMake(configIncs);
+ auto GetIncludeDirs = [target,
+ localGen](std::string const& cfg) -> std::string {
+ // Get the include dirs for this target, without stripping the implicit
+ // include dirs off, see
+ // https://gitlab.kitware.com/cmake/cmake/issues/13667
+ std::vector<std::string> includeDirs;
+ localGen->GetIncludeDirectories(includeDirs, target, "CXX", cfg, false);
+ return cmJoin(includeDirs, ";");
+ };
+ auto GetCompileDefinitions =
+ [target, localGen](std::string const& cfg) -> std::string {
+ std::set<std::string> defines;
+ localGen->AddCompileDefinitions(defines, target, cfg, "CXX");
+ return cmJoin(defines, ";");
+ };
+
+ // Default configuration settings
+ std::string const includeDirs = GetIncludeDirs(configDefault);
+ std::string const compileDefs = GetCompileDefinitions(configDefault);
+ // Other configuration settings
+ for (std::string const& cfg : configsList) {
+ {
+ std::string const configIncludeDirs = GetIncludeDirs(cfg);
+ if (configIncludeDirs != includeDirs) {
+ setup.ConfigMocIncludes[cfg] = configIncludeDirs;
+ }
}
- if (configCompileDefs != compileDefs) {
- configMocDefines[*li] =
- cmOutputConverter::EscapeForCMake(configCompileDefs);
+ {
+ std::string const configCompileDefs = GetCompileDefinitions(cfg);
+ if (configCompileDefs != compileDefs) {
+ setup.ConfigMocDefines[cfg] = configCompileDefs;
+ }
}
}
+ AddDefinitionEscaped(makefile, "_moc_include_dirs", includeDirs);
+ AddDefinitionEscaped(makefile, "_moc_compile_defs", compileDefs);
}
// Moc executable
{
+ std::string mocExec;
std::string err;
- const char* mocExec = CM_NULLPTR;
- if (qtMajorVersion == "5") {
- cmGeneratorTarget* qt5Moc = lg->FindGeneratorTargetToUse("Qt5::moc");
- if (qt5Moc != CM_NULLPTR) {
- mocExec = qt5Moc->ImportedGetLocation("");
+
+ if (digest.QtVersionMajor == "5") {
+ cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt5::moc");
+ if (tgt != nullptr) {
+ mocExec = SafeString(tgt->ImportedGetLocation(""));
} else {
- err = "Qt5::moc target not found " + autogenTargetName;
+ err = "AUTOMOC: Qt5::moc target not found";
}
- } else if (qtMajorVersion == "4") {
- cmGeneratorTarget* qt4Moc = lg->FindGeneratorTargetToUse("Qt4::moc");
- if (qt4Moc != CM_NULLPTR) {
- mocExec = qt4Moc->ImportedGetLocation("");
+ } else if (digest.QtVersionMajor == "4") {
+ cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt4::moc");
+ if (tgt != nullptr) {
+ mocExec = SafeString(tgt->ImportedGetLocation(""));
} else {
- err = "Qt4::moc target not found " + autogenTargetName;
+ err = "AUTOMOC: Qt4::moc target not found";
}
} else {
- err = "The CMAKE_AUTOMOC feature supports only Qt 4 and Qt 5 ";
- err += autogenTargetName;
+ err = "The AUTOMOC feature supports only Qt 4 and Qt 5";
}
- // Add definition or error
+
if (err.empty()) {
- AddDefinitionEscaped(makefile, "_qt_moc_executable",
- mocExec ? mocExec : "");
+ AddDefinitionEscaped(makefile, "_qt_moc_executable", mocExec);
} else {
+ err += " (" + target->GetName() + ")";
cmSystemTools::Error(err.c_str());
}
}
}
-static void UicGetOpts(cmGeneratorTarget const* target,
- const std::string& config, std::string& optString)
+static void SetupAutoTargetUic(cmQtAutoGenDigest const& digest,
+ std::string const& config,
+ std::vector<std::string> const& configs,
+ cmQtAutoGenSetup& setup)
{
- std::vector<std::string> opts;
- target->GetAutoUicOptions(opts, config);
- optString = cmJoin(opts, ";");
-}
-
-static void UicSetupAutoTarget(
- cmGeneratorTarget const* target, std::string const& qtMajorVersion,
- std::string const& config, std::vector<std::string> const& configs,
- std::vector<std::string> const& uicSkipList,
- std::map<std::string, std::string>& configUicOptions)
-{
- cmLocalGenerator* lg = target->GetLocalGenerator();
+ cmGeneratorTarget const* target = digest.Target;
cmMakefile* makefile = target->Target->GetMakefile();
- AddDefinitionEscaped(makefile, "_uic_skip", uicSkipList);
-
// Uic search paths
{
std::vector<std::string> uicSearchPaths;
- cmSystemTools::ExpandListArgument(
- GetSafeProperty(target, "AUTOUIC_SEARCH_PATHS"), uicSearchPaths);
- const std::string srcDir = makefile->GetCurrentSourceDirectory();
- for (std::vector<std::string>::iterator it = uicSearchPaths.begin();
- it != uicSearchPaths.end(); ++it) {
- *it = cmSystemTools::CollapseFullPath(*it, srcDir);
+ {
+ std::string const usp = GetSafeProperty(target, "AUTOUIC_SEARCH_PATHS");
+ if (!usp.empty()) {
+ cmSystemTools::ExpandListArgument(usp, uicSearchPaths);
+ std::string const srcDir = makefile->GetCurrentSourceDirectory();
+ for (std::string& path : uicSearchPaths) {
+ path = cmSystemTools::CollapseFullPath(path, srcDir);
+ }
+ }
}
AddDefinitionEscaped(makefile, "_uic_search_paths", uicSearchPaths);
}
// Uic target options
{
+ auto UicGetOpts = [target](std::string const& cfg) -> std::string {
+ std::vector<std::string> opts;
+ target->GetAutoUicOptions(opts, cfg);
+ return cmJoin(opts, ";");
+ };
+
// Default settings
- std::string uicOpts;
- UicGetOpts(target, config, uicOpts);
+ std::string const uicOpts = UicGetOpts(config);
AddDefinitionEscaped(makefile, "_uic_target_options", uicOpts);
// Configuration specific settings
- for (std::vector<std::string>::const_iterator li = configs.begin();
- li != configs.end(); ++li) {
- std::string configUicOpts;
- UicGetOpts(target, *li, configUicOpts);
+ for (std::string const& cfg : configs) {
+ std::string const configUicOpts = UicGetOpts(cfg);
if (configUicOpts != uicOpts) {
- configUicOptions[*li] =
- cmOutputConverter::EscapeForCMake(configUicOpts);
+ setup.ConfigUicOptions[cfg] = configUicOpts;
}
}
}
- // Uic files options
+ // .ui files skip and options
{
std::vector<std::string> uiFileFiles;
- std::vector<std::string> uiFileOptions;
+ std::vector<std::vector<std::string>> uiFileOptions;
{
- std::set<std::string> skipped;
- skipped.insert(uicSkipList.begin(), uicSkipList.end());
-
- const std::vector<cmSourceFile*> uiFilesWithOptions =
- makefile->GetQtUiFilesWithOptions();
- for (std::vector<cmSourceFile*>::const_iterator fileIt =
- uiFilesWithOptions.begin();
- fileIt != uiFilesWithOptions.end(); ++fileIt) {
- cmSourceFile* sf = *fileIt;
- const std::string absFile =
- cmsys::SystemTools::GetRealPath(sf->GetFullPath());
- if (skipped.insert(absFile).second) {
- // The file wasn't skipped
- uiFileFiles.push_back(absFile);
- {
- std::string opts = sf->GetProperty("AUTOUIC_OPTIONS");
- cmSystemTools::ReplaceString(opts, ";",
- cmQtAutoGeneratorCommon::listSep);
- uiFileOptions.push_back(opts);
+ std::string const uiExt = "ui";
+ for (cmSourceFile* sf : makefile->GetSourceFiles()) {
+ // sf->GetExtension() is only valid after sf->GetFullPath() ...
+ std::string const& fPath = sf->GetFullPath();
+ if (sf->GetExtension() == uiExt) {
+ std::string const absFile = cmSystemTools::GetRealPath(fPath);
+ // Check if the file should be skipped
+ if (sf->GetPropertyAsBool("SKIP_AUTOUIC") ||
+ sf->GetPropertyAsBool("SKIP_AUTOGEN")) {
+ setup.UicSkip.insert(absFile);
+ }
+ // Check if the files has uic options
+ std::string const uicOpts = GetSafeProperty(sf, "AUTOUIC_OPTIONS");
+ if (!uicOpts.empty()) {
+ // Check if file isn't skipped
+ if (setup.UicSkip.count(absFile) == 0) {
+ uiFileFiles.push_back(absFile);
+ std::vector<std::string> optsVec;
+ cmSystemTools::ExpandListArgument(uicOpts, optsVec);
+ uiFileOptions.push_back(std::move(optsVec));
+ }
}
}
}
@@ -508,233 +568,134 @@ static void UicSetupAutoTarget(
AddDefinitionEscaped(makefile, "_qt_uic_options_options", uiFileOptions);
}
+ AddDefinitionEscaped(makefile, "_uic_skip", setup.UicSkip);
+
// Uic executable
{
std::string err;
- const char* uicExec = CM_NULLPTR;
- if (qtMajorVersion == "5") {
- cmGeneratorTarget* qt5Uic = lg->FindGeneratorTargetToUse("Qt5::uic");
- if (qt5Uic != CM_NULLPTR) {
- uicExec = qt5Uic->ImportedGetLocation("");
+ std::string uicExec;
+
+ cmLocalGenerator* localGen = target->GetLocalGenerator();
+ if (digest.QtVersionMajor == "5") {
+ cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt5::uic");
+ if (tgt != nullptr) {
+ uicExec = SafeString(tgt->ImportedGetLocation(""));
} else {
// Project does not use Qt5Widgets, but has AUTOUIC ON anyway
}
- } else if (qtMajorVersion == "4") {
- cmGeneratorTarget* qt4Uic = lg->FindGeneratorTargetToUse("Qt4::uic");
- if (qt4Uic != CM_NULLPTR) {
- uicExec = qt4Uic->ImportedGetLocation("");
+ } else if (digest.QtVersionMajor == "4") {
+ cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt4::uic");
+ if (tgt != nullptr) {
+ uicExec = SafeString(tgt->ImportedGetLocation(""));
} else {
- err = "Qt4::uic target not found " + target->GetName();
+ err = "AUTOUIC: Qt4::uic target not found";
}
} else {
- err = "The CMAKE_AUTOUIC feature supports only Qt 4 and Qt 5 ";
- err += target->GetName();
+ err = "The AUTOUIC feature supports only Qt 4 and Qt 5";
}
- // Add definition or error
+
if (err.empty()) {
- AddDefinitionEscaped(makefile, "_qt_uic_executable",
- uicExec ? uicExec : "");
+ AddDefinitionEscaped(makefile, "_qt_uic_executable", uicExec);
} else {
+ err += " (" + target->GetName() + ")";
cmSystemTools::Error(err.c_str());
}
}
}
static std::string RccGetExecutable(cmGeneratorTarget const* target,
- const std::string& qtMajorVersion)
+ std::string const& qtMajorVersion)
{
std::string rccExec;
- cmLocalGenerator* lg = target->GetLocalGenerator();
+ std::string err;
+
+ cmLocalGenerator* localGen = target->GetLocalGenerator();
if (qtMajorVersion == "5") {
- cmGeneratorTarget* qt5Rcc = lg->FindGeneratorTargetToUse("Qt5::rcc");
- if (qt5Rcc != CM_NULLPTR) {
- rccExec = qt5Rcc->ImportedGetLocation("");
+ cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt5::rcc");
+ if (tgt != nullptr) {
+ rccExec = SafeString(tgt->ImportedGetLocation(""));
} else {
- cmSystemTools::Error("Qt5::rcc target not found ",
- target->GetName().c_str());
+ err = "AUTORCC: Qt5::rcc target not found";
}
} else if (qtMajorVersion == "4") {
- cmGeneratorTarget* qt4Rcc = lg->FindGeneratorTargetToUse("Qt4::rcc");
- if (qt4Rcc != CM_NULLPTR) {
- rccExec = qt4Rcc->ImportedGetLocation("");
+ cmGeneratorTarget* tgt = localGen->FindGeneratorTargetToUse("Qt4::rcc");
+ if (tgt != nullptr) {
+ rccExec = SafeString(tgt->ImportedGetLocation(""));
} else {
- cmSystemTools::Error("Qt4::rcc target not found ",
- target->GetName().c_str());
+ err = "AUTORCC: Qt4::rcc target not found";
}
} else {
- cmSystemTools::Error(
- "The CMAKE_AUTORCC feature supports only Qt 4 and Qt 5 ",
- target->GetName().c_str());
+ err = "The AUTORCC feature supports only Qt 4 and Qt 5";
}
- return rccExec;
-}
-static void RccMergeOptions(std::vector<std::string>& opts,
- const std::vector<std::string>& fileOpts,
- bool isQt5)
-{
- static const char* valueOptions[] = { "name", "root", "compress",
- "threshold" };
- std::vector<std::string> extraOpts;
- for (std::vector<std::string>::const_iterator fit = fileOpts.begin();
- fit != fileOpts.end(); ++fit) {
- std::vector<std::string>::iterator existingIt =
- std::find(opts.begin(), opts.end(), *fit);
- if (existingIt != opts.end()) {
- const char* optName = fit->c_str();
- if (*optName == '-') {
- ++optName;
- if (isQt5 && *optName == '-') {
- ++optName;
- }
- }
- // Test if this is a value option and change the existing value
- if ((optName != fit->c_str()) &&
- std::find_if(cmArrayBegin(valueOptions), cmArrayEnd(valueOptions),
- cmStrCmp(optName)) != cmArrayEnd(valueOptions)) {
- const std::vector<std::string>::iterator existValueIt(existingIt + 1);
- const std::vector<std::string>::const_iterator fileValueIt(fit + 1);
- if ((existValueIt != opts.end()) && (fileValueIt != fileOpts.end())) {
- *existValueIt = *fileValueIt;
- ++fit;
- }
- }
- } else {
- extraOpts.push_back(*fit);
- }
+ if (!err.empty()) {
+ err += " (" + target->GetName() + ")";
+ cmSystemTools::Error(err.c_str());
}
- opts.insert(opts.end(), extraOpts.begin(), extraOpts.end());
+ return rccExec;
}
-static void RccSetupAutoTarget(cmGeneratorTarget const* target,
- const std::string& qtMajorVersion)
+static void SetupAutoTargetRcc(cmQtAutoGenDigest const& digest)
{
- cmMakefile* makefile = target->Target->GetMakefile();
- const bool qtMajorVersion5 = (qtMajorVersion == "5");
- const std::string rccCommand = RccGetExecutable(target, qtMajorVersion);
- std::vector<std::string> _rcc_files;
- std::vector<std::string> _rcc_inputs;
- std::vector<std::string> rccFileFiles;
- std::vector<std::string> rccFileOptions;
- std::vector<std::string> rccOptionsTarget;
- if (const char* opts = target->GetProperty("AUTORCC_OPTIONS")) {
- cmSystemTools::ExpandListArgument(opts, rccOptionsTarget);
+ std::vector<std::string> rccFiles;
+ std::vector<std::string> rccBuilds;
+ std::vector<std::vector<std::string>> rccOptions;
+ std::vector<std::vector<std::string>> rccInputs;
+
+ for (cmQtAutoGenDigestQrc const& qrcDigest : digest.Qrcs) {
+ rccFiles.push_back(qrcDigest.QrcFile);
+ rccBuilds.push_back(qrcDigest.RccFile);
+ rccOptions.push_back(qrcDigest.Options);
+ rccInputs.push_back(qrcDigest.Resources);
}
- std::vector<cmSourceFile*> srcFiles;
- target->GetConfigCommonSourceFiles(srcFiles);
- for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin();
- fileIt != srcFiles.end(); ++fileIt) {
- cmSourceFile* sf = *fileIt;
- if ((sf->GetExtension() == "qrc") &&
- !PropertyEnabled(sf, "SKIP_AUTOGEN") &&
- !PropertyEnabled(sf, "SKIP_AUTORCC")) {
- const std::string absFile =
- cmsys::SystemTools::GetRealPath(sf->GetFullPath());
- // qrc file
- _rcc_files.push_back(absFile);
- // qrc file entries
- {
- std::string entriesList = "{";
- // Read input file list only for non generated .qrc files.
- if (!PropertyEnabled(sf, "GENERATED")) {
- std::string error;
- std::vector<std::string> files;
- if (cmQtAutoGeneratorCommon::RccListInputs(
- qtMajorVersion, rccCommand, absFile, files, &error)) {
- entriesList += cmJoin(files, cmQtAutoGeneratorCommon::listSep);
- } else {
- cmSystemTools::Error(error.c_str());
- }
- }
- entriesList += "}";
- _rcc_inputs.push_back(entriesList);
- }
- // rcc options for this qrc file
- {
- // Merged target and file options
- std::vector<std::string> rccOptions(rccOptionsTarget);
- if (const char* prop = sf->GetProperty("AUTORCC_OPTIONS")) {
- std::vector<std::string> optsVec;
- cmSystemTools::ExpandListArgument(prop, optsVec);
- RccMergeOptions(rccOptions, optsVec, qtMajorVersion5);
- }
- // Only store non empty options lists
- if (!rccOptions.empty()) {
- rccFileFiles.push_back(absFile);
- rccFileOptions.push_back(
- cmJoin(rccOptions, cmQtAutoGeneratorCommon::listSep));
- }
- }
- }
- }
-
- AddDefinitionEscaped(makefile, "_qt_rcc_executable", rccCommand);
- AddDefinitionEscaped(makefile, "_rcc_files", _rcc_files);
- AddDefinitionEscaped(makefile, "_rcc_inputs", _rcc_inputs);
- AddDefinitionEscaped(makefile, "_rcc_options_files", rccFileFiles);
- AddDefinitionEscaped(makefile, "_rcc_options_options", rccFileOptions);
-}
-
-void cmQtAutoGeneratorInitializer::InitializeAutogenSources(
- cmGeneratorTarget* target)
-{
- if (target->GetPropertyAsBool("AUTOMOC")) {
- cmMakefile* makefile = target->Target->GetMakefile();
- const std::vector<std::string> suffixes =
- GetConfigurationSuffixes(makefile);
- // Get build directory
- const std::string autogenBuildDir = GetAutogenTargetBuildDir(target);
- // Register all compilation files as generated
- for (std::vector<std::string>::const_iterator it = suffixes.begin();
- it != suffixes.end(); ++it) {
- std::string mcFile = autogenBuildDir + "/mocs_compilation";
- mcFile += *it;
- mcFile += ".cpp";
- AddGeneratedSource(makefile, mcFile, cmQtAutoGeneratorCommon::MOC);
- }
- // Mocs compilation file
- if (IsMultiConfig(target->GetGlobalGenerator())) {
- target->AddSource(autogenBuildDir + "/mocs_compilation_$<CONFIG>.cpp");
- } else {
- target->AddSource(autogenBuildDir + "/mocs_compilation.cpp");
- }
- }
+ cmMakefile* makefile = digest.Target->Target->GetMakefile();
+ AddDefinitionEscaped(makefile, "_qt_rcc_executable",
+ RccGetExecutable(digest.Target, digest.QtVersionMajor));
+ AddDefinitionEscaped(makefile, "_rcc_files", rccFiles);
+ AddDefinitionEscaped(makefile, "_rcc_builds", rccBuilds);
+ AddDefinitionEscaped(makefile, "_rcc_options", rccOptions);
+ AddDefinitionEscaped(makefile, "_rcc_inputs", rccInputs);
}
void cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
- cmLocalGenerator* lg, cmGeneratorTarget* target)
+ cmQtAutoGenDigest& digest)
{
+ cmGeneratorTarget* target = digest.Target;
cmMakefile* makefile = target->Target->GetMakefile();
+ cmLocalGenerator* localGen = target->GetLocalGenerator();
+ cmGlobalGenerator* globalGen = localGen->GetGlobalGenerator();
- // Create a custom target for running generators at buildtime
- const bool mocEnabled = target->GetPropertyAsBool("AUTOMOC");
- const bool uicEnabled = target->GetPropertyAsBool("AUTOUIC");
- const bool rccEnabled = target->GetPropertyAsBool("AUTORCC");
- const bool multiConfig = IsMultiConfig(target->GetGlobalGenerator());
- const std::string autogenTargetName = GetAutogenTargetName(target);
- const std::string autogenBuildDir = GetAutogenTargetBuildDir(target);
- const std::string workingDirectory =
+ std::string const autogenTargetName = GetAutogenTargetName(target);
+ std::string const autogenInfoDir = GetAutogenTargetFilesDir(target);
+ std::string const autogenBuildDir = GetAutogenTargetBuildDir(target);
+ std::string const workingDirectory =
cmSystemTools::CollapseFullPath("", makefile->GetCurrentBinaryDirectory());
- const std::string qtMajorVersion = GetQtMajorVersion(target);
- const std::string rccCommand = RccGetExecutable(target, qtMajorVersion);
- const std::vector<std::string> suffixes = GetConfigurationSuffixes(makefile);
- std::vector<std::string> autogenDependFiles;
- std::vector<std::string> autogenDependTargets;
+
+ cmQtAutoGen::MultiConfig const multiConfig = AutogenMultiConfig(globalGen);
+ std::string configDefault;
+ std::vector<std::string> configsList;
+ GetConfigs(makefile, configDefault, configsList);
+
+ std::set<std::string> autogenDependFiles;
+ std::set<cmTarget*> autogenDependTargets;
std::vector<std::string> autogenProvides;
// Remove build directories on cleanup
- makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES",
- autogenBuildDir.c_str(), false);
-
+ AddCleanFile(makefile, autogenBuildDir);
// Remove old settings on cleanup
{
- std::string base = GetAutogenTargetFilesDir(target);
- for (std::vector<std::string>::const_iterator it = suffixes.begin();
- it != suffixes.end(); ++it) {
- std::string fname = base + "/AutogenOldSettings" + *it + ".cmake";
- makefile->AppendProperty("ADDITIONAL_MAKE_CLEAN_FILES", fname.c_str(),
- false);
+ std::string base = autogenInfoDir + "/AutogenOldSettings";
+ if (multiConfig == cmQtAutoGen::SINGLE) {
+ AddCleanFile(makefile, base.append(".cmake"));
+ } else {
+ for (std::string const& cfg : configsList) {
+ std::string filename = base;
+ filename += "_";
+ filename += cfg;
+ filename += ".cmake";
+ AddCleanFile(makefile, filename);
+ }
}
}
@@ -745,7 +706,7 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
currentLine.push_back(cmSystemTools::GetCMakeCommand());
currentLine.push_back("-E");
currentLine.push_back("cmake_autogen");
- currentLine.push_back(GetAutogenTargetFilesDir(target));
+ currentLine.push_back(autogenInfoDir);
currentLine.push_back("$<CONFIGURATION>");
commandLines.push_back(currentLine);
}
@@ -754,327 +715,477 @@ void cmQtAutoGeneratorInitializer::InitializeAutogenTarget(
std::string autogenComment;
{
std::vector<std::string> toolNames;
- if (mocEnabled) {
- toolNames.push_back("MOC");
+ if (digest.MocEnabled) {
+ toolNames.emplace_back("MOC");
}
- if (uicEnabled) {
- toolNames.push_back("UIC");
+ if (digest.UicEnabled) {
+ toolNames.emplace_back("UIC");
}
- if (rccEnabled) {
- toolNames.push_back("RCC");
+ if (digest.RccEnabled) {
+ toolNames.emplace_back("RCC");
}
- std::string tools = toolNames[0];
+ std::string tools = toolNames.front();
toolNames.erase(toolNames.begin());
- while (toolNames.size() > 1) {
- tools += ", " + toolNames[0];
- toolNames.erase(toolNames.begin());
- }
- if (toolNames.size() == 1) {
- tools += " and " + toolNames[0];
+ if (!toolNames.empty()) {
+ while (toolNames.size() > 1) {
+ tools += ", ";
+ tools += toolNames.front();
+ toolNames.erase(toolNames.begin());
+ }
+ tools += " and " + toolNames.front();
}
autogenComment = "Automatic " + tools + " for target " + target->GetName();
}
// Add moc compilation to generated files list
- if (mocEnabled) {
- for (std::vector<std::string>::const_iterator it = suffixes.begin();
- it != suffixes.end(); ++it) {
- std::string mcFile = autogenBuildDir + "/mocs_compilation";
- mcFile += *it;
- mcFile += ".cpp";
- autogenProvides.push_back(mcFile);
+ if (digest.MocEnabled) {
+ std::string const mocsComp = autogenBuildDir + "/mocs_compilation.cpp";
+ auto files = AddGeneratedSource(target, mocsComp, multiConfig, configsList,
+ cmQtAutoGen::MOC);
+ for (std::string& file : files) {
+ autogenProvides.push_back(std::move(file));
}
}
// Add autogen includes directory to the origin target INCLUDE_DIRECTORIES
- if (mocEnabled || uicEnabled) {
- if (multiConfig) {
- target->AddIncludeDirectory(autogenBuildDir + "/include_$<CONFIG>",
- true);
-
- } else {
- target->AddIncludeDirectory(autogenBuildDir + "/include", true);
+ if (digest.MocEnabled || digest.UicEnabled) {
+ std::string includeDir = autogenBuildDir + "/include";
+ if (multiConfig != cmQtAutoGen::SINGLE) {
+ includeDir += "_$<CONFIG>";
}
+ target->AddIncludeDirectory(includeDir, true);
}
-#if defined(_WIN32) && !defined(__CYGWIN__)
- bool usePRE_BUILD = false;
- cmGlobalGenerator* gg = lg->GetGlobalGenerator();
- if (gg->GetName().find("Visual Studio") != std::string::npos) {
- // Under VS use a PRE_BUILD event instead of a separate target to
- // reduce the number of targets loaded into the IDE.
- // This also works around a VS 11 bug that may skip updating the target:
- // https://connect.microsoft.com/VisualStudio/feedback/details/769495
- usePRE_BUILD = true;
- }
-#endif
-
- // Initialize autogen target dependencies
- if (const char* extraDeps = target->GetProperty("AUTOGEN_TARGET_DEPENDS")) {
- std::vector<std::string> deps;
- cmSystemTools::ExpandListArgument(extraDeps, deps);
- for (std::vector<std::string>::const_iterator itC = deps.begin(),
- itE = deps.end();
- itC != itE; ++itC) {
- if (makefile->FindTargetToUse(*itC) != CM_NULLPTR) {
- autogenDependTargets.push_back(*itC);
- } else {
- autogenDependFiles.push_back(*itC);
- }
- }
- }
+ // Extract relevant source files
+ std::vector<std::string> generatedSources;
+ std::vector<std::string> generatedHeaders;
{
- cmFilePathChecksum fpathCheckSum(makefile);
- // Iterate over all source files
+ std::string const qrcExt = "qrc";
std::vector<cmSourceFile*> srcFiles;
target->GetConfigCommonSourceFiles(srcFiles);
- for (std::vector<cmSourceFile*>::const_iterator fileIt = srcFiles.begin();
- fileIt != srcFiles.end(); ++fileIt) {
- cmSourceFile* sf = *fileIt;
- if (!PropertyEnabled(sf, "SKIP_AUTOGEN")) {
- std::string const& ext = sf->GetExtension();
- // Add generated file that will be scanned by moc or uic to
- // the dependencies
- if (mocEnabled || uicEnabled) {
- const cmSystemTools::FileFormat fileType =
- cmSystemTools::GetFileFormat(ext.c_str());
- if ((fileType == cmSystemTools::CXX_FILE_FORMAT) ||
- (fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
- if (PropertyEnabled(sf, "GENERATED")) {
- if ((mocEnabled && !PropertyEnabled(sf, "SKIP_AUTOMOC")) ||
- (uicEnabled && !PropertyEnabled(sf, "SKIP_AUTOUIC"))) {
- autogenDependFiles.push_back(
- cmsys::SystemTools::GetRealPath(sf->GetFullPath()));
-#if defined(_WIN32) && !defined(__CYGWIN__)
- // Cannot use PRE_BUILD with generated files
- usePRE_BUILD = false;
-#endif
+ for (cmSourceFile* sf : srcFiles) {
+ if (sf->GetPropertyAsBool("SKIP_AUTOGEN")) {
+ continue;
+ }
+ // sf->GetExtension() is only valid after sf->GetFullPath() ...
+ std::string const& fPath = sf->GetFullPath();
+ std::string const& ext = sf->GetExtension();
+ // Register generated files that will be scanned by moc or uic
+ if (digest.MocEnabled || digest.UicEnabled) {
+ cmSystemTools::FileFormat const fileType =
+ cmSystemTools::GetFileFormat(ext.c_str());
+ if ((fileType == cmSystemTools::CXX_FILE_FORMAT) ||
+ (fileType == cmSystemTools::HEADER_FILE_FORMAT)) {
+ std::string const absPath = cmSystemTools::GetRealPath(fPath);
+ if ((digest.MocEnabled && !sf->GetPropertyAsBool("SKIP_AUTOMOC")) ||
+ (digest.UicEnabled && !sf->GetPropertyAsBool("SKIP_AUTOUIC"))) {
+ // Register source
+ const bool generated = sf->GetPropertyAsBool("GENERATED");
+ if (fileType == cmSystemTools::HEADER_FILE_FORMAT) {
+ if (generated) {
+ generatedHeaders.push_back(absPath);
+ } else {
+ digest.Headers.push_back(absPath);
+ }
+ } else {
+ if (generated) {
+ generatedSources.push_back(absPath);
+ } else {
+ digest.Sources.push_back(absPath);
}
}
}
}
- // Process rcc enabled files
- if (rccEnabled && (ext == "qrc") &&
- !PropertyEnabled(sf, "SKIP_AUTORCC")) {
- const std::string absFile =
- cmsys::SystemTools::GetRealPath(sf->GetFullPath());
-
- // Compose rcc output file name
+ }
+ // Register rcc enabled files
+ if (digest.RccEnabled && (ext == qrcExt) &&
+ !sf->GetPropertyAsBool("SKIP_AUTORCC")) {
+ // Register qrc file
+ {
+ cmQtAutoGenDigestQrc qrcDigest;
+ qrcDigest.QrcFile = cmSystemTools::GetRealPath(fPath);
+ qrcDigest.QrcName =
+ cmSystemTools::GetFilenameWithoutLastExtension(qrcDigest.QrcFile);
+ qrcDigest.Generated = sf->GetPropertyAsBool("GENERATED");
+ // RCC options
{
- std::string rccOutBase = autogenBuildDir + "/";
- rccOutBase += fpathCheckSum.getPart(absFile);
- rccOutBase += "/qrc_";
- rccOutBase +=
- cmsys::SystemTools::GetFilenameWithoutLastExtension(absFile);
-
- // Register rcc ouput file as generated
- for (std::vector<std::string>::const_iterator it =
- suffixes.begin();
- it != suffixes.end(); ++it) {
- std::string rccOutCfg = rccOutBase;
- rccOutCfg += *it;
- rccOutCfg += ".cpp";
- AddGeneratedSource(makefile, rccOutCfg,
- cmQtAutoGeneratorCommon::RCC);
- autogenProvides.push_back(rccOutCfg);
- }
- // Add rcc output file to origin target sources
- if (multiConfig) {
- target->AddSource(rccOutBase + "_$<CONFIG>.cpp");
- } else {
- target->AddSource(rccOutBase + ".cpp");
+ std::string const opts = GetSafeProperty(sf, "AUTORCC_OPTIONS");
+ if (!opts.empty()) {
+ cmSystemTools::ExpandListArgument(opts, qrcDigest.Options);
}
}
+ digest.Qrcs.push_back(std::move(qrcDigest));
+ }
+ }
+ }
+ // cmGeneratorTarget::GetConfigCommonSourceFiles computes the target's
+ // sources meta data cache. Clear it so that OBJECT library targets that
+ // are AUTOGEN initialized after this target get their added
+ // mocs_compilation.cpp source acknowledged by this target.
+ target->ClearSourcesCache();
+ }
- if (PropertyEnabled(sf, "GENERATED")) {
- // Add generated qrc file to the dependencies
- autogenDependFiles.push_back(absFile);
- } else {
- // Run cmake again when .qrc file changes
- makefile->AddCMakeDependFile(absFile);
-
- // Add the qrc input files to the dependencies
- std::string error;
- if (!cmQtAutoGeneratorCommon::RccListInputs(
- qtMajorVersion, rccCommand, absFile, autogenDependFiles,
- &error)) {
- cmSystemTools::Error(error.c_str());
+ // Process GENERATED sources and headers
+ if (!generatedSources.empty() || !generatedHeaders.empty()) {
+ // Check status of policy CMP0071
+ bool policyAccept = false;
+ bool policyWarn = false;
+ cmPolicies::PolicyStatus const CMP0071_status =
+ target->Makefile->GetPolicyStatus(cmPolicies::CMP0071);
+ switch (CMP0071_status) {
+ case cmPolicies::WARN:
+ policyWarn = true;
+ CM_FALLTHROUGH;
+ case cmPolicies::OLD:
+ // Ignore GENERATED file
+ break;
+ case cmPolicies::REQUIRED_IF_USED:
+ case cmPolicies::REQUIRED_ALWAYS:
+ case cmPolicies::NEW:
+ // Process GENERATED file
+ policyAccept = true;
+ break;
+ }
+
+ if (policyAccept) {
+ // Accept GENERATED sources
+ for (std::string const& absFile : generatedHeaders) {
+ digest.Headers.push_back(absFile);
+ autogenDependFiles.insert(absFile);
+ }
+ for (std::string const& absFile : generatedSources) {
+ digest.Sources.push_back(absFile);
+ autogenDependFiles.insert(absFile);
+ }
+ } else {
+ if (policyWarn) {
+ std::string msg;
+ msg += cmPolicies::GetPolicyWarning(cmPolicies::CMP0071);
+ msg += "\n";
+ std::string tools;
+ std::string property;
+ if (digest.MocEnabled && digest.UicEnabled) {
+ tools = "AUTOMOC and AUTOUIC";
+ property = "SKIP_AUTOGEN";
+ } else if (digest.MocEnabled) {
+ tools = "AUTOMOC";
+ property = "SKIP_AUTOMOC";
+ } else if (digest.UicEnabled) {
+ tools = "AUTOUIC";
+ property = "SKIP_AUTOUIC";
+ }
+ msg += "For compatibility, CMake is excluding the GENERATED source "
+ "file(s):\n";
+ for (const std::string& absFile : generatedHeaders) {
+ msg.append(" ").append(cmQtAutoGen::Quoted(absFile)).append("\n");
+ }
+ for (const std::string& absFile : generatedSources) {
+ msg.append(" ").append(cmQtAutoGen::Quoted(absFile)).append("\n");
+ }
+ msg += "from processing by ";
+ msg += tools;
+ msg +=
+ ". If any of the files should be processed, set CMP0071 to NEW. "
+ "If any of the files should not be processed, "
+ "explicitly exclude them by setting the source file property ";
+ msg += property;
+ msg += ":\n set_property(SOURCE file.h PROPERTY ";
+ msg += property;
+ msg += " ON)\n";
+ makefile->IssueMessage(cmake::AUTHOR_WARNING, msg);
+ }
+ }
+ }
+ // Sort headers and sources
+ std::sort(digest.Headers.begin(), digest.Headers.end());
+ std::sort(digest.Sources.begin(), digest.Sources.end());
+
+ // Process qrc files
+ if (!digest.Qrcs.empty()) {
+ const bool QtV5 = (digest.QtVersionMajor == "5");
+ std::string const rcc = RccGetExecutable(target, digest.QtVersionMajor);
+ // Target rcc options
+ std::vector<std::string> optionsTarget;
+ cmSystemTools::ExpandListArgument(
+ GetSafeProperty(target, "AUTORCC_OPTIONS"), optionsTarget);
+
+ // Check if file name is unique
+ for (cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) {
+ qrcDigest.Unique = true;
+ for (cmQtAutoGenDigestQrc const& qrcDig2 : digest.Qrcs) {
+ if ((&qrcDigest != &qrcDig2) &&
+ (qrcDigest.QrcName == qrcDig2.QrcName)) {
+ qrcDigest.Unique = false;
+ break;
+ }
+ }
+ }
+ // Path checksum
+ {
+ cmFilePathChecksum const fpathCheckSum(makefile);
+ for (cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) {
+ qrcDigest.PathChecksum = fpathCheckSum.getPart(qrcDigest.QrcFile);
+ // RCC output file name
+ std::string rccFile = autogenBuildDir + "/";
+ rccFile += qrcDigest.PathChecksum;
+ rccFile += "/qrc_";
+ rccFile += qrcDigest.QrcName;
+ rccFile += ".cpp";
+ qrcDigest.RccFile = std::move(rccFile);
+ }
+ }
+ // RCC options
+ for (cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) {
+ // Target options
+ std::vector<std::string> opts = optionsTarget;
+ // Merge computed "-name XYZ" option
+ {
+ std::string name = qrcDigest.QrcName;
+ // Replace '-' with '_'. The former is not valid for symbol names.
+ std::replace(name.begin(), name.end(), '-', '_');
+ if (!qrcDigest.Unique) {
+ name += "_";
+ name += qrcDigest.PathChecksum;
+ }
+ std::vector<std::string> nameOpts;
+ nameOpts.emplace_back("-name");
+ nameOpts.emplace_back(std::move(name));
+ cmQtAutoGen::RccMergeOptions(opts, nameOpts, QtV5);
+ }
+ // Merge file option
+ cmQtAutoGen::RccMergeOptions(opts, qrcDigest.Options, QtV5);
+ qrcDigest.Options = std::move(opts);
+ }
+ for (cmQtAutoGenDigestQrc& qrcDigest : digest.Qrcs) {
+ // Register file at target
+ {
+ auto files = AddGeneratedSource(target, qrcDigest.RccFile, multiConfig,
+ configsList, cmQtAutoGen::RCC);
+ for (std::string& file : files) {
+ autogenProvides.push_back(std::move(file));
+ }
+ }
+ // Dependencies
+ if (qrcDigest.Generated) {
+ // Add the GENERATED .qrc file to the dependencies
+ autogenDependFiles.insert(qrcDigest.QrcFile);
+ } else {
+ // Add the resource files to the dependencies
+ {
+ std::string error;
+ if (cmQtAutoGen::RccListInputs(digest.QtVersionMajor, rcc,
+ qrcDigest.QrcFile,
+ qrcDigest.Resources, &error)) {
+ for (std::string const& fileName : qrcDigest.Resources) {
+ autogenDependFiles.insert(fileName);
}
+ } else {
+ cmSystemTools::Error(error.c_str());
}
-#if defined(_WIN32) && !defined(__CYGWIN__)
- // Cannot use PRE_BUILD because the resource files themselves
- // may not be sources within the target so VS may not know the
- // target needs to re-build at all.
- usePRE_BUILD = false;
-#endif
}
+ // Run cmake again when .qrc file changes
+ makefile->AddCMakeDependFile(qrcDigest.QrcFile);
}
}
}
-#if defined(_WIN32) && !defined(__CYGWIN__)
+ // Add user defined autogen target dependencies
+ {
+ std::string const deps = GetSafeProperty(target, "AUTOGEN_TARGET_DEPENDS");
+ if (!deps.empty()) {
+ std::vector<std::string> extraDeps;
+ cmSystemTools::ExpandListArgument(deps, extraDeps);
+ for (std::string const& depName : extraDeps) {
+ // Allow target and file dependencies
+ auto* depTarget = makefile->FindTargetToUse(depName);
+ if (depTarget != nullptr) {
+ autogenDependTargets.insert(depTarget);
+ } else {
+ autogenDependFiles.insert(depName);
+ }
+ }
+ }
+ }
+
+ // Use PRE_BUILD on demand
+ bool usePRE_BUILD = false;
+ if (globalGen->GetName().find("Visual Studio") != std::string::npos) {
+ // Under VS use a PRE_BUILD event instead of a separate target to
+ // reduce the number of targets loaded into the IDE.
+ // This also works around a VS 11 bug that may skip updating the target:
+ // https://connect.microsoft.com/VisualStudio/feedback/details/769495
+ usePRE_BUILD = true;
+ }
+ // Disable PRE_BUILD in some cases
if (usePRE_BUILD) {
- // We can't use pre-build if we depend on additional files
+ // Cannot use PRE_BUILD with file depends
if (!autogenDependFiles.empty()) {
usePRE_BUILD = false;
}
}
+ // Create the autogen target/command
if (usePRE_BUILD) {
+ // Add additional autogen target dependencies to origin target
+ for (cmTarget* depTarget : autogenDependTargets) {
+ target->Target->AddUtility(depTarget->GetName(), makefile);
+ }
+
// Add the pre-build command directly to bypass the OBJECT_LIBRARY
// rejection in cmMakefile::AddCustomCommandToTarget because we know
// PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
- std::vector<std::string> no_output;
- std::vector<std::string> no_depends;
- cmCustomCommand cc(makefile, no_output, autogenProvides, no_depends,
+ //
+ // PRE_BUILD does not support file dependencies!
+ const std::vector<std::string> no_output;
+ const std::vector<std::string> no_deps;
+ cmCustomCommand cc(makefile, no_output, autogenProvides, no_deps,
commandLines, autogenComment.c_str(),
workingDirectory.c_str());
cc.SetEscapeOldStyle(false);
cc.SetEscapeAllowMakeVars(true);
target->Target->AddPreBuildCommand(cc);
+ } else {
- // Add additional target dependencies to the origin target
- for (std::vector<std::string>::const_iterator
- itC = autogenDependTargets.begin(),
- itE = autogenDependTargets.end();
- itC != itE; ++itC) {
- target->Target->AddUtility(*itC);
+ // Convert file dependencies std::set to std::vector
+ std::vector<std::string> autogenDepends(autogenDependFiles.begin(),
+ autogenDependFiles.end());
+
+ // Add link library target dependencies to the autogen target dependencies
+ for (std::string const& config : configsList) {
+ cmLinkImplementationLibraries const* libs =
+ target->GetLinkImplementationLibraries(config);
+ if (libs != nullptr) {
+ for (cmLinkItem const& item : libs->Libraries) {
+ cmGeneratorTarget const* libTarget = item.Target;
+ if ((libTarget != nullptr) &&
+ !StaticLibraryCycle(target, libTarget, config)) {
+ std::string util;
+ if (configsList.size() > 1) {
+ util += "$<$<CONFIG:";
+ util += config;
+ util += ">:";
+ }
+ util += libTarget->GetName();
+ if (configsList.size() > 1) {
+ util += ">";
+ }
+ autogenDepends.push_back(util);
+ }
+ }
+ }
}
- } else
-#endif
- {
+
+ // Create autogen target
cmTarget* autogenTarget = makefile->AddUtilityCommand(
autogenTargetName, true, workingDirectory.c_str(),
- /*byproducts=*/autogenProvides, autogenDependFiles, commandLines, false,
+ /*byproducts=*/autogenProvides, autogenDepends, commandLines, false,
autogenComment.c_str());
+ // Create autogen generator target
+ localGen->AddGeneratorTarget(
+ new cmGeneratorTarget(autogenTarget, localGen));
- cmGeneratorTarget* gt = new cmGeneratorTarget(autogenTarget, lg);
- lg->AddGeneratorTarget(gt);
+ // Forward origin utilities to autogen target
+ for (std::string const& depName : target->Target->GetUtilities()) {
+ autogenTarget->AddUtility(depName, makefile);
+ }
+ // Add additional autogen target dependencies to autogen target
+ for (cmTarget* depTarget : autogenDependTargets) {
+ autogenTarget->AddUtility(depTarget->GetName(), makefile);
+ }
- // Add origin link library targets to the autogen target dependencies
+ // Set FOLDER property in autogen target
{
- const cmTarget::LinkLibraryVectorType& libVec =
- target->Target->GetOriginalLinkLibraries();
- for (cmTarget::LinkLibraryVectorType::const_iterator
- itC = libVec.begin(),
- itE = libVec.end();
- itC != itE; ++itC) {
- const std::string& libName = itC->first;
- if (makefile->FindTargetToUse(libName) != CM_NULLPTR) {
- autogenDependTargets.push_back(libName);
- }
+ const char* autogenFolder =
+ makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
+ if (autogenFolder == nullptr) {
+ autogenFolder =
+ makefile->GetState()->GetGlobalProperty("AUTOGEN_TARGETS_FOLDER");
}
- }
- // Add origin utility targets to the autogen target dependencies
- {
- const std::set<std::string>& utils = target->Target->GetUtilities();
- for (std::set<std::string>::const_iterator itC = utils.begin(),
- itE = utils.end();
- itC != itE; ++itC) {
- autogenDependTargets.push_back(*itC);
+ // Inherit FOLDER property from target (#13688)
+ if (autogenFolder == nullptr) {
+ autogenFolder = SafeString(target->Target->GetProperty("FOLDER"));
+ }
+ if ((autogenFolder != nullptr) && (*autogenFolder != '\0')) {
+ autogenTarget->SetProperty("FOLDER", autogenFolder);
}
- }
- // Add additional target dependencies to the autogen target
- for (std::vector<std::string>::const_iterator
- itC = autogenDependTargets.begin(),
- itE = autogenDependTargets.end();
- itC != itE; ++itC) {
- autogenTarget->AddUtility(*itC);
- }
-
- // Set target folder
- const char* autogenFolder =
- makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
- if (!autogenFolder) {
- autogenFolder =
- makefile->GetState()->GetGlobalProperty("AUTOGEN_TARGETS_FOLDER");
- }
- if (autogenFolder && *autogenFolder) {
- autogenTarget->SetProperty("FOLDER", autogenFolder);
- } else {
- // inherit FOLDER property from target (#13688)
- utilCopyTargetProperty(gt->Target, target->Target, "FOLDER");
}
- target->Target->AddUtility(autogenTargetName);
+ // Add autogen target to the origin target dependencies
+ target->Target->AddUtility(autogenTargetName, makefile);
}
}
void cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget(
- cmGeneratorTarget const* target)
+ cmQtAutoGenDigest const& digest)
{
+ cmGeneratorTarget const* target = digest.Target;
cmMakefile* makefile = target->Target->GetMakefile();
+ cmQtAutoGen::MultiConfig const multiConfig =
+ AutogenMultiConfig(target->GetGlobalGenerator());
// forget the variables added here afterwards again:
cmMakefile::ScopePushPop varScope(makefile);
static_cast<void>(varScope);
- // Get configurations
- std::string config;
- const std::vector<std::string> configs(GetConfigurations(makefile, &config));
-
- // Configurations settings buffers
- std::map<std::string, std::string> configSuffix;
- std::map<std::string, std::string> configMocIncludes;
- std::map<std::string, std::string> configMocDefines;
- std::map<std::string, std::string> configUicOptions;
-
- // Configuration suffix
- if (IsMultiConfig(target->GetGlobalGenerator())) {
- for (std::vector<std::string>::const_iterator it = configs.begin();
- it != configs.end(); ++it) {
- configSuffix[*it] = "_" + *it;
+ // Configurations
+ std::string configDefault;
+ std::vector<std::string> configsList;
+ std::map<std::string, std::string> configSuffixes;
+ {
+ configDefault = makefile->GetConfigurations(configsList);
+ if (configsList.empty()) {
+ configsList.push_back("");
}
}
+ for (std::string const& cfg : configsList) {
+ configSuffixes[cfg] = "_" + cfg;
+ }
+
+ // Configurations settings buffers
+ cmQtAutoGenSetup setup;
// Basic setup
+ AddDefinitionEscaped(makefile, "_multi_config",
+ cmQtAutoGen::MultiConfigName(multiConfig));
+ AddDefinitionEscaped(makefile, "_build_dir",
+ GetAutogenTargetBuildDir(target));
+ AddDefinitionEscaped(makefile, "_sources", digest.Sources);
+ AddDefinitionEscaped(makefile, "_headers", digest.Headers);
+ AddDefinitionEscaped(makefile, "_qt_version_major", digest.QtVersionMajor);
+ AddDefinitionEscaped(makefile, "_qt_version_minor", digest.QtVersionMinor);
{
- const bool mocEnabled = target->GetPropertyAsBool("AUTOMOC");
- const bool uicEnabled = target->GetPropertyAsBool("AUTOUIC");
- const bool rccEnabled = target->GetPropertyAsBool("AUTORCC");
- const std::string autogenTargetName = GetAutogenTargetName(target);
- const std::string qtMajorVersion = GetQtMajorVersion(target);
-
- std::vector<std::string> sources;
- std::vector<std::string> headers;
-
- if (mocEnabled || uicEnabled || rccEnabled) {
- std::vector<std::string> mocSkipList;
- std::vector<std::string> uicSkipList;
- AcquireScanFiles(target, sources, headers, mocSkipList, uicSkipList);
- if (mocEnabled) {
- MocSetupAutoTarget(target, autogenTargetName, qtMajorVersion, config,
- configs, mocSkipList, configMocIncludes,
- configMocDefines);
- }
- if (uicEnabled) {
- UicSetupAutoTarget(target, qtMajorVersion, config, configs,
- uicSkipList, configUicOptions);
+ if (digest.MocEnabled || digest.UicEnabled) {
+ SetupAcquireSkipFiles(digest, setup);
+ if (digest.MocEnabled) {
+ SetupAutoTargetMoc(digest, configDefault, configsList, setup);
}
- if (rccEnabled) {
- RccSetupAutoTarget(target, qtMajorVersion);
+ if (digest.UicEnabled) {
+ SetupAutoTargetUic(digest, configDefault, configsList, setup);
}
}
-
- AddDefinitionEscaped(makefile, "_autogen_build_dir",
- GetAutogenTargetBuildDir(target));
- AddDefinitionEscaped(makefile, "_qt_version_major", qtMajorVersion);
- AddDefinitionEscaped(makefile, "_sources", sources);
- AddDefinitionEscaped(makefile, "_headers", headers);
+ if (digest.RccEnabled) {
+ SetupAutoTargetRcc(digest);
+ }
}
// Generate info file
- std::string infoFile = GetAutogenTargetFilesDir(target);
- infoFile += "/AutogenInfo.cmake";
{
- std::string inf = cmSystemTools::GetCMakeRoot();
- inf += "/Modules/AutogenInfo.cmake.in";
- makefile->ConfigureFile(inf.c_str(), infoFile.c_str(), false, true, false);
- }
+ std::string const infoDir = GetAutogenTargetFilesDir(target);
+ if (!cmSystemTools::MakeDirectory(infoDir)) {
+ std::string emsg = ("Could not create directory: ");
+ emsg += cmQtAutoGen::Quoted(infoDir);
+ cmSystemTools::Error(emsg.c_str());
+ }
+ std::string const infoFile = infoDir + "/AutogenInfo.cmake";
+ {
+ std::string infoFileIn = cmSystemTools::GetCMakeRoot();
+ infoFileIn += "/Modules/AutogenInfo.cmake.in";
+ makefile->ConfigureFile(infoFileIn.c_str(), infoFile.c_str(), false,
+ true, false);
+ }
- // Append custom definitions to info file on demand
- if (!configSuffix.empty() || !configMocDefines.empty() ||
- !configMocIncludes.empty() || !configUicOptions.empty()) {
+ // Append custom definitions to info file
+ // --------------------------------------
// Ensure we have write permission in case .in was read-only.
mode_t perm = 0;
@@ -1091,39 +1202,22 @@ void cmQtAutoGeneratorInitializer::SetupAutoGenerateTarget(
// Open and write file
cmsys::ofstream ofs(infoFile.c_str(), std::ios::app);
if (ofs) {
- ofs << "# Configuration specific options\n";
- for (std::map<std::string, std::string>::iterator
- it = configSuffix.begin(),
- end = configSuffix.end();
- it != end; ++it) {
- ofs << "set(AM_CONFIG_SUFFIX_" << it->first << " " << it->second
- << ")\n";
- }
- for (std::map<std::string, std::string>::iterator
- it = configMocDefines.begin(),
- end = configMocDefines.end();
- it != end; ++it) {
- ofs << "set(AM_MOC_DEFINITIONS_" << it->first << " " << it->second
- << ")\n";
- }
- for (std::map<std::string, std::string>::iterator
- it = configMocIncludes.begin(),
- end = configMocIncludes.end();
- it != end; ++it) {
- ofs << "set(AM_MOC_INCLUDES_" << it->first << " " << it->second
- << ")\n";
- }
- for (std::map<std::string, std::string>::iterator
- it = configUicOptions.begin(),
- end = configUicOptions.end();
- it != end; ++it) {
- ofs << "set(AM_UIC_TARGET_OPTIONS_" << it->first << " " << it->second
- << ")\n";
- }
+ auto OfsWriteMap = [&ofs](
+ const char* key, std::map<std::string, std::string> const& map) {
+ for (auto const& item : map) {
+ ofs << "set(" << key << "_" << item.first << " "
+ << cmOutputConverter::EscapeForCMake(item.second) << ")\n";
+ }
+ };
+ ofs << "# Configurations options\n";
+ OfsWriteMap("AM_CONFIG_SUFFIX", configSuffixes);
+ OfsWriteMap("AM_MOC_DEFINITIONS", setup.ConfigMocDefines);
+ OfsWriteMap("AM_MOC_INCLUDES", setup.ConfigMocIncludes);
+ OfsWriteMap("AM_UIC_TARGET_OPTIONS", setup.ConfigUicOptions);
} else {
// File open error
std::string error = "Internal CMake error when trying to open file: ";
- error += cmQtAutoGeneratorCommon::Quoted(infoFile);
+ error += cmQtAutoGen::Quoted(infoFile);
error += " for writing.";
cmSystemTools::Error(error.c_str());
}
diff --git a/Source/cmQtAutoGeneratorInitializer.h b/Source/cmQtAutoGeneratorInitializer.h
index ca806f5a9..b8a5ae480 100644
--- a/Source/cmQtAutoGeneratorInitializer.h
+++ b/Source/cmQtAutoGeneratorInitializer.h
@@ -4,17 +4,21 @@
#define cmQtAutoGeneratorInitializer_h
#include "cmConfigure.h" // IWYU pragma: keep
+#include "cmQtAutoGenDigest.h"
+
+#include <string>
class cmGeneratorTarget;
-class cmLocalGenerator;
class cmQtAutoGeneratorInitializer
{
public:
- static void InitializeAutogenSources(cmGeneratorTarget* target);
- static void InitializeAutogenTarget(cmLocalGenerator* lg,
- cmGeneratorTarget* target);
- static void SetupAutoGenerateTarget(cmGeneratorTarget const* target);
+ static std::string GetQtMajorVersion(cmGeneratorTarget const* target);
+ static std::string GetQtMinorVersion(cmGeneratorTarget const* target,
+ std::string const& qtVersionMajor);
+
+ static void InitializeAutogenTarget(cmQtAutoGenDigest& digest);
+ static void SetupAutoGenerateTarget(cmQtAutoGenDigest const& digest);
};
#endif
diff --git a/Source/cmQtAutoGenerators.cxx b/Source/cmQtAutoGenerators.cxx
index c3ecb51b8..b329d3828 100644
--- a/Source/cmQtAutoGenerators.cxx
+++ b/Source/cmQtAutoGenerators.cxx
@@ -1,16 +1,15 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
+#include "cmQtAutoGen.h"
#include "cmQtAutoGenerators.h"
-#include "cmQtAutoGeneratorCommon.h"
-#include "cmConfigure.h"
#include "cmsys/FStream.hxx"
#include "cmsys/Terminal.h"
#include <algorithm>
-#include <assert.h>
+#include <array>
#include <list>
+#include <memory>
#include <sstream>
-#include <stdlib.h>
#include <string.h>
#include <utility>
@@ -23,7 +22,6 @@
#include "cmStateDirectory.h"
#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
#if defined(__APPLE__)
@@ -38,253 +36,119 @@ static const char* SettingsKeyRcc = "AM_RCC_SETTINGS_HASH";
// -- Static functions
-inline static std::string Quoted(const std::string& text)
+static std::string HeadLine(std::string const& title)
{
- return cmQtAutoGeneratorCommon::Quoted(text);
+ std::string head = title;
+ head += '\n';
+ head.append(head.size() - 1, '-');
+ head += '\n';
+ return head;
}
-static std::string QuotedCommand(const std::vector<std::string>& command)
+static std::string QuotedCommand(std::vector<std::string> const& command)
{
std::string res;
- for (std::vector<std::string>::const_iterator cit = command.begin();
- cit != command.end(); ++cit) {
+ for (std::string const& item : command) {
if (!res.empty()) {
res.push_back(' ');
}
- const std::string cesc = Quoted(*cit);
- if (cit->empty() || (cesc.size() > (cit->size() + 2)) ||
+ std::string const cesc = cmQtAutoGen::Quoted(item);
+ if (item.empty() || (cesc.size() > (item.size() + 2)) ||
(cesc.find(' ') != std::string::npos)) {
res += cesc;
} else {
- res += *cit;
+ res += item;
}
}
return res;
}
-static void InfoGet(cmMakefile* makefile, const char* key, std::string& value)
+static std::string SubDirPrefix(std::string const& fileName)
{
- value = makefile->GetSafeDefinition(key);
-}
-
-static void InfoGet(cmMakefile* makefile, const char* key, bool& value)
-{
- value = makefile->IsOn(key);
-}
-
-static void InfoGet(cmMakefile* makefile, const char* key,
- std::vector<std::string>& list)
-{
- cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition(key), list);
-}
-
-static void InfoGetConfig(cmMakefile* makefile, const char* key,
- const std::string& config, std::string& value)
-{
- const char* valueConf = CM_NULLPTR;
- {
- std::string keyConf = key;
- if (!config.empty()) {
- keyConf += "_";
- keyConf += config;
- }
- valueConf = makefile->GetDefinition(keyConf);
- }
- if (valueConf == CM_NULLPTR) {
- valueConf = makefile->GetSafeDefinition(key);
- }
- value = valueConf;
-}
-
-static void InfoGetConfig(cmMakefile* makefile, const char* key,
- const std::string& config,
- std::vector<std::string>& list)
-{
- std::string value;
- InfoGetConfig(makefile, key, config, value);
- cmSystemTools::ExpandListArgument(value, list);
-}
-
-inline static bool SettingsMatch(cmMakefile* makefile, const char* key,
- const std::string& value)
-{
- return (value == makefile->GetSafeDefinition(key));
-}
-
-static void SettingAppend(std::string& str, const char* key,
- const std::string& value)
-{
- if (!value.empty()) {
- str += "set(";
- str += key;
- str += " ";
- str += cmOutputConverter::EscapeForCMake(value);
- str += ")\n";
- }
-}
-
-static std::string SubDirPrefix(const std::string& fileName)
-{
- std::string res(cmsys::SystemTools::GetFilenamePath(fileName));
+ std::string res(cmSystemTools::GetFilenamePath(fileName));
if (!res.empty()) {
res += '/';
}
return res;
}
-static bool FileNameIsUnique(const std::string& filePath,
- const std::map<std::string, std::string>& fileMap)
-{
- size_t count(0);
- const std::string fileName = cmsys::SystemTools::GetFilenameName(filePath);
- for (std::map<std::string, std::string>::const_iterator si = fileMap.begin();
- si != fileMap.end(); ++si) {
- if (cmsys::SystemTools::GetFilenameName(si->first) == fileName) {
- ++count;
- if (count > 1) {
- return false;
- }
- }
- }
- return true;
-}
-
-static bool ReadAll(std::string& content, const std::string& filename)
+static bool ReadFile(std::string& content, std::string const& filename,
+ std::string* error = nullptr)
{
bool success = false;
- {
- cmsys::ifstream ifs(filename.c_str());
+ if (cmSystemTools::FileExists(filename)) {
+ std::size_t const length = cmSystemTools::FileLength(filename);
+ cmsys::ifstream ifs(filename.c_str(), (std::ios::in | std::ios::binary));
if (ifs) {
- std::ostringstream osst;
- osst << ifs.rdbuf();
- content = osst.str();
- success = true;
+ content.resize(length);
+ ifs.read(&content.front(), content.size());
+ if (ifs) {
+ success = true;
+ } else {
+ content.clear();
+ if (error != nullptr) {
+ error->append("Reading from the file failed.");
+ }
+ }
+ } else if (error != nullptr) {
+ error->append("Opening the file for reading failed.");
}
+ } else if (error != nullptr) {
+ error->append("The file does not exist.");
}
return success;
}
/**
- * @brief Tests if buildFile doesn't exist or is older than sourceFile
- * @return True if buildFile doesn't exist or is older than sourceFile
+ * @brief Tests if buildFile is older than sourceFile
+ * @return True if buildFile is older than sourceFile.
+ * False may indicate an error.
*/
-static bool FileAbsentOrOlder(const std::string& buildFile,
- const std::string& sourceFile)
+static bool FileIsOlderThan(std::string const& buildFile,
+ std::string const& sourceFile,
+ std::string* error = nullptr)
{
int result = 0;
- bool success =
- cmsys::SystemTools::FileTimeCompare(buildFile, sourceFile, &result);
- return (!success || (result <= 0));
-}
-
-static bool ListContains(const std::vector<std::string>& list,
- const std::string& entry)
-{
- return (std::find(list.begin(), list.end(), entry) != list.end());
-}
-
-static std::string JoinOptionsList(const std::vector<std::string>& opts)
-{
- return cmOutputConverter::EscapeForCMake(cmJoin(opts, ";"));
-}
-
-static std::string JoinOptionsMap(
- const std::map<std::string, std::string>& opts)
-{
- std::string result;
- for (std::map<std::string, std::string>::const_iterator it = opts.begin();
- it != opts.end(); ++it) {
- if (it != opts.begin()) {
- result += cmQtAutoGeneratorCommon::listSep;
- }
- result += it->first;
- result += "===";
- result += it->second;
+ if (cmSystemTools::FileTimeCompare(buildFile, sourceFile, &result)) {
+ return (result < 0);
}
- return result;
-}
-
-static std::string JoinExts(const std::vector<std::string>& lst)
-{
- std::string result;
- if (!lst.empty()) {
- const std::string separator = ",";
- for (std::vector<std::string>::const_iterator it = lst.begin();
- it != lst.end(); ++it) {
- if (it != lst.begin()) {
- result += separator;
- }
- result += '.';
- result += *it;
- }
+ if (error != nullptr) {
+ error->append(
+ "File modification time comparison failed for the files\n ");
+ error->append(cmQtAutoGen::Quoted(buildFile));
+ error->append("\nand\n ");
+ error->append(cmQtAutoGen::Quoted(sourceFile));
}
- return result;
+ return false;
}
-static void UicMergeOptions(std::vector<std::string>& opts,
- const std::vector<std::string>& fileOpts,
- bool isQt5)
+static bool ListContains(std::vector<std::string> const& list,
+ std::string const& entry)
{
- static const char* valueOptions[] = { "tr", "translate",
- "postfix", "generator",
- "include", // Since Qt 5.3
- "g" };
- std::vector<std::string> extraOpts;
- for (std::vector<std::string>::const_iterator it = fileOpts.begin();
- it != fileOpts.end(); ++it) {
- std::vector<std::string>::iterator existingIt =
- std::find(opts.begin(), opts.end(), *it);
- if (existingIt != opts.end()) {
- const char* o = it->c_str();
- if (*o == '-') {
- ++o;
- }
- if (isQt5 && *o == '-') {
- ++o;
- }
- if (std::find_if(cmArrayBegin(valueOptions), cmArrayEnd(valueOptions),
- cmStrCmp(*it)) != cmArrayEnd(valueOptions)) {
- assert(existingIt + 1 != opts.end());
- *(existingIt + 1) = *(it + 1);
- ++it;
- }
- } else {
- extraOpts.push_back(*it);
- }
- }
- opts.insert(opts.end(), extraOpts.begin(), extraOpts.end());
+ return (std::find(list.begin(), list.end(), entry) != list.end());
}
// -- Class methods
cmQtAutoGenerators::cmQtAutoGenerators()
- : Verbose(cmsys::SystemTools::HasEnv("VERBOSE"))
+ : MultiConfig(cmQtAutoGen::WRAP)
+ , IncludeProjectDirsBefore(false)
+ , Verbose(cmSystemTools::HasEnv("VERBOSE"))
, ColorOutput(true)
, MocSettingsChanged(false)
, MocPredefsChanged(false)
- , MocRunFailed(false)
+ , MocRelaxedMode(false)
, UicSettingsChanged(false)
- , UicRunFailed(false)
, RccSettingsChanged(false)
- , RccRunFailed(false)
{
-
- std::string colorEnv;
- cmsys::SystemTools::GetEnv("COLOR", colorEnv);
- if (!colorEnv.empty()) {
- if (cmSystemTools::IsOn(colorEnv.c_str())) {
- this->ColorOutput = true;
- } else {
- this->ColorOutput = false;
+ {
+ std::string colorEnv;
+ cmSystemTools::GetEnv("COLOR", colorEnv);
+ if (!colorEnv.empty()) {
+ this->ColorOutput = cmSystemTools::IsOn(colorEnv.c_str());
}
}
- // Moc macro filters
- this->MocMacroFilters[0].first = "Q_OBJECT";
- this->MocMacroFilters[0].second.compile("[\n][ \t]*Q_OBJECT[^a-zA-Z0-9_]");
- this->MocMacroFilters[1].first = "Q_GADGET";
- this->MocMacroFilters[1].second.compile("[\n][ \t]*Q_GADGET[^a-zA-Z0-9_]");
-
// Precompile regular expressions
this->MocRegExpInclude.compile(
"[\n][ \t]*#[ \t]*include[ \t]+"
@@ -293,8 +157,8 @@ cmQtAutoGenerators::cmQtAutoGenerators()
"[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
}
-bool cmQtAutoGenerators::Run(const std::string& targetDirectory,
- const std::string& config)
+bool cmQtAutoGenerators::Run(std::string const& targetDirectory,
+ std::string const& config)
{
cmake cm(cmake::RoleScript);
cm.SetHomeOutputDirectory(targetDirectory);
@@ -306,16 +170,14 @@ bool cmQtAutoGenerators::Run(const std::string& targetDirectory,
snapshot.GetDirectory().SetCurrentBinary(targetDirectory);
snapshot.GetDirectory().SetCurrentSource(targetDirectory);
- CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, snapshot));
- gg.SetCurrentMakefile(mf.get());
+ auto makefile = cm::make_unique<cmMakefile>(&gg, snapshot);
+ gg.SetCurrentMakefile(makefile.get());
bool success = false;
- if (this->ReadAutogenInfoFile(mf.get(), targetDirectory, config)) {
- // Read old settings
- this->SettingsFileRead(mf.get());
- // Init and run
- this->Init(mf.get());
- if (this->RunAutogen()) {
+ if (this->InitInfoFile(makefile.get(), targetDirectory, config)) {
+ // Read latest settings
+ this->SettingsFileRead(makefile.get());
+ if (this->Process()) {
// Write current settings
if (this->SettingsFileWrite()) {
success = true;
@@ -325,108 +187,145 @@ bool cmQtAutoGenerators::Run(const std::string& targetDirectory,
return success;
}
-bool cmQtAutoGenerators::MocDependFilterPush(const std::string& key,
- const std::string& regExp)
+bool cmQtAutoGenerators::InitInfoFile(cmMakefile* makefile,
+ std::string const& targetDirectory,
+ std::string const& config)
{
- bool success = false;
- if (!key.empty()) {
- if (!regExp.empty()) {
- MocDependFilter filter;
- filter.key = key;
- if (filter.regExp.compile(regExp)) {
- this->MocDependFilters.push_back(filter);
- success = true;
- } else {
- this->LogError("AutoMoc: Error in AUTOMOC_DEPEND_FILTERS: Compiling "
- "regular expression failed.\nKey: " +
- Quoted(key) + "\nExp.: " + Quoted(regExp));
+ // -- Meta
+ this->HeaderExtensions = makefile->GetCMakeInstance()->GetHeaderExtensions();
+
+ // Utility lambdas
+ auto InfoGet = [makefile](const char* key) {
+ return makefile->GetSafeDefinition(key);
+ };
+ auto InfoGetBool = [makefile](const char* key) {
+ return makefile->IsOn(key);
+ };
+ auto InfoGetList = [makefile](const char* key) -> std::vector<std::string> {
+ std::vector<std::string> list;
+ cmSystemTools::ExpandListArgument(makefile->GetSafeDefinition(key), list);
+ return list;
+ };
+ auto InfoGetLists =
+ [makefile](const char* key) -> std::vector<std::vector<std::string>> {
+ std::vector<std::vector<std::string>> lists;
+ {
+ std::string const value = makefile->GetSafeDefinition(key);
+ std::string::size_type pos = 0;
+ while (pos < value.size()) {
+ std::string::size_type next = value.find(cmQtAutoGen::listSep, pos);
+ std::string::size_type length =
+ (next != std::string::npos) ? next - pos : value.size() - pos;
+ // Remove enclosing braces
+ if (length >= 2) {
+ std::string::const_iterator itBeg = value.begin() + (pos + 1);
+ std::string::const_iterator itEnd = itBeg + (length - 2);
+ {
+ std::string subValue(itBeg, itEnd);
+ std::vector<std::string> list;
+ cmSystemTools::ExpandListArgument(subValue, list);
+ lists.push_back(std::move(list));
+ }
+ }
+ pos += length;
+ pos += cmQtAutoGen::listSep.size();
}
- } else {
- this->LogError("AutoMoc: Error in AUTOMOC_DEPEND_FILTERS: Regular "
- "expression is empty");
}
- } else {
- this->LogError("AutoMoc: Error in AUTOMOC_DEPEND_FILTERS: Key is empty");
- }
- return success;
-}
-
-bool cmQtAutoGenerators::ReadAutogenInfoFile(
- cmMakefile* makefile, const std::string& targetDirectory,
- const std::string& config)
-{
- std::string filename(cmSystemTools::CollapseFullPath(targetDirectory));
- cmSystemTools::ConvertToUnixSlashes(filename);
- filename += "/AutogenInfo.cmake";
+ return lists;
+ };
+ auto InfoGetConfig = [makefile, &config](const char* key) -> std::string {
+ const char* valueConf = nullptr;
+ {
+ std::string keyConf = key;
+ keyConf += '_';
+ keyConf += config;
+ valueConf = makefile->GetDefinition(keyConf);
+ }
+ if (valueConf == nullptr) {
+ valueConf = makefile->GetSafeDefinition(key);
+ }
+ return std::string(valueConf);
+ };
+ auto InfoGetConfigList =
+ [&InfoGetConfig](const char* key) -> std::vector<std::string> {
+ std::vector<std::string> list;
+ cmSystemTools::ExpandListArgument(InfoGetConfig(key), list);
+ return list;
+ };
- if (!makefile->ReadListFile(filename.c_str())) {
- this->LogError("AutoGen: Error processing file: " + filename);
+ // -- Read info file
+ this->InfoFile = cmSystemTools::CollapseFullPath(targetDirectory);
+ cmSystemTools::ConvertToUnixSlashes(this->InfoFile);
+ this->InfoFile += "/AutogenInfo.cmake";
+ if (!makefile->ReadListFile(this->InfoFile.c_str())) {
+ this->LogFileError(cmQtAutoGen::GEN, this->InfoFile,
+ "File processing failed");
return false;
}
- // - Old settings file
- {
- this->SettingsFile = cmSystemTools::CollapseFullPath(targetDirectory);
- cmSystemTools::ConvertToUnixSlashes(this->SettingsFile);
- this->SettingsFile += "/AutogenOldSettings";
- this->SettingsFile += this->ConfigSuffix;
- this->SettingsFile += ".cmake";
- }
-
// -- Meta
- InfoGetConfig(makefile, "AM_CONFIG_SUFFIX", config, this->ConfigSuffix);
+ this->MultiConfig = cmQtAutoGen::MultiConfigType(InfoGet("AM_MULTI_CONFIG"));
+ this->ConfigSuffix = InfoGetConfig("AM_CONFIG_SUFFIX");
+ if (this->ConfigSuffix.empty()) {
+ this->ConfigSuffix = "_";
+ this->ConfigSuffix += config;
+ }
// - Files and directories
- InfoGet(makefile, "AM_CMAKE_SOURCE_DIR", this->ProjectSourceDir);
- InfoGet(makefile, "AM_CMAKE_BINARY_DIR", this->ProjectBinaryDir);
- InfoGet(makefile, "AM_CMAKE_CURRENT_SOURCE_DIR", this->CurrentSourceDir);
- InfoGet(makefile, "AM_CMAKE_CURRENT_BINARY_DIR", this->CurrentBinaryDir);
- InfoGet(makefile, "AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE",
- this->IncludeProjectDirsBefore);
- InfoGet(makefile, "AM_BUILD_DIR", this->AutogenBuildDir);
+ this->ProjectSourceDir = InfoGet("AM_CMAKE_SOURCE_DIR");
+ this->ProjectBinaryDir = InfoGet("AM_CMAKE_BINARY_DIR");
+ this->CurrentSourceDir = InfoGet("AM_CMAKE_CURRENT_SOURCE_DIR");
+ this->CurrentBinaryDir = InfoGet("AM_CMAKE_CURRENT_BINARY_DIR");
+ this->IncludeProjectDirsBefore =
+ InfoGetBool("AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE");
+ this->AutogenBuildDir = InfoGet("AM_BUILD_DIR");
if (this->AutogenBuildDir.empty()) {
- this->LogError("AutoGen: Error: Missing autogen build directory ");
+ this->LogFileError(cmQtAutoGen::GEN, this->InfoFile,
+ "Autogen build directory missing");
return false;
}
- InfoGet(makefile, "AM_SOURCES", this->Sources);
- InfoGet(makefile, "AM_HEADERS", this->Headers);
// - Qt environment
- InfoGet(makefile, "AM_QT_VERSION_MAJOR", this->QtMajorVersion);
- if (this->QtMajorVersion.empty()) {
- InfoGet(makefile, "AM_Qt5Core_VERSION_MAJOR", this->QtMajorVersion);
- }
- InfoGet(makefile, "AM_QT_MOC_EXECUTABLE", this->MocExecutable);
- InfoGet(makefile, "AM_QT_UIC_EXECUTABLE", this->UicExecutable);
- InfoGet(makefile, "AM_QT_RCC_EXECUTABLE", this->RccExecutable);
+ this->QtMajorVersion = InfoGet("AM_QT_VERSION_MAJOR");
+ this->QtMinorVersion = InfoGet("AM_QT_VERSION_MINOR");
+ this->MocExecutable = InfoGet("AM_QT_MOC_EXECUTABLE");
+ this->UicExecutable = InfoGet("AM_QT_UIC_EXECUTABLE");
+ this->RccExecutable = InfoGet("AM_QT_RCC_EXECUTABLE");
- InfoGet(makefile, "AM_MOC_PREDEFS_CMD", this->MocPredefsCmd);
// Check Qt version
if ((this->QtMajorVersion != "4") && (this->QtMajorVersion != "5")) {
- this->LogError("AutoGen: Error: Unsupported Qt version: " +
- Quoted(this->QtMajorVersion));
+ this->LogFileError(cmQtAutoGen::GEN, this->InfoFile,
+ "Unsupported Qt version: " +
+ cmQtAutoGen::Quoted(this->QtMajorVersion));
return false;
}
// - Moc
if (this->MocEnabled()) {
- InfoGet(makefile, "AM_MOC_SKIP", this->MocSkipList);
- InfoGetConfig(makefile, "AM_MOC_DEFINITIONS", config,
- this->MocDefinitions);
+ this->MocSkipList = InfoGetList("AM_MOC_SKIP");
+ this->MocDefinitions = InfoGetConfigList("AM_MOC_DEFINITIONS");
#ifdef _WIN32
{
- const std::string win32("WIN32");
+ std::string const win32("WIN32");
if (!ListContains(this->MocDefinitions, win32)) {
this->MocDefinitions.push_back(win32);
}
}
#endif
- InfoGetConfig(makefile, "AM_MOC_INCLUDES", config, this->MocIncludePaths);
- InfoGet(makefile, "AM_MOC_OPTIONS", this->MocOptions);
- InfoGet(makefile, "AM_MOC_RELAXED_MODE", this->MocRelaxedMode);
+ this->MocIncludePaths = InfoGetConfigList("AM_MOC_INCLUDES");
+ this->MocOptions = InfoGetList("AM_MOC_OPTIONS");
+ this->MocRelaxedMode = InfoGetBool("AM_MOC_RELAXED_MODE");
+ {
+ std::vector<std::string> const MocMacroNames =
+ InfoGetList("AM_MOC_MACRO_NAMES");
+ for (std::string const& item : MocMacroNames) {
+ this->MocMacroFilters.emplace_back(
+ item, ("[\n][ \t]*{?[ \t]*" + item).append("[^a-zA-Z0-9_]"));
+ }
+ }
{
- std::vector<std::string> mocDependFilters;
- InfoGet(makefile, "AM_MOC_DEPEND_FILTERS", mocDependFilters);
+ std::vector<std::string> const mocDependFilters =
+ InfoGetList("AM_MOC_DEPEND_FILTERS");
// Insert Q_PLUGIN_METADATA dependency filter
if (this->QtMajorVersion != "4") {
this->MocDependFilterPush("Q_PLUGIN_METADATA",
@@ -435,104 +334,266 @@ bool cmQtAutoGenerators::ReadAutogenInfoFile(
}
// Insert user defined dependency filters
if ((mocDependFilters.size() % 2) == 0) {
- for (std::vector<std::string>::const_iterator dit =
- mocDependFilters.begin();
- dit != mocDependFilters.end(); dit += 2) {
+ for (std::vector<std::string>::const_iterator
+ dit = mocDependFilters.begin(),
+ ditEnd = mocDependFilters.end();
+ dit != ditEnd; dit += 2) {
if (!this->MocDependFilterPush(*dit, *(dit + 1))) {
return false;
}
}
} else {
- this->LogError(
- "AutoMoc: Error: AUTOMOC_DEPEND_FILTERS list size is not "
- "a multiple of 2 in:\n" +
- Quoted(filename));
+ this->LogFileError(
+ cmQtAutoGen::MOC, this->InfoFile,
+ "AUTOMOC_DEPEND_FILTERS list size is not a multiple of 2");
return false;
}
}
+ this->MocPredefsCmd = InfoGetList("AM_MOC_PREDEFS_CMD");
}
// - Uic
if (this->UicEnabled()) {
- InfoGet(makefile, "AM_UIC_SKIP", this->UicSkipList);
- InfoGet(makefile, "AM_UIC_SEARCH_PATHS", this->UicSearchPaths);
- InfoGetConfig(makefile, "AM_UIC_TARGET_OPTIONS", config,
- this->UicTargetOptions);
+ this->UicSkipList = InfoGetList("AM_UIC_SKIP");
+ this->UicSearchPaths = InfoGetList("AM_UIC_SEARCH_PATHS");
+ this->UicTargetOptions = InfoGetConfigList("AM_UIC_TARGET_OPTIONS");
{
- std::vector<std::string> uicFilesVec;
- std::vector<std::string> uicOptionsVec;
- InfoGet(makefile, "AM_UIC_OPTIONS_FILES", uicFilesVec);
- InfoGet(makefile, "AM_UIC_OPTIONS_OPTIONS", uicOptionsVec);
+ auto sources = InfoGetList("AM_UIC_OPTIONS_FILES");
+ auto options = InfoGetLists("AM_UIC_OPTIONS_OPTIONS");
// Compare list sizes
- if (uicFilesVec.size() == uicOptionsVec.size()) {
- for (std::vector<std::string>::iterator
- fileIt = uicFilesVec.begin(),
- optionIt = uicOptionsVec.begin();
- fileIt != uicFilesVec.end(); ++fileIt, ++optionIt) {
- cmSystemTools::ReplaceString(*optionIt,
- cmQtAutoGeneratorCommon::listSep, ";");
- this->UicOptions[*fileIt] = *optionIt;
- }
- } else {
- this->LogError(
- "AutoGen: Error: Uic files/options lists size missmatch in:\n" +
- Quoted(filename));
+ if (sources.size() != options.size()) {
+ std::ostringstream ost;
+ ost << "files/options lists sizes missmatch (" << sources.size() << "/"
+ << options.size() << ")";
+ this->LogFileError(cmQtAutoGen::UIC, this->InfoFile, ost.str());
return false;
}
+ auto fitEnd = sources.cend();
+ auto fit = sources.begin();
+ auto oit = options.begin();
+ while (fit != fitEnd) {
+ this->UicOptions[*fit] = std::move(*oit);
+ ++fit;
+ ++oit;
+ }
}
}
// - Rcc
if (this->RccEnabled()) {
- InfoGet(makefile, "AM_RCC_SOURCES", this->RccSources);
- // File options
+ // File lists
+ auto sources = InfoGetList("AM_RCC_SOURCES");
+ auto builds = InfoGetList("AM_RCC_BUILDS");
+ auto options = InfoGetLists("AM_RCC_OPTIONS");
+ auto inputs = InfoGetLists("AM_RCC_INPUTS");
+
+ if (sources.size() != builds.size()) {
+ std::ostringstream ost;
+ ost << "sources, builds lists sizes missmatch (" << sources.size() << "/"
+ << builds.size() << ")";
+ this->LogFileError(cmQtAutoGen::RCC, this->InfoFile, ost.str());
+ return false;
+ }
+ if (sources.size() != options.size()) {
+ std::ostringstream ost;
+ ost << "sources, options lists sizes missmatch (" << sources.size()
+ << "/" << options.size() << ")";
+ this->LogFileError(cmQtAutoGen::RCC, this->InfoFile, ost.str());
+ return false;
+ }
+ if (sources.size() != inputs.size()) {
+ std::ostringstream ost;
+ ost << "sources, inputs lists sizes missmatch (" << sources.size() << "/"
+ << inputs.size() << ")";
+ this->LogFileError(cmQtAutoGen::RCC, this->InfoFile, ost.str());
+ return false;
+ }
+ {
+ auto srcItEnd = sources.end();
+ auto srcIt = sources.begin();
+ auto bldIt = builds.begin();
+ auto optIt = options.begin();
+ auto inpIt = inputs.begin();
+ while (srcIt != srcItEnd) {
+ this->RccJobs.push_back(RccJob{ std::move(*srcIt), std::move(*bldIt),
+ std::move(*optIt),
+ std::move(*inpIt) });
+ ++srcIt;
+ ++bldIt;
+ ++optIt;
+ ++inpIt;
+ }
+ }
+ }
+
+ // Initialize source file jobs
+ {
+ // Utility lambdas
+ auto AddJob = [this](std::map<std::string, SourceJob>& jobs,
+ std::string&& sourceFile) {
+ const bool moc = !this->MocSkip(sourceFile);
+ const bool uic = !this->UicSkip(sourceFile);
+ if (moc || uic) {
+ SourceJob& job = jobs[std::move(sourceFile)];
+ job.Moc = moc;
+ job.Uic = uic;
+ }
+ };
+
+ // Add header jobs
+ for (std::string& hdr : InfoGetList("AM_HEADERS")) {
+ AddJob(this->HeaderJobs, std::move(hdr));
+ }
+ // Add source jobs
{
- std::vector<std::string> rccFilesVec;
- std::vector<std::string> rccOptionsVec;
- InfoGet(makefile, "AM_RCC_OPTIONS_FILES", rccFilesVec);
- InfoGet(makefile, "AM_RCC_OPTIONS_OPTIONS", rccOptionsVec);
- if (rccFilesVec.size() == rccOptionsVec.size()) {
- for (std::vector<std::string>::iterator
- fileIt = rccFilesVec.begin(),
- optionIt = rccOptionsVec.begin();
- fileIt != rccFilesVec.end(); ++fileIt, ++optionIt) {
- // Replace item separator
- cmSystemTools::ReplaceString(*optionIt,
- cmQtAutoGeneratorCommon::listSep, ";");
- this->RccOptions[*fileIt] = *optionIt;
+ std::vector<std::string> sources = InfoGetList("AM_SOURCES");
+ // Add header(s) for the source file
+ for (std::string const& src : sources) {
+ const bool srcMoc = !this->MocSkip(src);
+ const bool srcUic = !this->UicSkip(src);
+ if (!srcMoc && !srcUic) {
+ continue;
}
- } else {
- this->LogError(
- "AutoGen: Error: RCC files/options lists size missmatch in:\n" +
- Quoted(filename));
- return false;
+ // Search for the default header file and a private header
+ std::array<std::string, 2> headerBases;
+ headerBases[0] = SubDirPrefix(src);
+ headerBases[0] += cmSystemTools::GetFilenameWithoutLastExtension(src);
+ headerBases[1] = headerBases[0];
+ headerBases[1] += "_p";
+ for (std::string const& headerBase : headerBases) {
+ std::string header;
+ if (this->FindHeader(header, headerBase)) {
+ const bool moc = srcMoc && !this->MocSkip(header);
+ const bool uic = srcUic && !this->UicSkip(header);
+ if (moc || uic) {
+ SourceJob& job = this->HeaderJobs[std::move(header)];
+ job.Moc = moc;
+ job.Uic = uic;
+ }
+ }
+ }
+ }
+ // Add Source jobs
+ for (std::string& src : sources) {
+ AddJob(this->SourceJobs, std::move(src));
}
}
- // File lists
+ }
+
+ // Init derived information
+ // ------------------------
+
+ // Init file path checksum generator
+ this->FilePathChecksum.setupParentDirs(
+ this->CurrentSourceDir, this->CurrentBinaryDir, this->ProjectSourceDir,
+ this->ProjectBinaryDir);
+
+ // include directory
+ this->AutogenIncludeDir = "include";
+ if (this->MultiConfig != cmQtAutoGen::SINGLE) {
+ this->AutogenIncludeDir += this->ConfigSuffix;
+ }
+ this->AutogenIncludeDir += "/";
+
+ // Moc variables
+ if (this->MocEnabled()) {
+ // Mocs compilation file
+ this->MocCompFileRel = "mocs_compilation";
+ if (this->MultiConfig == cmQtAutoGen::FULL) {
+ this->MocCompFileRel += this->ConfigSuffix;
+ }
+ this->MocCompFileRel += ".cpp";
+ this->MocCompFileAbs = cmSystemTools::CollapseCombinedPath(
+ this->AutogenBuildDir, this->MocCompFileRel);
+
+ // Moc predefs file
+ if (!this->MocPredefsCmd.empty()) {
+ this->MocPredefsFileRel = "moc_predefs";
+ if (this->MultiConfig != cmQtAutoGen::SINGLE) {
+ this->MocPredefsFileRel += this->ConfigSuffix;
+ }
+ this->MocPredefsFileRel += ".h";
+ this->MocPredefsFileAbs = cmSystemTools::CollapseCombinedPath(
+ this->AutogenBuildDir, this->MocPredefsFileRel);
+ }
+
+ // Sort include directories on demand
+ if (this->IncludeProjectDirsBefore) {
+ // Move strings to temporary list
+ std::list<std::string> includes;
+ includes.insert(includes.end(), this->MocIncludePaths.begin(),
+ this->MocIncludePaths.end());
+ this->MocIncludePaths.clear();
+ this->MocIncludePaths.reserve(includes.size());
+ // Append project directories only
+ {
+ std::array<std::string const*, 2> const movePaths = {
+ { &this->ProjectBinaryDir, &this->ProjectSourceDir }
+ };
+ for (std::string const* ppath : movePaths) {
+ std::list<std::string>::iterator it = includes.begin();
+ while (it != includes.end()) {
+ std::string const& path = *it;
+ if (cmSystemTools::StringStartsWith(path, ppath->c_str())) {
+ this->MocIncludePaths.push_back(path);
+ it = includes.erase(it);
+ } else {
+ ++it;
+ }
+ }
+ }
+ }
+ // Append remaining directories
+ this->MocIncludePaths.insert(this->MocIncludePaths.end(),
+ includes.begin(), includes.end());
+ }
+ // Compose moc includes list
{
- std::vector<std::string> rccInputLists;
- InfoGet(makefile, "AM_RCC_INPUTS", rccInputLists);
- if (this->RccSources.size() == rccInputLists.size()) {
- for (std::vector<std::string>::iterator
- fileIt = this->RccSources.begin(),
- inputIt = rccInputLists.begin();
- fileIt != this->RccSources.end(); ++fileIt, ++inputIt) {
- // Remove braces
- *inputIt = inputIt->substr(1, inputIt->size() - 2);
- // Replace item separator
- cmSystemTools::ReplaceString(*inputIt,
- cmQtAutoGeneratorCommon::listSep, ";");
- std::vector<std::string> rccInputFiles;
- cmSystemTools::ExpandListArgument(*inputIt, rccInputFiles);
- this->RccInputs[*fileIt] = rccInputFiles;
+ std::set<std::string> frameworkPaths;
+ for (std::string const& path : this->MocIncludePaths) {
+ this->MocIncludes.push_back("-I" + path);
+ // Extract framework path
+ if (cmHasLiteralSuffix(path, ".framework/Headers")) {
+ // Go up twice to get to the framework root
+ std::vector<std::string> pathComponents;
+ cmSystemTools::SplitPath(path, pathComponents);
+ std::string frameworkPath = cmSystemTools::JoinPath(
+ pathComponents.begin(), pathComponents.end() - 2);
+ frameworkPaths.insert(frameworkPath);
}
- } else {
- this->LogError(
- "AutoGen: Error: RCC sources/inputs lists size missmatch in:\n" +
- Quoted(filename));
- return false;
}
+ // Append framework includes
+ for (std::string const& path : frameworkPaths) {
+ this->MocIncludes.push_back("-F");
+ this->MocIncludes.push_back(path);
+ }
+ }
+ // Setup single list with all options
+ {
+ // Add includes
+ this->MocAllOptions.insert(this->MocAllOptions.end(),
+ this->MocIncludes.begin(),
+ this->MocIncludes.end());
+ // Add definitions
+ for (std::string const& def : this->MocDefinitions) {
+ this->MocAllOptions.push_back("-D" + def);
+ }
+ // Add options
+ this->MocAllOptions.insert(this->MocAllOptions.end(),
+ this->MocOptions.begin(),
+ this->MocOptions.end());
+ }
+ }
+
+ // - Old settings file
+ {
+ this->SettingsFile = cmSystemTools::CollapseFullPath(targetDirectory);
+ cmSystemTools::ConvertToUnixSlashes(this->SettingsFile);
+ this->SettingsFile += "/AutogenOldSettings";
+ if (this->MultiConfig != cmQtAutoGen::SINGLE) {
+ this->SettingsFile += this->ConfigSuffix;
}
+ this->SettingsFile += ".cmake";
}
return true;
@@ -543,20 +604,16 @@ void cmQtAutoGenerators::SettingsFileRead(cmMakefile* makefile)
// Compose current settings strings
{
cmCryptoHash crypt(cmCryptoHash::AlgoSHA256);
- const std::string sep(" ~~~ ");
+ std::string const sep(" ~~~ ");
if (this->MocEnabled()) {
std::string str;
str += this->MocExecutable;
str += sep;
- str += JoinOptionsList(this->MocDefinitions);
- str += sep;
- str += JoinOptionsList(this->MocIncludePaths);
- str += sep;
- str += JoinOptionsList(this->MocOptions);
+ str += cmJoin(this->MocAllOptions, ";");
str += sep;
str += this->IncludeProjectDirsBefore ? "TRUE" : "FALSE";
str += sep;
- str += JoinOptionsList(this->MocPredefsCmd);
+ str += cmJoin(this->MocPredefsCmd, ";");
str += sep;
this->SettingsStringMoc = crypt.HashString(str);
}
@@ -564,17 +621,27 @@ void cmQtAutoGenerators::SettingsFileRead(cmMakefile* makefile)
std::string str;
str += this->UicExecutable;
str += sep;
- str += JoinOptionsList(this->UicTargetOptions);
- str += sep;
- str += JoinOptionsMap(this->UicOptions);
+ str += cmJoin(this->UicTargetOptions, ";");
+ for (const auto& item : this->UicOptions) {
+ str += sep;
+ str += item.first;
+ str += sep;
+ str += cmJoin(item.second, ";");
+ }
str += sep;
this->SettingsStringUic = crypt.HashString(str);
}
if (this->RccEnabled()) {
std::string str;
str += this->RccExecutable;
- str += sep;
- str += JoinOptionsMap(this->RccOptions);
+ for (const RccJob& rccJob : this->RccJobs) {
+ str += sep;
+ str += rccJob.QrcFile;
+ str += sep;
+ str += rccJob.RccFile;
+ str += sep;
+ str += cmJoin(rccJob.Options, ";");
+ }
str += sep;
this->SettingsStringRcc = crypt.HashString(str);
}
@@ -582,19 +649,24 @@ void cmQtAutoGenerators::SettingsFileRead(cmMakefile* makefile)
// Read old settings
if (makefile->ReadListFile(this->SettingsFile.c_str())) {
- if (!SettingsMatch(makefile, SettingsKeyMoc, this->SettingsStringMoc)) {
- this->MocSettingsChanged = true;
- }
- if (!SettingsMatch(makefile, SettingsKeyUic, this->SettingsStringUic)) {
- this->UicSettingsChanged = true;
- }
- if (!SettingsMatch(makefile, SettingsKeyRcc, this->SettingsStringRcc)) {
- this->RccSettingsChanged = true;
+ {
+ auto SMatch = [makefile](const char* key, std::string const& value) {
+ return (value == makefile->GetSafeDefinition(key));
+ };
+ if (!SMatch(SettingsKeyMoc, this->SettingsStringMoc)) {
+ this->MocSettingsChanged = true;
+ }
+ if (!SMatch(SettingsKeyUic, this->SettingsStringUic)) {
+ this->UicSettingsChanged = true;
+ }
+ if (!SMatch(SettingsKeyRcc, this->SettingsStringRcc)) {
+ this->RccSettingsChanged = true;
+ }
}
// In case any setting changed remove the old settings file.
// This triggers a full rebuild on the next run if the current
// build is aborted before writing the current settings in the end.
- if (this->AnySettingsChanged()) {
+ if (this->SettingsChanged()) {
cmSystemTools::RemoveFile(this->SettingsFile);
}
} else {
@@ -609,20 +681,30 @@ bool cmQtAutoGenerators::SettingsFileWrite()
{
bool success = true;
// Only write if any setting changed
- if (this->AnySettingsChanged()) {
+ if (this->SettingsChanged()) {
if (this->Verbose) {
- this->LogInfo("AutoGen: Writing settings file " +
- Quoted(this->SettingsFile));
+ this->LogInfo(cmQtAutoGen::GEN, "Writing settings file " +
+ cmQtAutoGen::Quoted(this->SettingsFile));
}
// Compose settings file content
std::string settings;
- SettingAppend(settings, SettingsKeyMoc, this->SettingsStringMoc);
- SettingAppend(settings, SettingsKeyUic, this->SettingsStringUic);
- SettingAppend(settings, SettingsKeyRcc, this->SettingsStringRcc);
+ {
+ auto SettingAppend = [&settings](const char* key,
+ std::string const& value) {
+ settings += "set(";
+ settings += key;
+ settings += " ";
+ settings += cmOutputConverter::EscapeForCMake(value);
+ settings += ")\n";
+ };
+ SettingAppend(SettingsKeyMoc, this->SettingsStringMoc);
+ SettingAppend(SettingsKeyUic, this->SettingsStringUic);
+ SettingAppend(SettingsKeyRcc, this->SettingsStringRcc);
+ }
// Write settings file
- if (!this->FileWrite("AutoGen", this->SettingsFile, settings)) {
- this->LogError("AutoGen: Error: Could not write old settings file " +
- Quoted(this->SettingsFile));
+ if (!this->FileWrite(cmQtAutoGen::GEN, this->SettingsFile, settings)) {
+ this->LogFileError(cmQtAutoGen::GEN, this->SettingsFile,
+ "Settings file writing failed");
// Remove old settings file to trigger a full rebuild on the next run
cmSystemTools::RemoveFile(this->SettingsFile);
success = false;
@@ -631,157 +713,49 @@ bool cmQtAutoGenerators::SettingsFileWrite()
return success;
}
-void cmQtAutoGenerators::Init(cmMakefile* makefile)
-{
- // Mocs compilation file
- this->MocCompFileRel = "mocs_compilation";
- this->MocCompFileRel += this->ConfigSuffix;
- this->MocCompFileRel += ".cpp";
- this->MocCompFileAbs = cmSystemTools::CollapseCombinedPath(
- this->AutogenBuildDir, this->MocCompFileRel);
-
- // Mocs include directory
- this->AutogenIncludeDir = "include";
- this->AutogenIncludeDir += this->ConfigSuffix;
- this->AutogenIncludeDir += "/";
-
- // Moc predefs file
- if (!this->MocPredefsCmd.empty()) {
- this->MocPredefsFileRel = "moc_predefs.h";
- this->MocPredefsFileAbs = cmSystemTools::CollapseCombinedPath(
- this->AutogenBuildDir, this->MocPredefsFileRel);
- }
-
- // Init file path checksum generator
- FPathChecksum.setupParentDirs(this->CurrentSourceDir, this->CurrentBinaryDir,
- this->ProjectSourceDir,
- this->ProjectBinaryDir);
-
- // Acquire header extensions
- this->HeaderExtensions = makefile->GetCMakeInstance()->GetHeaderExtensions();
-
- // Sort include directories on demand
- if (this->IncludeProjectDirsBefore) {
- // Move strings to temporary list
- std::list<std::string> includes;
- includes.insert(includes.end(), this->MocIncludePaths.begin(),
- this->MocIncludePaths.end());
- this->MocIncludePaths.clear();
- this->MocIncludePaths.reserve(includes.size());
- // Append project directories only
- {
- const char* movePaths[2] = { this->ProjectBinaryDir.c_str(),
- this->ProjectSourceDir.c_str() };
- for (const char* const* mpit = cmArrayBegin(movePaths);
- mpit != cmArrayEnd(movePaths); ++mpit) {
- std::list<std::string>::iterator it = includes.begin();
- while (it != includes.end()) {
- const std::string& path = *it;
- if (cmsys::SystemTools::StringStartsWith(path, *mpit)) {
- this->MocIncludePaths.push_back(path);
- it = includes.erase(it);
- } else {
- ++it;
- }
- }
- }
- }
- // Append remaining directories
- this->MocIncludePaths.insert(this->MocIncludePaths.end(), includes.begin(),
- includes.end());
- }
- // Compose moc includes list
- {
- std::set<std::string> frameworkPaths;
- for (std::vector<std::string>::const_iterator it =
- this->MocIncludePaths.begin();
- it != this->MocIncludePaths.end(); ++it) {
- const std::string& path = *it;
- this->MocIncludes.push_back("-I" + path);
- // Extract framework path
- if (cmHasLiteralSuffix(path, ".framework/Headers")) {
- // Go up twice to get to the framework root
- std::vector<std::string> pathComponents;
- cmsys::SystemTools::SplitPath(path, pathComponents);
- std::string frameworkPath = cmsys::SystemTools::JoinPath(
- pathComponents.begin(), pathComponents.end() - 2);
- frameworkPaths.insert(frameworkPath);
- }
- }
- // Append framework includes
- for (std::set<std::string>::const_iterator it = frameworkPaths.begin();
- it != frameworkPaths.end(); ++it) {
- this->MocIncludes.push_back("-F");
- this->MocIncludes.push_back(*it);
- }
- }
-}
-
-bool cmQtAutoGenerators::RunAutogen()
+bool cmQtAutoGenerators::Process()
{
// the program goes through all .cpp files to see which moc files are
// included. It is not really interesting how the moc file is named, but
// what file the moc is created from. Once a moc is included the same moc
- // may not be included in the mocs_compilation_$<CONFIG>.cpp file anymore.
+ // may not be included in the mocs_compilation.cpp file anymore.
// OTOH if there's a header containing Q_OBJECT where no corresponding
// moc file is included anywhere a moc_<filename>.cpp file is created and
- // included in the mocs_compilation_$<CONFIG>.cpp file.
+ // included in the mocs_compilation.cpp file.
// Create AUTOGEN include directory
{
- const std::string incDirAbs = cmSystemTools::CollapseCombinedPath(
+ std::string const incDirAbs = cmSystemTools::CollapseCombinedPath(
this->AutogenBuildDir, this->AutogenIncludeDir);
- if (!cmsys::SystemTools::MakeDirectory(incDirAbs)) {
- this->LogError("AutoGen: Error: Could not create include directory " +
- Quoted(incDirAbs));
+ if (!cmSystemTools::MakeDirectory(incDirAbs)) {
+ this->LogFileError(cmQtAutoGen::GEN, incDirAbs,
+ "Could not create directory");
return false;
}
}
- // key = moc source filepath, value = moc output filepath
- std::map<std::string, std::string> mocsIncluded;
- std::map<std::string, std::string> mocsNotIncluded;
- std::map<std::string, std::set<std::string> > mocDepends;
- std::map<std::string, std::vector<std::string> > uisIncluded;
- // collects all headers which may need to be mocced
- std::set<std::string> mocHeaderFiles;
- std::set<std::string> uicHeaderFiles;
-
- // Parse sources
- for (std::vector<std::string>::const_iterator it = this->Sources.begin();
- it != this->Sources.end(); ++it) {
- const std::string& absFilename = cmsys::SystemTools::GetRealPath(*it);
- // Parse source file for MOC/UIC
- if (!this->ParseSourceFile(absFilename, mocsIncluded, mocDepends,
- uisIncluded, this->MocRelaxedMode)) {
+ // Parse source files
+ for (const auto& item : this->SourceJobs) {
+ if (!this->ParseSourceFile(item.first, item.second)) {
return false;
}
- // Find additional headers
- this->SearchHeadersForSourceFile(absFilename, mocHeaderFiles,
- uicHeaderFiles);
}
-
- // Parse headers
- for (std::vector<std::string>::const_iterator it = this->Headers.begin();
- it != this->Headers.end(); ++it) {
- const std::string& headerName = cmsys::SystemTools::GetRealPath(*it);
- if (!this->MocSkip(headerName)) {
- mocHeaderFiles.insert(headerName);
- }
- if (!this->UicSkip(headerName)) {
- uicHeaderFiles.insert(headerName);
+ // Parse header files
+ for (const auto& item : this->HeaderJobs) {
+ if (!this->ParseHeaderFile(item.first, item.second)) {
+ return false;
}
}
- if (!this->ParseHeaders(mocHeaderFiles, uicHeaderFiles, mocsIncluded,
- mocsNotIncluded, mocDepends, uisIncluded)) {
+ // Read missing dependency information
+ if (!this->ParsePostprocess()) {
return false;
- };
+ }
// Generate files
- if (!this->MocGenerateAll(mocsIncluded, mocsNotIncluded, mocDepends)) {
+ if (!this->MocGenerateAll()) {
return false;
}
- if (!this->UicGenerateAll(uisIncluded)) {
+ if (!this->UicGenerateAll()) {
return false;
}
if (!this->RccGenerateAll()) {
@@ -792,72 +766,96 @@ bool cmQtAutoGenerators::RunAutogen()
}
/**
- * @brief Tests if the C++ content requires moc processing
- * @return True if moc is required
+ * @return True on success
*/
-bool cmQtAutoGenerators::MocRequired(const std::string& contentText,
- std::string* macroName)
+bool cmQtAutoGenerators::ParseSourceFile(std::string const& absFilename,
+ const SourceJob& job)
{
- for (unsigned int ii = 0; ii != cmArraySize(this->MocMacroFilters); ++ii) {
- MocMacroFilter& filter = this->MocMacroFilters[ii];
- // Run a simple find string operation before the expensive
- // regular expression check
- if (contentText.find(filter.first) != std::string::npos) {
- if (filter.second.find(contentText)) {
- // Return macro name on demand
- if (macroName != CM_NULLPTR) {
- *macroName = filter.first;
- }
- return true;
+ std::string contentText;
+ std::string error;
+ bool success = ReadFile(contentText, absFilename, &error);
+ if (success) {
+ if (!contentText.empty()) {
+ if (job.Moc) {
+ success = this->MocParseSourceContent(absFilename, contentText);
}
+ if (success && job.Uic) {
+ success = this->UicParseContent(absFilename, contentText);
+ }
+ } else {
+ this->LogFileWarning(cmQtAutoGen::GEN, absFilename,
+ "The source file is empty");
}
+ } else {
+ this->LogFileError(cmQtAutoGen::GEN, absFilename,
+ "Could not read the source file: " + error);
}
- return false;
+ return success;
}
-void cmQtAutoGenerators::MocFindDepends(
- const std::string& absFilename, const std::string& contentText,
- std::map<std::string, std::set<std::string> >& mocDepends)
+/**
+ * @return True on success
+ */
+bool cmQtAutoGenerators::ParseHeaderFile(std::string const& absFilename,
+ const SourceJob& job)
{
- for (std::vector<MocDependFilter>::iterator fit =
- this->MocDependFilters.begin();
- fit != this->MocDependFilters.end(); ++fit) {
- MocDependFilter& filter = *fit;
- // Run a simple find string operation before the expensive
- // regular expression check
- if (contentText.find(filter.key) != std::string::npos) {
- // Run regular expression check loop
- const std::string sourcePath = SubDirPrefix(absFilename);
- const char* contentChars = contentText.c_str();
- while (filter.regExp.find(contentChars)) {
- // Evaluate match
- const std::string match = filter.regExp.match(1);
- if (!match.empty()) {
- // Find the dependency file
- std::string incFile;
- if (this->MocFindIncludedFile(incFile, sourcePath, match)) {
- mocDepends[absFilename].insert(incFile);
- if (this->Verbose) {
- this->LogInfo("AutoMoc: Found dependency:\n " +
- Quoted(absFilename) + "\n " + Quoted(incFile));
- }
- } else {
- this->LogWarning("AutoMoc: Warning: " + Quoted(absFilename) +
- "\n" + "Could not find dependency file " +
- Quoted(match));
- }
- }
- contentChars += filter.regExp.end();
+ std::string contentText;
+ std::string error;
+ bool success = ReadFile(contentText, absFilename, &error);
+ if (success) {
+ if (!contentText.empty()) {
+ if (job.Moc) {
+ this->MocParseHeaderContent(absFilename, contentText);
+ }
+ if (job.Uic) {
+ success = this->UicParseContent(absFilename, contentText);
+ }
+ } else {
+ this->LogFileWarning(cmQtAutoGen::GEN, absFilename,
+ "The header file is empty");
+ }
+ } else {
+ this->LogFileError(cmQtAutoGen::GEN, absFilename,
+ "Could not read the header file: " + error);
+ }
+ return success;
+}
+
+/**
+ * @return True on success
+ */
+bool cmQtAutoGenerators::ParsePostprocess()
+{
+ bool success = true;
+ // Read missin dependecies
+ for (auto& item : this->MocJobsIncluded) {
+ if (!item->DependsValid) {
+ std::string content;
+ std::string error;
+ if (ReadFile(content, item->SourceFile, &error)) {
+ this->MocFindDepends(item->SourceFile, content, item->Depends);
+ item->DependsValid = true;
+ } else {
+ std::string emsg = "Could not read file\n ";
+ emsg += item->SourceFile;
+ emsg += "\nrequired by moc include \"";
+ emsg += item->IncludeString;
+ emsg += "\".\n";
+ emsg += error;
+ this->LogFileError(cmQtAutoGen::MOC, item->Includer, emsg);
+ success = false;
+ break;
}
}
}
+ return success;
}
/**
* @brief Tests if the file should be ignored for moc scanning
* @return True if the file should be ignored
*/
-bool cmQtAutoGenerators::MocSkip(const std::string& absFilename) const
+bool cmQtAutoGenerators::MocSkip(std::string const& absFilename) const
{
if (this->MocEnabled()) {
// Test if the file name is on the skip list
@@ -869,68 +867,189 @@ bool cmQtAutoGenerators::MocSkip(const std::string& absFilename) const
}
/**
- * @brief Tests if the file name is in the skip list
+ * @brief Tests if the C++ content requires moc processing
+ * @return True if moc is required
*/
-bool cmQtAutoGenerators::UicSkip(const std::string& absFilename) const
+bool cmQtAutoGenerators::MocRequired(std::string const& contentText,
+ std::string* macroName)
{
- if (this->UicEnabled()) {
- // Test if the file name is on the skip list
- if (!ListContains(this->UicSkipList, absFilename)) {
- return false;
+ for (KeyRegExp& filter : this->MocMacroFilters) {
+ // Run a simple find string operation before the expensive
+ // regular expression check
+ if (contentText.find(filter.Key) != std::string::npos) {
+ if (filter.RegExp.find(contentText)) {
+ // Return macro name on demand
+ if (macroName != nullptr) {
+ *macroName = filter.Key;
+ }
+ return true;
+ }
}
}
- return true;
+ return false;
}
-/**
- * @return True on success
- */
-bool cmQtAutoGenerators::ParseSourceFile(
- const std::string& absFilename,
- std::map<std::string, std::string>& mocsIncluded,
- std::map<std::string, std::set<std::string> >& mocDepends,
- std::map<std::string, std::vector<std::string> >& uisIncluded, bool relaxed)
+std::string cmQtAutoGenerators::MocStringMacros() const
{
- std::string contentText;
- bool success = ReadAll(contentText, absFilename);
- if (success) {
- if (!contentText.empty()) {
- // Parse source contents for MOC
- if (success && !this->MocSkip(absFilename)) {
- success = this->MocParseSourceContent(
- absFilename, contentText, mocsIncluded, mocDepends, relaxed);
+ std::string res;
+ const auto itB = this->MocMacroFilters.cbegin();
+ const auto itE = this->MocMacroFilters.cend();
+ const auto itL = itE - 1;
+ auto itC = itB;
+ for (; itC != itE; ++itC) {
+ // Separator
+ if (itC != itB) {
+ if (itC != itL) {
+ res += ", ";
+ } else {
+ res += " or ";
+ }
+ }
+ // Key
+ res += itC->Key;
+ }
+ return res;
+}
+
+std::string cmQtAutoGenerators::MocStringHeaders(
+ std::string const& fileBase) const
+{
+ std::string res = fileBase;
+ res += ".{";
+ res += cmJoin(this->HeaderExtensions, ",");
+ res += "}";
+ return res;
+}
+
+std::string cmQtAutoGenerators::MocFindIncludedHeader(
+ std::string const& sourcePath, std::string const& includeBase) const
+{
+ std::string header;
+ // Search in vicinity of the source
+ if (!this->FindHeader(header, sourcePath + includeBase)) {
+ // Search in include directories
+ for (std::string const& path : this->MocIncludePaths) {
+ std::string fullPath = path;
+ fullPath.push_back('/');
+ fullPath += includeBase;
+ if (this->FindHeader(header, fullPath)) {
+ break;
+ }
+ }
+ }
+ // Sanitize
+ if (!header.empty()) {
+ header = cmSystemTools::GetRealPath(header);
+ }
+ return header;
+}
+
+bool cmQtAutoGenerators::MocFindIncludedFile(
+ std::string& absFile, std::string const& sourcePath,
+ std::string const& includeString) const
+{
+ bool success = false;
+ // Search in vicinity of the source
+ {
+ std::string testPath = sourcePath;
+ testPath += includeString;
+ if (cmSystemTools::FileExists(testPath.c_str())) {
+ absFile = cmSystemTools::GetRealPath(testPath);
+ success = true;
+ }
+ }
+ // Search in include directories
+ if (!success) {
+ for (std::string const& path : this->MocIncludePaths) {
+ std::string fullPath = path;
+ fullPath.push_back('/');
+ fullPath += includeString;
+ if (cmSystemTools::FileExists(fullPath.c_str())) {
+ absFile = cmSystemTools::GetRealPath(fullPath);
+ success = true;
+ break;
}
- // Parse source contents for UIC
- if (success && !this->UicSkip(absFilename)) {
- this->UicParseContent(absFilename, contentText, uisIncluded);
+ }
+ }
+ return success;
+}
+
+bool cmQtAutoGenerators::MocDependFilterPush(std::string const& key,
+ std::string const& regExp)
+{
+ std::string error;
+ if (!key.empty()) {
+ if (!regExp.empty()) {
+ KeyRegExp filter;
+ filter.Key = key;
+ if (filter.RegExp.compile(regExp)) {
+ this->MocDependFilters.push_back(std::move(filter));
+ } else {
+ error = "Regular expression compiling failed";
}
} else {
- std::ostringstream ost;
- ost << "AutoGen: Warning: The file is empty:\n"
- << Quoted(absFilename) << "\n";
- this->LogWarning(ost.str());
+ error = "Regular expression is empty";
}
} else {
- std::ostringstream ost;
- ost << "AutoGen: Error: Could not read file:\n" << Quoted(absFilename);
- this->LogError(ost.str());
+ error = "Key is empty";
}
- return success;
+ if (!error.empty()) {
+ std::string emsg = "AUTOMOC_DEPEND_FILTERS: ";
+ emsg += error;
+ emsg += "\n";
+ emsg += " Key: ";
+ emsg += cmQtAutoGen::Quoted(key);
+ emsg += "\n";
+ emsg += " RegExp: ";
+ emsg += cmQtAutoGen::Quoted(regExp);
+ emsg += "\n";
+ this->LogError(cmQtAutoGen::MOC, emsg);
+ return false;
+ }
+ return true;
}
-void cmQtAutoGenerators::UicParseContent(
- const std::string& absFilename, const std::string& contentText,
- std::map<std::string, std::vector<std::string> >& uisIncluded)
+void cmQtAutoGenerators::MocFindDepends(std::string const& absFilename,
+ std::string const& contentText,
+ std::set<std::string>& depends)
{
- if (this->Verbose) {
- this->LogInfo("AutoUic: Checking " + absFilename);
+ if (this->MocDependFilters.empty() && contentText.empty()) {
+ return;
}
- const char* contentChars = contentText.c_str();
- if (strstr(contentChars, "ui_") != CM_NULLPTR) {
- while (this->UicRegExpInclude.find(contentChars)) {
- uisIncluded[absFilename].push_back(this->UicRegExpInclude.match(1));
- contentChars += this->UicRegExpInclude.end();
+ std::vector<std::string> matches;
+ for (KeyRegExp& filter : this->MocDependFilters) {
+ // Run a simple find string check
+ if (contentText.find(filter.Key) != std::string::npos) {
+ // Run the expensive regular expression check loop
+ const char* contentChars = contentText.c_str();
+ while (filter.RegExp.find(contentChars)) {
+ std::string match = filter.RegExp.match(1);
+ if (!match.empty()) {
+ matches.emplace_back(std::move(match));
+ }
+ contentChars += filter.RegExp.end();
+ }
+ }
+ }
+
+ if (!matches.empty()) {
+ std::string const sourcePath = SubDirPrefix(absFilename);
+ for (std::string const& match : matches) {
+ // Find the dependency file
+ std::string incFile;
+ if (this->MocFindIncludedFile(incFile, sourcePath, match)) {
+ depends.insert(incFile);
+ if (this->Verbose) {
+ this->LogInfo(cmQtAutoGen::MOC, "Found dependency:\n " +
+ cmQtAutoGen::Quoted(absFilename) + "\n " +
+ cmQtAutoGen::Quoted(incFile));
+ }
+ } else {
+ this->LogFileWarning(cmQtAutoGen::MOC, absFilename,
+ "Could not find dependency file " +
+ cmQtAutoGen::Quoted(match));
+ }
}
}
}
@@ -938,322 +1057,336 @@ void cmQtAutoGenerators::UicParseContent(
/**
* @return True on success
*/
-bool cmQtAutoGenerators::MocParseSourceContent(
- const std::string& absFilename, const std::string& contentText,
- std::map<std::string, std::string>& mocsIncluded,
- std::map<std::string, std::set<std::string> >& mocDepends, bool relaxed)
+bool cmQtAutoGenerators::MocParseSourceContent(std::string const& absFilename,
+ std::string const& contentText)
{
if (this->Verbose) {
- this->LogInfo("AutoMoc: Checking " + absFilename);
- }
+ this->LogInfo(cmQtAutoGen::MOC, "Checking: " + absFilename);
+ }
+
+ auto AddJob = [this, &absFilename](std::string const& sourceFile,
+ std::string const& includeString,
+ std::string const* content) {
+ auto job = cm::make_unique<MocJobIncluded>();
+ job->SourceFile = sourceFile;
+ job->BuildFileRel = this->AutogenIncludeDir;
+ job->BuildFileRel += includeString;
+ job->Includer = absFilename;
+ job->IncludeString = includeString;
+ job->DependsValid = (content != nullptr);
+ if (job->DependsValid) {
+ this->MocFindDepends(sourceFile, *content, job->Depends);
+ }
+ this->MocJobsIncluded.push_back(std::move(job));
+ };
- const std::string scannedFileAbsPath = SubDirPrefix(absFilename);
- const std::string scannedFileBasename =
- cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
+ struct MocInc
+ {
+ std::string Inc; // full include string
+ std::string Dir; // include string directory
+ std::string Base; // include string file base
+ };
- std::string macroName;
- const bool requiresMoc = this->MocRequired(contentText, &macroName);
- bool ownDotMocIncluded = false;
- std::string ownMocUnderscoreInclude;
- std::string ownMocUnderscoreHeader;
-
- // first a simple string check for "moc" is *much* faster than the regexp,
- // and if the string search already fails, we don't have to try the
- // expensive regexp
- const char* contentChars = contentText.c_str();
- if (strstr(contentChars, "moc") != CM_NULLPTR) {
- // Iterate over all included moc files
- while (this->MocRegExpInclude.find(contentChars)) {
- const std::string incString = this->MocRegExpInclude.match(1);
- // Basename of the moc include
- const std::string incSubDir(SubDirPrefix(incString));
- const std::string incBasename =
- cmsys::SystemTools::GetFilenameWithoutLastExtension(incString);
-
- // If the moc include is of the moc_foo.cpp style we expect
- // the Q_OBJECT class declaration in a header file.
- // If the moc include is of the foo.moc style we need to look for
- // a Q_OBJECT macro in the current source file, if it contains the
- // macro we generate the moc file from the source file.
- if (cmHasLiteralPrefix(incBasename, "moc_")) {
- // Include: moc_FOO.cxx
- // Remove the moc_ part
- const std::string incRealBasename = incBasename.substr(4);
- const std::string headerToMoc =
- this->MocFindHeader(scannedFileAbsPath, incSubDir + incRealBasename);
- if (!headerToMoc.empty()) {
- if (!this->MocSkip(headerToMoc)) {
- // Register moc job
- mocsIncluded[headerToMoc] = incString;
- this->MocFindDepends(headerToMoc, contentText, mocDepends);
- // Store meta information for relaxed mode
- if (relaxed && (incRealBasename == scannedFileBasename)) {
- ownMocUnderscoreInclude = incString;
- ownMocUnderscoreHeader = headerToMoc;
- }
- }
+ // Extract moc includes from file
+ std::vector<MocInc> mocIncsUsc;
+ std::vector<MocInc> mocIncsDot;
+ {
+ const char* contentChars = contentText.c_str();
+ if (strstr(contentChars, "moc") != nullptr) {
+ while (this->MocRegExpInclude.find(contentChars)) {
+ std::string incString = this->MocRegExpInclude.match(1);
+ std::string incDir(SubDirPrefix(incString));
+ std::string incBase =
+ cmSystemTools::GetFilenameWithoutLastExtension(incString);
+ if (cmHasLiteralPrefix(incBase, "moc_")) {
+ // moc_<BASE>.cxx
+ // Remove the moc_ part from the base name
+ mocIncsUsc.push_back(MocInc{ std::move(incString), std::move(incDir),
+ incBase.substr(4) });
} else {
- std::ostringstream ost;
- ost << "AutoMoc: Error: " << Quoted(absFilename) << "\n"
- << "The file includes the moc file " << Quoted(incString)
- << ", but could not find header "
- << Quoted(incRealBasename + "{" +
- JoinExts(this->HeaderExtensions) + "}");
- ;
- this->LogError(ost.str());
- return false;
+ // <BASE>.moc
+ mocIncsDot.push_back(MocInc{ std::move(incString), std::move(incDir),
+ std::move(incBase) });
}
+ // Forward content pointer
+ contentChars += this->MocRegExpInclude.end();
+ }
+ }
+ }
+
+ std::string selfMacroName;
+ const bool selfRequiresMoc = this->MocRequired(contentText, &selfMacroName);
+
+ // Check if there is anything to do
+ if (!selfRequiresMoc && mocIncsUsc.empty() && mocIncsDot.empty()) {
+ return true;
+ }
+
+ // Scan file variables
+ std::string const scanFileDir = SubDirPrefix(absFilename);
+ std::string const scanFileBase =
+ cmSystemTools::GetFilenameWithoutLastExtension(absFilename);
+ // Relaxed mode variables
+ bool ownDotMocIncluded = false;
+ std::string ownMocUscInclude;
+ std::string ownMocUscHeader;
+
+ // Process moc_<BASE>.cxx includes
+ for (const MocInc& mocInc : mocIncsUsc) {
+ std::string const header =
+ this->MocFindIncludedHeader(scanFileDir, mocInc.Dir + mocInc.Base);
+ if (!header.empty()) {
+ // Check if header is skipped
+ if (this->MocSkip(header)) {
+ continue;
+ }
+ // Register moc job
+ AddJob(header, mocInc.Inc, nullptr);
+ // Store meta information for relaxed mode
+ if (this->MocRelaxedMode && (mocInc.Base == scanFileBase)) {
+ ownMocUscInclude = mocInc.Inc;
+ ownMocUscHeader = header;
+ }
+ } else {
+ std::string emsg = "The file includes the moc file ";
+ emsg += cmQtAutoGen::Quoted(mocInc.Inc);
+ emsg += ", but could not find the header ";
+ emsg += cmQtAutoGen::Quoted(this->MocStringHeaders(mocInc.Base));
+ this->LogFileError(cmQtAutoGen::MOC, absFilename, emsg);
+ return false;
+ }
+ }
+
+ // Process <BASE>.moc includes
+ for (const MocInc& mocInc : mocIncsDot) {
+ const bool ownMoc = (mocInc.Base == scanFileBase);
+ if (this->MocRelaxedMode) {
+ // Relaxed mode
+ if (selfRequiresMoc && ownMoc) {
+ // Add self
+ AddJob(absFilename, mocInc.Inc, &contentText);
+ ownDotMocIncluded = true;
} else {
- // Include: FOO.moc
- std::string fileToMoc;
- if (relaxed) {
- // Mode: Relaxed
- if (requiresMoc && (incBasename == scannedFileBasename)) {
- // Include self
- fileToMoc = absFilename;
- ownDotMocIncluded = true;
- } else {
- // In relaxed mode try to find a header instead but issue a warning
- const std::string headerToMoc =
- this->MocFindHeader(scannedFileAbsPath, incSubDir + incBasename);
- if (!headerToMoc.empty()) {
- if (!this->MocSkip(headerToMoc)) {
- // This is for KDE4 compatibility:
- fileToMoc = headerToMoc;
- if (!requiresMoc && (incBasename == scannedFileBasename)) {
- std::ostringstream ost;
- ost
- << "AutoMoc: Warning: " << Quoted(absFilename) << "\n"
- << "The file includes the moc file " << Quoted(incString)
- << ", but does not contain a Q_OBJECT or Q_GADGET macro.\n"
- << "Running moc on " << Quoted(headerToMoc) << "!\n"
- << "Include " << Quoted("moc_" + incBasename + ".cpp")
- << " for a compatibility with strict mode (see "
- "CMAKE_AUTOMOC_RELAXED_MODE).\n";
- this->LogWarning(ost.str());
- } else {
- std::ostringstream ost;
- ost << "AutoMoc: Warning: " << Quoted(absFilename) << "\n"
- << "The file includes the moc file " << Quoted(incString)
- << " instead of "
- << Quoted("moc_" + incBasename + ".cpp") << ".\n"
- << "Running moc on " << Quoted(headerToMoc) << "!\n"
- << "Include " << Quoted("moc_" + incBasename + ".cpp")
- << " for compatibility with strict mode (see "
- "CMAKE_AUTOMOC_RELAXED_MODE).\n";
- this->LogWarning(ost.str());
- }
- }
+ // In relaxed mode try to find a header instead but issue a warning.
+ // This is for KDE4 compatibility
+ std::string const header =
+ this->MocFindIncludedHeader(scanFileDir, mocInc.Dir + mocInc.Base);
+ if (!header.empty()) {
+ // Check if header is skipped
+ if (this->MocSkip(header)) {
+ continue;
+ }
+ // Register moc job
+ AddJob(header, mocInc.Inc, nullptr);
+ if (!selfRequiresMoc) {
+ if (ownMoc) {
+ std::string emsg = "The file includes the moc file ";
+ emsg += cmQtAutoGen::Quoted(mocInc.Inc);
+ emsg += ", but does not contain a ";
+ emsg += this->MocStringMacros();
+ emsg += " macro.\nRunning moc on\n ";
+ emsg += cmQtAutoGen::Quoted(header);
+ emsg += "!\nBetter include ";
+ emsg += cmQtAutoGen::Quoted("moc_" + mocInc.Base + ".cpp");
+ emsg += " for a compatibility with strict mode.\n"
+ "(CMAKE_AUTOMOC_RELAXED_MODE warning)\n";
+ this->LogFileWarning(cmQtAutoGen::MOC, absFilename, emsg);
} else {
- std::ostringstream ost;
- ost << "AutoMoc: Error: " << Quoted(absFilename) << "\n"
- << "The file includes the moc file " << Quoted(incString)
- << ", which seems to be the moc file from a different "
- "source file. CMake also could not find a matching "
- "header.";
- this->LogError(ost.str());
- return false;
+ std::string emsg = "The file includes the moc file ";
+ emsg += cmQtAutoGen::Quoted(mocInc.Inc);
+ emsg += " instead of ";
+ emsg += cmQtAutoGen::Quoted("moc_" + mocInc.Base + ".cpp");
+ emsg += ".\nRunning moc on\n ";
+ emsg += cmQtAutoGen::Quoted(header);
+ emsg += "!\nBetter include ";
+ emsg += cmQtAutoGen::Quoted("moc_" + mocInc.Base + ".cpp");
+ emsg += " for compatibility with strict mode.\n"
+ "(CMAKE_AUTOMOC_RELAXED_MODE warning)\n";
+ this->LogFileWarning(cmQtAutoGen::MOC, absFilename, emsg);
}
}
} else {
- // Mode: Strict
- if (incBasename == scannedFileBasename) {
- // Include self
- fileToMoc = absFilename;
- ownDotMocIncluded = true;
- // Accept but issue a warning if moc isn't required
- if (!requiresMoc) {
- std::ostringstream ost;
- ost << "AutoMoc: Warning: " << Quoted(absFilename) << "\n"
- << "The file includes the moc file " << Quoted(incString)
- << ", but does not contain a Q_OBJECT or Q_GADGET "
- "macro.";
- this->LogWarning(ost.str());
- }
- } else {
- // Don't allow FOO.moc include other than self in strict mode
- std::ostringstream ost;
- ost << "AutoMoc: Error: " << Quoted(absFilename) << "\n"
- << "The file includes the moc file " << Quoted(incString)
- << ", which seems to be the moc file from a different "
- "source file. This is not supported. Include "
- << Quoted(scannedFileBasename + ".moc")
- << " to run moc on this source file.";
- this->LogError(ost.str());
- return false;
- }
+ std::string emsg = "The file includes the moc file ";
+ emsg += cmQtAutoGen::Quoted(mocInc.Inc);
+ emsg += ", which seems to be the moc file from a different "
+ "source file. CMake also could not find a matching "
+ "header.";
+ this->LogFileError(cmQtAutoGen::MOC, absFilename, emsg);
+ return false;
}
- if (!fileToMoc.empty()) {
- mocsIncluded[fileToMoc] = incString;
- this->MocFindDepends(fileToMoc, contentText, mocDepends);
+ }
+ } else {
+ // Strict mode
+ if (ownMoc) {
+ // Include self
+ AddJob(absFilename, mocInc.Inc, &contentText);
+ ownDotMocIncluded = true;
+ // Accept but issue a warning if moc isn't required
+ if (!selfRequiresMoc) {
+ std::string emsg = "The file includes the moc file ";
+ emsg += cmQtAutoGen::Quoted(mocInc.Inc);
+ emsg += ", but does not contain a ";
+ emsg += this->MocStringMacros();
+ emsg += " macro.";
+ this->LogFileWarning(cmQtAutoGen::MOC, absFilename, emsg);
}
+ } else {
+ // Don't allow <BASE>.moc include other than self in strict mode
+ std::string emsg = "The file includes the moc file ";
+ emsg += cmQtAutoGen::Quoted(mocInc.Inc);
+ emsg += ", which seems to be the moc file from a different "
+ "source file.\nThis is not supported. Include ";
+ emsg += cmQtAutoGen::Quoted(scanFileBase + ".moc");
+ emsg += " to run moc on this source file.";
+ this->LogFileError(cmQtAutoGen::MOC, absFilename, emsg);
+ return false;
}
- // Forward content pointer
- contentChars += this->MocRegExpInclude.end();
}
}
- if (requiresMoc && !ownDotMocIncluded) {
+ if (selfRequiresMoc && !ownDotMocIncluded) {
// In this case, check whether the scanned file itself contains a Q_OBJECT.
// If this is the case, the moc_foo.cpp should probably be generated from
// foo.cpp instead of foo.h, because otherwise it won't build.
// But warn, since this is not how it is supposed to be used.
- if (relaxed && !ownMocUnderscoreInclude.empty()) {
+ if (this->MocRelaxedMode && !ownMocUscInclude.empty()) {
// This is for KDE4 compatibility:
- std::ostringstream ost;
- ost << "AutoMoc: Warning: " << Quoted(absFilename) << "\n"
- << "The file contains a " << macroName
- << " macro, but does not include "
- << Quoted(scannedFileBasename + ".moc") << ", but instead includes "
- << Quoted(ownMocUnderscoreInclude) << ".\n"
- << "Running moc on " << Quoted(absFilename) << "!\n"
- << "Better include " << Quoted(scannedFileBasename + ".moc")
- << " for compatibility with strict mode (see "
- "CMAKE_AUTOMOC_RELAXED_MODE).";
- this->LogWarning(ost.str());
-
- // Use scanned source file instead of scanned header file as moc source
- mocsIncluded[absFilename] = ownMocUnderscoreInclude;
- this->MocFindDepends(absFilename, contentText, mocDepends);
- // Remove
- mocsIncluded.erase(ownMocUnderscoreHeader);
+ std::string emsg = "The file contains a ";
+ emsg += selfMacroName;
+ emsg += " macro, but does not include ";
+ emsg += cmQtAutoGen::Quoted(scanFileBase + ".moc");
+ emsg += ". Instead it includes ";
+ emsg += cmQtAutoGen::Quoted(ownMocUscInclude);
+ emsg += ".\nRunning moc on\n ";
+ emsg += cmQtAutoGen::Quoted(absFilename);
+ emsg += "!\nBetter include ";
+ emsg += cmQtAutoGen::Quoted(scanFileBase + ".moc");
+ emsg += " for compatibility with strict mode.\n"
+ "(CMAKE_AUTOMOC_RELAXED_MODE warning)";
+ this->LogFileWarning(cmQtAutoGen::MOC, absFilename, emsg);
+
+ // Remove own header job
+ {
+ auto itC = this->MocJobsIncluded.begin();
+ auto itE = this->MocJobsIncluded.end();
+ for (; itC != itE; ++itC) {
+ if ((*itC)->SourceFile == ownMocUscHeader) {
+ if ((*itC)->IncludeString == ownMocUscInclude) {
+ this->MocJobsIncluded.erase(itC);
+ break;
+ }
+ }
+ }
+ }
+ // Add own source job
+ AddJob(absFilename, ownMocUscInclude, &contentText);
} else {
// Otherwise always error out since it will not compile:
- std::ostringstream ost;
- ost << "AutoMoc: Error: " << Quoted(absFilename) << "\n"
- << "The file contains a " << macroName
- << " macro, but does not include "
- << Quoted(scannedFileBasename + ".moc") << "!\n"
- << "Consider adding the include or enabling SKIP_AUTOMOC for this "
- "file.";
- this->LogError(ost.str());
+ std::string emsg = "The file contains a ";
+ emsg += selfMacroName;
+ emsg += " macro, but does not include ";
+ emsg += cmQtAutoGen::Quoted(scanFileBase + ".moc");
+ emsg += "!\nConsider to\n - add #include \"";
+ emsg += scanFileBase;
+ emsg += ".moc\"\n - enable SKIP_AUTOMOC for this file";
+ this->LogFileError(cmQtAutoGen::MOC, absFilename, emsg);
return false;
}
}
-
return true;
}
-void cmQtAutoGenerators::MocParseHeaderContent(
- const std::string& absFilename, const std::string& contentText,
- std::map<std::string, std::string>& mocsNotIncluded,
- std::map<std::string, std::set<std::string> >& mocDepends)
+void cmQtAutoGenerators::MocParseHeaderContent(std::string const& absFilename,
+ std::string const& contentText)
{
- // Log
if (this->Verbose) {
- this->LogInfo("AutoMoc: Checking " + absFilename);
- }
- if (this->MocRequired(contentText)) {
- // Register moc job
- mocsNotIncluded[absFilename] =
- this->ChecksumedPath(absFilename, "moc_", this->ConfigSuffix + ".cpp");
- this->MocFindDepends(absFilename, contentText, mocDepends);
- }
-}
-
-void cmQtAutoGenerators::SearchHeadersForSourceFile(
- const std::string& absFilename, std::set<std::string>& mocHeaderFiles,
- std::set<std::string>& uicHeaderFiles) const
-{
- std::string basepaths[2];
- {
- std::string bpath = SubDirPrefix(absFilename);
- bpath += cmsys::SystemTools::GetFilenameWithoutLastExtension(absFilename);
- // search for default header files and private header files
- basepaths[0] = bpath;
- basepaths[1] = bpath + "_p";
- }
-
- for (const std::string* bpit = cmArrayBegin(basepaths);
- bpit != cmArrayEnd(basepaths); ++bpit) {
- std::string headerName;
- if (this->FindHeader(headerName, *bpit)) {
- // Moc headers
- if (!this->MocSkip(absFilename) && !this->MocSkip(headerName)) {
- mocHeaderFiles.insert(headerName);
- }
- // Uic headers
- if (!this->UicSkip(absFilename) && !this->UicSkip(headerName)) {
- uicHeaderFiles.insert(headerName);
- }
- }
- }
-}
-
-bool cmQtAutoGenerators::ParseHeaders(
- const std::set<std::string>& mocHeaderFiles,
- const std::set<std::string>& uicHeaderFiles,
- const std::map<std::string, std::string>& mocsIncluded,
- std::map<std::string, std::string>& mocsNotIncluded,
- std::map<std::string, std::set<std::string> >& mocDepends,
- std::map<std::string, std::vector<std::string> >& uisIncluded)
-{
- bool success = true;
- // Merged header files list to read files only once
- std::set<std::string> headerFiles;
- headerFiles.insert(mocHeaderFiles.begin(), mocHeaderFiles.end());
- headerFiles.insert(uicHeaderFiles.begin(), uicHeaderFiles.end());
-
- for (std::set<std::string>::const_iterator hIt = headerFiles.begin();
- hIt != headerFiles.end(); ++hIt) {
- const std::string& headerName = *hIt;
- std::string contentText;
- if (ReadAll(contentText, headerName)) {
- // Parse header content for MOC
- if ((mocHeaderFiles.find(headerName) != mocHeaderFiles.end()) &&
- (mocsIncluded.find(headerName) == mocsIncluded.end())) {
- this->MocParseHeaderContent(headerName, contentText, mocsNotIncluded,
- mocDepends);
- }
- // Parse header content for UIC
- if (uicHeaderFiles.find(headerName) != uicHeaderFiles.end()) {
- this->UicParseContent(headerName, contentText, uisIncluded);
+ this->LogInfo(cmQtAutoGen::MOC, "Checking: " + absFilename);
+ }
+
+ auto const fit =
+ std::find_if(this->MocJobsIncluded.cbegin(), this->MocJobsIncluded.cend(),
+ [&absFilename](std::unique_ptr<MocJobIncluded> const& job) {
+ return job->SourceFile == absFilename;
+ });
+ if (fit == this->MocJobsIncluded.cend()) {
+ if (this->MocRequired(contentText)) {
+ auto job = cm::make_unique<MocJobAuto>();
+ job->SourceFile = absFilename;
+ {
+ std::string& bld = job->BuildFileRel;
+ bld = this->FilePathChecksum.getPart(absFilename);
+ bld += '/';
+ bld += "moc_";
+ bld += cmSystemTools::GetFilenameWithoutLastExtension(absFilename);
+ if (this->MultiConfig != cmQtAutoGen::SINGLE) {
+ bld += this->ConfigSuffix;
+ }
+ bld += ".cpp";
}
- } else {
- std::ostringstream ost;
- ost << "AutoGen: Error: Could not read header file:\n"
- << Quoted(headerName);
- this->LogError(ost.str());
- success = false;
- break;
+ this->MocFindDepends(absFilename, contentText, job->Depends);
+ this->MocJobsAuto.push_back(std::move(job));
}
}
- return success;
}
-bool cmQtAutoGenerators::MocGenerateAll(
- const std::map<std::string, std::string>& mocsIncluded,
- const std::map<std::string, std::string>& mocsNotIncluded,
- const std::map<std::string, std::set<std::string> >& mocDepends)
+bool cmQtAutoGenerators::MocGenerateAll()
{
if (!this->MocEnabled()) {
return true;
}
- // Look for name collisions
+ // Look for name collisions in included moc files
{
- std::multimap<std::string, std::string> collisions;
- // Test merged map of included and notIncluded
- std::map<std::string, std::string> mergedMocs(mocsIncluded);
- mergedMocs.insert(mocsNotIncluded.begin(), mocsNotIncluded.end());
- if (this->NameCollisionTest(mergedMocs, collisions)) {
- std::ostringstream ost;
- ost << "AutoMoc: Error: "
- "The same moc file will be generated "
- "from different sources.\n"
- "To avoid this error either\n"
- "- rename the source files or\n"
- "- do not include the (moc_NAME.cpp|NAME.moc) file";
- this->LogErrorNameCollision(ost.str(), collisions);
+ bool collision = false;
+ std::map<std::string, std::vector<MocJobIncluded const*>> collisions;
+ for (auto const& job : this->MocJobsIncluded) {
+ auto& list = collisions[job->IncludeString];
+ if (!list.empty()) {
+ collision = true;
+ }
+ list.push_back(job.get());
+ }
+ if (collision) {
+ std::string emsg =
+ "Included moc files with the same name will be "
+ "generated from different sources.\n"
+ "Consider to\n"
+ " - not include the \"moc_<NAME>.cpp\" file\n"
+ " - add a directory prefix to a \"<NAME>.moc\" include "
+ "(e.g \"sub/<NAME>.moc\")\n"
+ " - rename the source file(s)\n"
+ "Include conflicts\n"
+ "-----------------\n";
+ const auto& colls = collisions;
+ for (auto const& coll : colls) {
+ if (coll.second.size() > 1) {
+ emsg += cmQtAutoGen::Quoted(coll.first);
+ emsg += " included in\n";
+ for (const MocJobIncluded* job : coll.second) {
+ emsg += " - ";
+ emsg += cmQtAutoGen::Quoted(job->Includer);
+ emsg += "\n";
+ }
+ emsg += "would be generated from\n";
+ for (const MocJobIncluded* job : coll.second) {
+ emsg += " - ";
+ emsg += cmQtAutoGen::Quoted(job->SourceFile);
+ emsg += "\n";
+ }
+ }
+ }
+ this->LogError(cmQtAutoGen::MOC, emsg);
return false;
}
}
- // Generate moc_predefs
+ // (Re)generate moc_predefs.h on demand
if (!this->MocPredefsCmd.empty()) {
if (this->MocSettingsChanged ||
- FileAbsentOrOlder(this->MocPredefsFileAbs, this->SettingsFile)) {
- this->LogBold("Generating MOC predefs " + this->MocPredefsFileRel);
+ !cmSystemTools::FileExists(this->MocPredefsFileAbs)) {
+ if (this->Verbose) {
+ this->LogBold("Generating MOC predefs " + this->MocPredefsFileRel);
+ }
std::string output;
{
@@ -1263,149 +1396,200 @@ bool cmQtAutoGenerators::MocGenerateAll(
cmd.insert(cmd.end(), this->MocIncludes.begin(),
this->MocIncludes.end());
// Add definitions
- for (std::vector<std::string>::const_iterator it =
- this->MocDefinitions.begin();
- it != this->MocDefinitions.end(); ++it) {
- cmd.push_back("-D" + (*it));
+ for (std::string const& def : this->MocDefinitions) {
+ cmd.push_back("-D" + def);
}
// Execute command
- if (!this->RunCommand(cmd, output, false)) {
- {
- std::ostringstream ost;
- ost << "AutoMoc: Error: moc predefs generation command failed\n";
- ost << "AutoMoc: Command:\n" << QuotedCommand(cmd) << "\n";
- ost << "AutoMoc: Command output:\n" << output << "\n";
- this->LogError(ost.str());
- }
+ if (!this->RunCommand(cmd, output)) {
+ this->LogCommandError(cmQtAutoGen::MOC,
+ "moc_predefs generation failed", cmd, output);
return false;
}
}
+
// (Re)write predefs file only on demand
if (this->FileDiffers(this->MocPredefsFileAbs, output)) {
- if (this->FileWrite("AutoMoc", this->MocPredefsFileAbs, output)) {
+ if (this->FileWrite(cmQtAutoGen::MOC, this->MocPredefsFileAbs,
+ output)) {
this->MocPredefsChanged = true;
} else {
+ this->LogFileError(cmQtAutoGen::MOC, this->MocPredefsFileAbs,
+ "moc_predefs file writing failed");
return false;
}
+ } else {
+ // Touch to update the time stamp
+ if (this->Verbose) {
+ this->LogInfo(cmQtAutoGen::MOC,
+ "Touching moc_predefs " + this->MocPredefsFileRel);
+ }
+ cmSystemTools::Touch(this->MocPredefsFileAbs, false);
}
}
+
+ // Add moc_predefs.h to moc file dependecies
+ for (auto const& item : this->MocJobsIncluded) {
+ item->Depends.insert(this->MocPredefsFileAbs);
+ }
+ for (auto const& item : this->MocJobsAuto) {
+ item->Depends.insert(this->MocPredefsFileAbs);
+ }
}
// Generate moc files that are included by source files.
- for (std::map<std::string, std::string>::const_iterator it =
- mocsIncluded.begin();
- it != mocsIncluded.end(); ++it) {
- if (!this->MocGenerateFile(it->first, it->second, mocDepends, true)) {
- if (this->MocRunFailed) {
- return false;
- }
+ for (auto const& item : this->MocJobsIncluded) {
+ if (!this->MocGenerateFile(*item)) {
+ return false;
}
}
-
// Generate moc files that are _not_ included by source files.
- bool mocCompFileGenerated = false;
- for (std::map<std::string, std::string>::const_iterator it =
- mocsNotIncluded.begin();
- it != mocsNotIncluded.end(); ++it) {
- if (this->MocGenerateFile(it->first, it->second, mocDepends, false)) {
- mocCompFileGenerated = true;
- } else {
- if (this->MocRunFailed) {
- return false;
- }
+ bool autoNameGenerated = false;
+ for (auto const& item : this->MocJobsAuto) {
+ if (!this->MocGenerateFile(*item, &autoNameGenerated)) {
+ return false;
}
}
// Compose mocs compilation file content
- std::string automocSource;
{
- std::ostringstream ost;
- ost << "/* This file is autogenerated, do not edit*/\n";
- if (mocsNotIncluded.empty()) {
- // Dummy content
- ost << "enum some_compilers { need_more_than_nothing };\n";
+ std::string mocs =
+ "// This file is autogenerated. Changes will be overwritten.\n";
+ if (this->MocJobsAuto.empty()) {
+ // Placeholder content
+ mocs +=
+ "// No files found that require moc or the moc files are included\n";
+ mocs += "enum some_compilers { need_more_than_nothing };\n";
} else {
// Valid content
- for (std::map<std::string, std::string>::const_iterator it =
- mocsNotIncluded.begin();
- it != mocsNotIncluded.end(); ++it) {
- ost << "#include \"" << it->second << "\"\n";
+ for (const auto& item : this->MocJobsAuto) {
+ mocs += "#include \"";
+ mocs += item->BuildFileRel;
+ mocs += "\"\n";
}
}
- automocSource = ost.str();
- }
- if (this->FileDiffers(this->MocCompFileAbs, automocSource)) {
- // Actually write mocs compilation file
- this->LogBold("Generating MOC compilation " + this->MocCompFileRel);
- if (!this->FileWrite("AutoMoc", this->MocCompFileAbs, automocSource)) {
- return false;
- }
- } else if (mocCompFileGenerated) {
- // Only touch mocs compilation file
- if (this->Verbose) {
- this->LogInfo("Touching MOC compilation " + this->MocCompFileRel);
+ if (this->FileDiffers(this->MocCompFileAbs, mocs)) {
+ // Actually write mocs compilation file
+ if (this->Verbose) {
+ this->LogBold("Generating MOC compilation " + this->MocCompFileRel);
+ }
+ if (!this->FileWrite(cmQtAutoGen::MOC, this->MocCompFileAbs, mocs)) {
+ this->LogFileError(cmQtAutoGen::MOC, this->MocCompFileAbs,
+ "mocs compilation file writing failed");
+ return false;
+ }
+ } else if (autoNameGenerated) {
+ // Only touch mocs compilation file
+ if (this->Verbose) {
+ this->LogInfo(cmQtAutoGen::MOC,
+ "Touching mocs compilation " + this->MocCompFileRel);
+ }
+ cmSystemTools::Touch(this->MocCompFileAbs, false);
}
- cmSystemTools::Touch(this->MocCompFileAbs, false);
}
return true;
}
/**
- * @return True if a moc file was created. False may indicate an error.
+ * @return True on success
*/
-bool cmQtAutoGenerators::MocGenerateFile(
- const std::string& sourceFile, const std::string& mocFileName,
- const std::map<std::string, std::set<std::string> >& mocDepends,
- bool included)
+bool cmQtAutoGenerators::MocGenerateFile(const MocJobAuto& mocJob,
+ bool* generated)
{
- bool mocGenerated = false;
- bool generateMoc = this->MocSettingsChanged || this->MocPredefsChanged;
-
- const std::string mocFileRel =
- included ? (this->AutogenIncludeDir + mocFileName) : mocFileName;
- const std::string mocFileAbs =
- cmSystemTools::CollapseCombinedPath(this->AutogenBuildDir, mocFileRel);
-
- if (!generateMoc) {
- // Test if the source file is newer that the build file
- generateMoc = FileAbsentOrOlder(mocFileAbs, sourceFile);
- if (!generateMoc) {
- // Test if a dependency file changed
- std::map<std::string, std::set<std::string> >::const_iterator dit =
- mocDepends.find(sourceFile);
- if (dit != mocDepends.end()) {
- for (std::set<std::string>::const_iterator fit = dit->second.begin();
- fit != dit->second.end(); ++fit) {
- if (FileAbsentOrOlder(mocFileAbs, *fit)) {
- generateMoc = true;
- break;
- }
+ bool success = true;
+
+ std::string const mocFileAbs = cmSystemTools::CollapseCombinedPath(
+ this->AutogenBuildDir, mocJob.BuildFileRel);
+
+ bool generate = false;
+ std::string generateReason;
+ if (!generate && !cmSystemTools::FileExists(mocFileAbs.c_str())) {
+ if (this->Verbose) {
+ generateReason = "Generating ";
+ generateReason += cmQtAutoGen::Quoted(mocFileAbs);
+ generateReason += " from its source file ";
+ generateReason += cmQtAutoGen::Quoted(mocJob.SourceFile);
+ generateReason += " because it doesn't exist";
+ }
+ generate = true;
+ }
+ if (!generate && this->MocSettingsChanged) {
+ if (this->Verbose) {
+ generateReason = "Generating ";
+ generateReason += cmQtAutoGen::Quoted(mocFileAbs);
+ generateReason += " from ";
+ generateReason += cmQtAutoGen::Quoted(mocJob.SourceFile);
+ generateReason += " because the MOC settings changed";
+ }
+ generate = true;
+ }
+ if (!generate && this->MocPredefsChanged) {
+ if (this->Verbose) {
+ generateReason = "Generating ";
+ generateReason += cmQtAutoGen::Quoted(mocFileAbs);
+ generateReason += " from ";
+ generateReason += cmQtAutoGen::Quoted(mocJob.SourceFile);
+ generateReason += " because moc_predefs.h changed";
+ }
+ generate = true;
+ }
+ if (!generate) {
+ std::string error;
+ if (FileIsOlderThan(mocFileAbs, mocJob.SourceFile, &error)) {
+ if (this->Verbose) {
+ generateReason = "Generating ";
+ generateReason += cmQtAutoGen::Quoted(mocFileAbs);
+ generateReason += " because it's older than its source file ";
+ generateReason += cmQtAutoGen::Quoted(mocJob.SourceFile);
+ }
+ generate = true;
+ } else {
+ if (!error.empty()) {
+ this->LogError(cmQtAutoGen::MOC, error);
+ success = false;
+ }
+ }
+ }
+ if (success && !generate) {
+ // Test if a dependency file is newer
+ std::string error;
+ for (std::string const& depFile : mocJob.Depends) {
+ if (FileIsOlderThan(mocFileAbs, depFile, &error)) {
+ if (this->Verbose) {
+ generateReason = "Generating ";
+ generateReason += cmQtAutoGen::Quoted(mocFileAbs);
+ generateReason += " from ";
+ generateReason += cmQtAutoGen::Quoted(mocJob.SourceFile);
+ generateReason += " because it is older than ";
+ generateReason += cmQtAutoGen::Quoted(depFile);
}
+ generate = true;
+ break;
+ }
+ if (!error.empty()) {
+ this->LogError(cmQtAutoGen::MOC, error);
+ success = false;
+ break;
}
}
}
- if (generateMoc) {
+
+ if (generate) {
// Log
- this->LogBold("Generating MOC source " + mocFileRel);
+ if (this->Verbose) {
+ this->LogBold("Generating MOC source " + mocJob.BuildFileRel);
+ this->LogInfo(cmQtAutoGen::MOC, generateReason);
+ }
// Make sure the parent directory exists
- if (this->MakeParentDirectory("AutoMoc", mocFileAbs)) {
+ if (this->MakeParentDirectory(cmQtAutoGen::MOC, mocFileAbs)) {
// Compose moc command
std::vector<std::string> cmd;
cmd.push_back(this->MocExecutable);
- // Add includes
- cmd.insert(cmd.end(), this->MocIncludes.begin(),
- this->MocIncludes.end());
- // Add definitions
- for (std::vector<std::string>::const_iterator it =
- this->MocDefinitions.begin();
- it != this->MocDefinitions.end(); ++it) {
- cmd.push_back("-D" + (*it));
- }
// Add options
- cmd.insert(cmd.end(), this->MocOptions.begin(), this->MocOptions.end());
+ cmd.insert(cmd.end(), this->MocAllOptions.begin(),
+ this->MocAllOptions.end());
// Add predefs include
if (!this->MocPredefsFileAbs.empty()) {
cmd.push_back("--include");
@@ -1413,47 +1597,119 @@ bool cmQtAutoGenerators::MocGenerateFile(
}
cmd.push_back("-o");
cmd.push_back(mocFileAbs);
- cmd.push_back(sourceFile);
+ cmd.push_back(mocJob.SourceFile);
// Execute moc command
std::string output;
if (this->RunCommand(cmd, output)) {
// Success
- mocGenerated = true;
+ if (generated != nullptr) {
+ *generated = true;
+ }
} else {
- // Command failed
+ // Moc command failed
{
- std::ostringstream ost;
- ost << "AutoMoc: Error: moc process failed for\n";
- ost << Quoted(mocFileRel) << "\n";
- ost << "AutoMoc: Command:\n" << QuotedCommand(cmd) << "\n";
- ost << "AutoMoc: Command output:\n" << output << "\n";
- this->LogError(ost.str());
+ std::string emsg = "moc failed for\n ";
+ emsg += cmQtAutoGen::Quoted(mocJob.SourceFile);
+ this->LogCommandError(cmQtAutoGen::MOC, emsg, cmd, output);
}
cmSystemTools::RemoveFile(mocFileAbs);
- this->MocRunFailed = true;
+ success = false;
}
} else {
// Parent directory creation failed
- this->MocRunFailed = true;
+ success = false;
+ }
+ }
+ return success;
+}
+
+/**
+ * @brief Tests if the file name is in the skip list
+ */
+bool cmQtAutoGenerators::UicSkip(std::string const& absFilename) const
+{
+ if (this->UicEnabled()) {
+ // Test if the file name is on the skip list
+ if (!ListContains(this->UicSkipList, absFilename)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool cmQtAutoGenerators::UicParseContent(std::string const& absFilename,
+ std::string const& contentText)
+{
+ if (this->Verbose) {
+ this->LogInfo(cmQtAutoGen::UIC, "Checking: " + absFilename);
+ }
+
+ std::vector<std::string> includes;
+ // Extracte includes
+ {
+ const char* contentChars = contentText.c_str();
+ if (strstr(contentChars, "ui_") != nullptr) {
+ while (this->UicRegExpInclude.find(contentChars)) {
+ includes.push_back(this->UicRegExpInclude.match(1));
+ contentChars += this->UicRegExpInclude.end();
+ }
+ }
+ }
+
+ for (std::string const& includeString : includes) {
+ std::string uiInputFile;
+ if (!UicFindIncludedFile(uiInputFile, absFilename, includeString)) {
+ return false;
+ }
+ // Check if this file should be skipped
+ if (this->UicSkip(uiInputFile)) {
+ continue;
+ }
+ // Check if the job already exists
+ bool jobExists = false;
+ for (const auto& job : this->UicJobs) {
+ if ((job->SourceFile == uiInputFile) &&
+ (job->IncludeString == includeString)) {
+ jobExists = true;
+ break;
+ }
+ }
+ if (!jobExists) {
+ auto job = cm::make_unique<UicJob>();
+ job->SourceFile = uiInputFile;
+ job->BuildFileRel = this->AutogenIncludeDir;
+ job->BuildFileRel += includeString;
+ job->Includer = absFilename;
+ job->IncludeString = includeString;
+ this->UicJobs.push_back(std::move(job));
}
}
- return mocGenerated;
+
+ return true;
}
bool cmQtAutoGenerators::UicFindIncludedFile(std::string& absFile,
- const std::string& sourceFile,
- const std::string& searchPath,
- const std::string& searchFile)
+ std::string const& sourceFile,
+ std::string const& includeString)
{
bool success = false;
- std::vector<std::string> testFiles;
+ std::string searchFile =
+ cmSystemTools::GetFilenameWithoutLastExtension(includeString).substr(3);
+ searchFile += ".ui";
// Collect search paths list
+ std::vector<std::string> testFiles;
{
- const std::string searchFileFull = searchPath + searchFile;
+ std::string const searchPath = SubDirPrefix(includeString);
+
+ std::string searchFileFull;
+ if (!searchPath.empty()) {
+ searchFileFull = searchPath;
+ searchFileFull += searchFile;
+ }
// Vicinity of the source
{
- const std::string sourcePath = SubDirPrefix(sourceFile);
+ std::string const sourcePath = SubDirPrefix(sourceFile);
testFiles.push_back(sourcePath + searchFile);
if (!searchPath.empty()) {
testFiles.push_back(sourcePath + searchFileFull);
@@ -1461,27 +1717,21 @@ bool cmQtAutoGenerators::UicFindIncludedFile(std::string& absFile,
}
// AUTOUIC search paths
if (!this->UicSearchPaths.empty()) {
- for (std::vector<std::string>::const_iterator iit =
- this->UicSearchPaths.begin();
- iit != this->UicSearchPaths.end(); ++iit) {
- testFiles.push_back(*iit + "/" + searchFile);
+ for (std::string const& sPath : this->UicSearchPaths) {
+ testFiles.push_back((sPath + "/").append(searchFile));
}
if (!searchPath.empty()) {
- for (std::vector<std::string>::const_iterator iit =
- this->UicSearchPaths.begin();
- iit != this->UicSearchPaths.end(); ++iit) {
- testFiles.push_back(*iit + "/" + searchFileFull);
+ for (std::string const& sPath : this->UicSearchPaths) {
+ testFiles.push_back((sPath + "/").append(searchFileFull));
}
}
}
}
// Search for the .ui file!
- for (std::vector<std::string>::const_iterator iit = testFiles.begin();
- iit != testFiles.end(); ++iit) {
- const std::string& testFile = *iit;
- if (cmsys::SystemTools::FileExists(testFile.c_str())) {
- absFile = cmsys::SystemTools::GetRealPath(testFile);
+ for (std::string const& testFile : testFiles) {
+ if (cmSystemTools::FileExists(testFile.c_str())) {
+ absFile = cmSystemTools::GetRealPath(testFile);
success = true;
break;
}
@@ -1489,84 +1739,75 @@ bool cmQtAutoGenerators::UicFindIncludedFile(std::string& absFile,
// Log error
if (!success) {
- std::ostringstream ost;
- ost << "AutoUic: Error: " << Quoted(sourceFile) << "\n";
- ost << "Could not find " << Quoted(searchFile) << " in\n";
- for (std::vector<std::string>::const_iterator iit = testFiles.begin();
- iit != testFiles.end(); ++iit) {
- ost << " " << Quoted(*iit) << "\n";
+ std::string emsg = "Could not find ";
+ emsg += cmQtAutoGen::Quoted(searchFile);
+ emsg += " in\n";
+ for (std::string const& testFile : testFiles) {
+ emsg += " ";
+ emsg += cmQtAutoGen::Quoted(testFile);
+ emsg += "\n";
}
- this->LogError(ost.str());
+ this->LogFileError(cmQtAutoGen::UIC, sourceFile, emsg);
}
return success;
}
-bool cmQtAutoGenerators::UicGenerateAll(
- const std::map<std::string, std::vector<std::string> >& uisIncluded)
+bool cmQtAutoGenerators::UicGenerateAll()
{
if (!this->UicEnabled()) {
return true;
}
- // single map with input / output names
- std::map<std::string, std::map<std::string, std::string> > sourceGenMap;
+ // Look for name collisions in included uic files
{
- // Collision lookup map
- std::map<std::string, std::string> testMap;
- // Compile maps
- for (std::map<std::string, std::vector<std::string> >::const_iterator sit =
- uisIncluded.begin();
- sit != uisIncluded.end(); ++sit) {
- const std::string& source(sit->first);
- const std::vector<std::string>& sourceIncs(sit->second);
- // insert new source/destination map
- std::map<std::string, std::string>& uiGenMap = sourceGenMap[source];
- for (std::vector<std::string>::const_iterator uit = sourceIncs.begin();
- uit != sourceIncs.end(); ++uit) {
- // Remove ui_ from the begin filename by substr()
- const std::string uiBasePath = SubDirPrefix(*uit);
- const std::string uiBaseName =
- cmsys::SystemTools::GetFilenameWithoutLastExtension(*uit).substr(3);
- const std::string uiFileName = uiBaseName + ".ui";
- std::string uiInputFile;
- if (UicFindIncludedFile(uiInputFile, source, uiBasePath, uiFileName)) {
- std::string uiOutputFile = uiBasePath + "ui_" + uiBaseName + ".h";
- cmSystemTools::ReplaceString(uiOutputFile, "..", "__");
- uiGenMap[uiInputFile] = uiOutputFile;
- testMap[uiInputFile] = uiOutputFile;
- } else {
- return false;
- }
+ bool collision = false;
+ std::map<std::string, std::vector<UicJob const*>> collisions;
+ for (auto const& job : this->UicJobs) {
+ auto& list = collisions[job->IncludeString];
+ if (!list.empty()) {
+ collision = true;
}
- }
- // look for name collisions
- {
- std::multimap<std::string, std::string> collisions;
- if (this->NameCollisionTest(testMap, collisions)) {
- std::ostringstream ost;
- ost << "AutoUic: Error: The same ui_NAME.h file will be generated "
- "from different sources.\n"
- "To avoid this error rename the source files.\n";
- this->LogErrorNameCollision(ost.str(), collisions);
- return false;
+ list.push_back(job.get());
+ }
+ if (collision) {
+ std::string emsg =
+ "Included uic files with the same name will be "
+ "generated from different sources.\n"
+ "Consider to\n"
+ " - add a directory prefix to a \"ui_<NAME>.h\" include "
+ "(e.g \"sub/ui_<NAME>.h\")\n"
+ " - rename the <NAME>.ui file(s) and adjust the \"ui_<NAME>.h\" "
+ "include(s)\n"
+ "Include conflicts\n"
+ "-----------------\n";
+ const auto& colls = collisions;
+ for (auto const& coll : colls) {
+ if (coll.second.size() > 1) {
+ emsg += cmQtAutoGen::Quoted(coll.first);
+ emsg += " included in\n";
+ for (const UicJob* job : coll.second) {
+ emsg += " - ";
+ emsg += cmQtAutoGen::Quoted(job->Includer);
+ emsg += "\n";
+ }
+ emsg += "would be generated from\n";
+ for (const UicJob* job : coll.second) {
+ emsg += " - ";
+ emsg += cmQtAutoGen::Quoted(job->SourceFile);
+ emsg += "\n";
+ }
+ }
}
+ this->LogError(cmQtAutoGen::UIC, emsg);
+ return false;
}
}
- // generate ui files
- for (std::map<std::string,
- std::map<std::string, std::string> >::const_iterator it =
- sourceGenMap.begin();
- it != sourceGenMap.end(); ++it) {
- for (std::map<std::string, std::string>::const_iterator sit =
- it->second.begin();
- sit != it->second.end(); ++sit) {
- if (!this->UicGenerateFile(it->first, sit->first, sit->second)) {
- if (this->UicRunFailed) {
- return false;
- }
- }
+ // Generate ui header files
+ for (const auto& item : this->UicJobs) {
+ if (!this->UicGenerateFile(*item)) {
+ return false;
}
}
@@ -1574,71 +1815,100 @@ bool cmQtAutoGenerators::UicGenerateAll(
}
/**
- * @return True if a uic file was created. False may indicate an error.
+ * @return True on success
*/
-bool cmQtAutoGenerators::UicGenerateFile(const std::string& realName,
- const std::string& uiInputFile,
- const std::string& uiOutputFile)
+bool cmQtAutoGenerators::UicGenerateFile(const UicJob& uicJob)
{
- bool uicGenerated = false;
- bool generateUic = this->UicSettingsChanged;
+ bool success = true;
- const std::string uicFileRel = this->AutogenIncludeDir + uiOutputFile;
- const std::string uicFileAbs =
- cmSystemTools::CollapseCombinedPath(this->AutogenBuildDir, uicFileRel);
+ std::string const uicFileAbs = cmSystemTools::CollapseCombinedPath(
+ this->AutogenBuildDir, uicJob.BuildFileRel);
- if (!generateUic) {
- // Test if the source file is newer that the build file
- generateUic = FileAbsentOrOlder(uicFileAbs, uiInputFile);
+ bool generate = false;
+ std::string generateReason;
+ if (!generate && !cmSystemTools::FileExists(uicFileAbs.c_str())) {
+ if (this->Verbose) {
+ generateReason = "Generating ";
+ generateReason += cmQtAutoGen::Quoted(uicFileAbs);
+ generateReason += " from its source file ";
+ generateReason += cmQtAutoGen::Quoted(uicJob.SourceFile);
+ generateReason += " because it doesn't exist";
+ }
+ generate = true;
+ }
+ if (!generate && this->UicSettingsChanged) {
+ if (this->Verbose) {
+ generateReason = "Generating ";
+ generateReason += cmQtAutoGen::Quoted(uicFileAbs);
+ generateReason += " from ";
+ generateReason += cmQtAutoGen::Quoted(uicJob.SourceFile);
+ generateReason += " because the UIC settings changed";
+ }
+ generate = true;
+ }
+ if (!generate) {
+ std::string error;
+ if (FileIsOlderThan(uicFileAbs, uicJob.SourceFile, &error)) {
+ if (this->Verbose) {
+ generateReason = "Generating ";
+ generateReason += cmQtAutoGen::Quoted(uicFileAbs);
+ generateReason += " because it's older than its source file ";
+ generateReason += cmQtAutoGen::Quoted(uicJob.SourceFile);
+ }
+ generate = true;
+ } else {
+ if (!error.empty()) {
+ this->LogError(cmQtAutoGen::UIC, error);
+ success = false;
+ }
+ }
}
- if (generateUic) {
+ if (generate) {
// Log
- this->LogBold("Generating UIC header " + uicFileRel);
+ if (this->Verbose) {
+ this->LogBold("Generating UIC header " + uicJob.BuildFileRel);
+ this->LogInfo(cmQtAutoGen::UIC, generateReason);
+ }
// Make sure the parent directory exists
- if (this->MakeParentDirectory("AutoUic", uicFileAbs)) {
+ if (this->MakeParentDirectory(cmQtAutoGen::UIC, uicFileAbs)) {
// Compose uic command
std::vector<std::string> cmd;
cmd.push_back(this->UicExecutable);
{
std::vector<std::string> allOpts = this->UicTargetOptions;
- std::map<std::string, std::string>::const_iterator optionIt =
- this->UicOptions.find(uiInputFile);
+ auto optionIt = this->UicOptions.find(uicJob.SourceFile);
if (optionIt != this->UicOptions.end()) {
- std::vector<std::string> fileOpts;
- cmSystemTools::ExpandListArgument(optionIt->second, fileOpts);
- UicMergeOptions(allOpts, fileOpts, (this->QtMajorVersion == "5"));
+ cmQtAutoGen::UicMergeOptions(allOpts, optionIt->second,
+ (this->QtMajorVersion == "5"));
}
cmd.insert(cmd.end(), allOpts.begin(), allOpts.end());
}
cmd.push_back("-o");
cmd.push_back(uicFileAbs);
- cmd.push_back(uiInputFile);
+ cmd.push_back(uicJob.SourceFile);
std::string output;
if (this->RunCommand(cmd, output)) {
// Success
- uicGenerated = true;
} else {
// Command failed
{
- std::ostringstream ost;
- ost << "AutoUic: Error: uic process failed for\n";
- ost << Quoted(uicFileRel) << " needed by\n";
- ost << Quoted(realName) << "\n";
- ost << "AutoUic: Command:\n" << QuotedCommand(cmd) << "\n";
- ost << "AutoUic: Command output:\n" << output << "\n";
- this->LogError(ost.str());
+ std::string emsg = "uic failed for\n ";
+ emsg += cmQtAutoGen::Quoted(uicJob.SourceFile);
+ emsg += "\nincluded by\n ";
+ emsg += cmQtAutoGen::Quoted(uicJob.Includer);
+ this->LogCommandError(cmQtAutoGen::UIC, emsg, cmd, output);
}
cmSystemTools::RemoveFile(uicFileAbs);
- this->UicRunFailed = true;
+ success = false;
}
} else {
// Parent directory creation failed
- this->UicRunFailed = true;
+ success = false;
}
}
- return uicGenerated;
+ return success;
}
bool cmQtAutoGenerators::RccGenerateAll()
@@ -1647,322 +1917,375 @@ bool cmQtAutoGenerators::RccGenerateAll()
return true;
}
- // generate single map with input / output names
- std::map<std::string, std::string> qrcGenMap;
- {
- const std::string qrcPrefix = "qrc_";
- const std::string qrcSuffix = this->ConfigSuffix + ".cpp";
- for (std::vector<std::string>::const_iterator si =
- this->RccSources.begin();
- si != this->RccSources.end(); ++si) {
- const std::string ext =
- cmsys::SystemTools::GetFilenameLastExtension(*si);
- if (ext == ".qrc") {
- qrcGenMap[*si] = this->ChecksumedPath(*si, qrcPrefix, qrcSuffix);
- }
- }
- }
-
- // look for name collisions
- {
- std::multimap<std::string, std::string> collisions;
- if (this->NameCollisionTest(qrcGenMap, collisions)) {
- std::ostringstream ost;
- ost << "AutoRcc: Error: The same qrc_NAME.cpp file"
- " will be generated from different sources.\n"
- "To avoid this error rename the source .qrc files.\n";
- this->LogErrorNameCollision(ost.str(), collisions);
+ // Generate rcc files
+ for (const RccJob& rccJob : this->RccJobs) {
+ if (!this->RccGenerateFile(rccJob)) {
return false;
}
}
-
- // generate qrc files
- for (std::map<std::string, std::string>::const_iterator si =
- qrcGenMap.begin();
- si != qrcGenMap.end(); ++si) {
- bool unique = FileNameIsUnique(si->first, qrcGenMap);
- if (!this->RccGenerateFile(si->first, si->second, unique)) {
- if (this->RccRunFailed) {
- return false;
- }
- }
- }
return true;
}
/**
- * @return True if a rcc file was created. False may indicate an error.
+ * @return True on success
*/
-bool cmQtAutoGenerators::RccGenerateFile(const std::string& rccInputFile,
- const std::string& rccOutputFile,
- bool unique_n)
+bool cmQtAutoGenerators::RccGenerateFile(const RccJob& rccJob)
{
+ bool success = true;
bool rccGenerated = false;
- bool generateRcc = this->RccSettingsChanged;
-
- const std::string rccBuildFile =
- cmSystemTools::CollapseCombinedPath(this->AutogenBuildDir, rccOutputFile);
-
- if (!generateRcc) {
- // Test if the resources list file is newer than build file
- generateRcc = FileAbsentOrOlder(rccBuildFile, rccInputFile);
- if (!generateRcc) {
- // Acquire input file list
- std::vector<std::string> readFiles;
- const std::vector<std::string>* files = &this->RccInputs[rccInputFile];
- if (files->empty()) {
- // Read input file list from qrc file
- std::string error;
- if (cmQtAutoGeneratorCommon::RccListInputs(
- this->QtMajorVersion, this->RccExecutable, rccInputFile,
- readFiles, &error)) {
- files = &readFiles;
- } else {
- files = CM_NULLPTR;
- this->LogError(error);
- this->RccRunFailed = true;
- }
+
+ std::string rccFileAbs;
+ {
+ std::string suffix;
+ switch (this->MultiConfig) {
+ case cmQtAutoGen::SINGLE:
+ break;
+ case cmQtAutoGen::WRAP:
+ suffix = "_CMAKE";
+ suffix += this->ConfigSuffix;
+ suffix += "_";
+ break;
+ case cmQtAutoGen::FULL:
+ suffix = this->ConfigSuffix;
+ break;
+ }
+ rccFileAbs = cmQtAutoGen::AppendFilenameSuffix(rccJob.RccFile, suffix);
+ }
+ std::string const rccFileRel = cmSystemTools::RelativePath(
+ this->AutogenBuildDir.c_str(), rccFileAbs.c_str());
+
+ // Check if regeneration is required
+ bool generate = false;
+ std::string generateReason;
+ if (!cmSystemTools::FileExists(rccJob.QrcFile)) {
+ {
+ std::string error = "Could not find the file\n ";
+ error += cmQtAutoGen::Quoted(rccJob.QrcFile);
+ this->LogError(cmQtAutoGen::RCC, error);
+ }
+ success = false;
+ }
+ if (success && !generate && !cmSystemTools::FileExists(rccFileAbs.c_str())) {
+ if (this->Verbose) {
+ generateReason = "Generating ";
+ generateReason += cmQtAutoGen::Quoted(rccFileAbs);
+ generateReason += " from its source file ";
+ generateReason += cmQtAutoGen::Quoted(rccJob.QrcFile);
+ generateReason += " because it doesn't exist";
+ }
+ generate = true;
+ }
+ if (success && !generate && this->RccSettingsChanged) {
+ if (this->Verbose) {
+ generateReason = "Generating ";
+ generateReason += cmQtAutoGen::Quoted(rccFileAbs);
+ generateReason += " from ";
+ generateReason += cmQtAutoGen::Quoted(rccJob.QrcFile);
+ generateReason += " because the RCC settings changed";
+ }
+ generate = true;
+ }
+ if (success && !generate) {
+ std::string error;
+ if (FileIsOlderThan(rccFileAbs, rccJob.QrcFile, &error)) {
+ if (this->Verbose) {
+ generateReason = "Generating ";
+ generateReason += cmQtAutoGen::Quoted(rccFileAbs);
+ generateReason += " because it is older than ";
+ generateReason += cmQtAutoGen::Quoted(rccJob.QrcFile);
+ }
+ generate = true;
+ } else {
+ if (!error.empty()) {
+ this->LogError(cmQtAutoGen::RCC, error);
+ success = false;
+ }
+ }
+ }
+ if (success && !generate) {
+ // Acquire input file list
+ std::vector<std::string> readFiles;
+ std::vector<std::string> const* files = nullptr;
+ if (!rccJob.Inputs.empty()) {
+ files = &rccJob.Inputs;
+ } else {
+ // Read input file list from qrc file
+ std::string error;
+ if (cmQtAutoGen::RccListInputs(this->QtMajorVersion, this->RccExecutable,
+ rccJob.QrcFile, readFiles, &error)) {
+ files = &readFiles;
+ } else {
+ this->LogFileError(cmQtAutoGen::RCC, rccJob.QrcFile, error);
+ success = false;
}
- // Test if any input file is newer than the build file
- if (files != CM_NULLPTR) {
- for (std::vector<std::string>::const_iterator it = files->begin();
- it != files->end(); ++it) {
- if (FileAbsentOrOlder(rccBuildFile, *it)) {
- generateRcc = true;
- break;
+ }
+ // Test if any input file is newer than the build file
+ if (files != nullptr) {
+ std::string error;
+ for (std::string const& resFile : *files) {
+ if (!cmSystemTools::FileExists(resFile.c_str())) {
+ error = "Could not find the file\n ";
+ error += cmQtAutoGen::Quoted(resFile);
+ error += "\nwhich is listed in\n ";
+ error += cmQtAutoGen::Quoted(rccJob.QrcFile);
+ break;
+ }
+ if (FileIsOlderThan(rccFileAbs, resFile, &error)) {
+ if (this->Verbose) {
+ generateReason = "Generating ";
+ generateReason += cmQtAutoGen::Quoted(rccFileAbs);
+ generateReason += " from ";
+ generateReason += cmQtAutoGen::Quoted(rccJob.QrcFile);
+ generateReason += " because it is older than ";
+ generateReason += cmQtAutoGen::Quoted(resFile);
}
+ generate = true;
+ break;
+ }
+ if (!error.empty()) {
+ break;
}
}
+ // Print error
+ if (!error.empty()) {
+ this->LogError(cmQtAutoGen::RCC, error);
+ success = false;
+ }
}
}
- if (generateRcc) {
+ // Regenerate on demand
+ if (generate) {
// Log
- this->LogBold("Generating RCC source " + rccOutputFile);
+ if (this->Verbose) {
+ this->LogBold("Generating RCC source " + rccFileRel);
+ this->LogInfo(cmQtAutoGen::RCC, generateReason);
+ }
// Make sure the parent directory exists
- if (this->MakeParentDirectory("AutoRcc", rccBuildFile)) {
- // Compose symbol name
- std::string symbolName =
- cmsys::SystemTools::GetFilenameWithoutLastExtension(rccInputFile);
- if (!unique_n) {
- symbolName += "_";
- symbolName += FPathChecksum.getPart(rccInputFile);
- }
- // Replace '-' with '_'. The former is valid for
- // file names but not for symbol names.
- std::replace(symbolName.begin(), symbolName.end(), '-', '_');
-
+ if (this->MakeParentDirectory(cmQtAutoGen::RCC, rccFileAbs)) {
// Compose rcc command
std::vector<std::string> cmd;
cmd.push_back(this->RccExecutable);
- {
- std::map<std::string, std::string>::const_iterator optionIt =
- this->RccOptions.find(rccInputFile);
- if (optionIt != this->RccOptions.end()) {
- cmSystemTools::ExpandListArgument(optionIt->second, cmd);
- }
- }
- cmd.push_back("-name");
- cmd.push_back(symbolName);
+ cmd.insert(cmd.end(), rccJob.Options.begin(), rccJob.Options.end());
cmd.push_back("-o");
- cmd.push_back(rccBuildFile);
- cmd.push_back(rccInputFile);
+ cmd.push_back(rccFileAbs);
+ cmd.push_back(rccJob.QrcFile);
std::string output;
if (this->RunCommand(cmd, output)) {
// Success
rccGenerated = true;
} else {
- // Command failed
{
- std::ostringstream ost;
- ost << "AutoRcc: Error: rcc process failed for\n";
- ost << Quoted(rccOutputFile) << "\n";
- ost << "AutoRcc: Command:\n" << QuotedCommand(cmd) << "\n";
- ost << "AutoRcc: Command output:\n" << output << "\n";
- this->LogError(ost.str());
+ std::string emsg = "rcc failed for\n ";
+ emsg += cmQtAutoGen::Quoted(rccJob.QrcFile);
+ this->LogCommandError(cmQtAutoGen::RCC, emsg, cmd, output);
}
- cmSystemTools::RemoveFile(rccBuildFile);
- this->RccRunFailed = true;
+ cmSystemTools::RemoveFile(rccFileAbs);
+ success = false;
}
} else {
// Parent directory creation failed
- this->RccRunFailed = true;
+ success = false;
}
}
- return rccGenerated;
-}
-void cmQtAutoGenerators::LogErrorNameCollision(
- const std::string& message,
- const std::multimap<std::string, std::string>& collisions) const
-{
- typedef std::multimap<std::string, std::string>::const_iterator Iter;
-
- std::ostringstream ost;
- // Add message
- if (!message.empty()) {
- ost << message;
- if (message[message.size() - 1] != '\n') {
- ost << '\n';
+ // Generate a wrapper source file on demand
+ if (success && (this->MultiConfig == cmQtAutoGen::WRAP)) {
+ // Wrapper file name
+ std::string const& wrapperFileAbs = rccJob.RccFile;
+ std::string const wrapperFileRel = cmSystemTools::RelativePath(
+ this->AutogenBuildDir.c_str(), wrapperFileAbs.c_str());
+ // Wrapper file content
+ std::string content = "// This is an autogenerated configuration "
+ "wrapper file. Changes will be overwritten.\n"
+ "#include \"";
+ content += cmSystemTools::GetFilenameName(rccFileRel);
+ content += "\"\n";
+ // Write content to file
+ if (this->FileDiffers(wrapperFileAbs, content)) {
+ // Write new wrapper file
+ if (this->Verbose) {
+ this->LogBold("Generating RCC wrapper " + wrapperFileRel);
+ }
+ if (!this->FileWrite(cmQtAutoGen::RCC, wrapperFileAbs, content)) {
+ this->LogFileError(cmQtAutoGen::RCC, wrapperFileAbs,
+ "rcc wrapper file writing failed");
+ success = false;
+ }
+ } else if (rccGenerated) {
+ // Just touch the wrapper file
+ if (this->Verbose) {
+ this->LogInfo(cmQtAutoGen::RCC,
+ "Touching RCC wrapper " + wrapperFileRel);
+ }
+ cmSystemTools::Touch(wrapperFileAbs, false);
}
}
- // Append collision list
- for (Iter it = collisions.begin(); it != collisions.end(); ++it) {
- ost << it->first << " : " << it->second << '\n';
- }
- this->LogError(ost.str());
+
+ return success;
}
-void cmQtAutoGenerators::LogBold(const std::string& message) const
+void cmQtAutoGenerators::LogBold(std::string const& message) const
{
cmSystemTools::MakefileColorEcho(cmsysTerminal_Color_ForegroundBlue |
cmsysTerminal_Color_ForegroundBold,
message.c_str(), true, this->ColorOutput);
}
-void cmQtAutoGenerators::LogInfo(const std::string& message) const
+void cmQtAutoGenerators::LogInfo(cmQtAutoGen::Generator genType,
+ std::string const& message) const
{
- std::string msg(message);
- if (!msg.empty()) {
- if (msg[msg.size() - 1] != '\n') {
- msg.push_back('\n');
- }
- cmSystemTools::Stdout(msg.c_str(), msg.size());
+ std::string msg = cmQtAutoGen::GeneratorName(genType);
+ msg += ": ";
+ msg += message;
+ if (msg.back() != '\n') {
+ msg.push_back('\n');
}
+ cmSystemTools::Stdout(msg.c_str(), msg.size());
}
-void cmQtAutoGenerators::LogWarning(const std::string& message) const
+void cmQtAutoGenerators::LogWarning(cmQtAutoGen::Generator genType,
+ std::string const& message) const
{
- std::string msg(message);
- if (!msg.empty()) {
- if (msg[msg.size() - 1] != '\n') {
- msg.push_back('\n');
- }
- // Append empty line
+ std::string msg = cmQtAutoGen::GeneratorName(genType);
+ msg += " warning:";
+ if (message.find('\n') == std::string::npos) {
+ // Single line message
+ msg.push_back(' ');
+ } else {
+ // Multi line message
+ msg.push_back('\n');
+ }
+ // Message
+ msg += message;
+ if (msg.back() != '\n') {
msg.push_back('\n');
- cmSystemTools::Stdout(msg.c_str(), msg.size());
}
+ msg.push_back('\n');
+ cmSystemTools::Stdout(msg.c_str(), msg.size());
}
-void cmQtAutoGenerators::LogError(const std::string& message) const
+void cmQtAutoGenerators::LogFileWarning(cmQtAutoGen::Generator genType,
+ std::string const& filename,
+ std::string const& message) const
{
- std::string msg(message);
- if (!msg.empty()) {
- if (msg[msg.size() - 1] != '\n') {
- msg.push_back('\n');
- }
- // Append empty line
- msg.push_back('\n');
- cmSystemTools::Stderr(msg.c_str(), msg.size());
- }
+ std::string msg = " ";
+ msg += cmQtAutoGen::Quoted(filename);
+ msg.push_back('\n');
+ // Message
+ msg += message;
+ this->LogWarning(genType, msg);
}
-/**
- * @brief Collects name collisions as output/input pairs
- * @return True if there were collisions
- */
-bool cmQtAutoGenerators::NameCollisionTest(
- const std::map<std::string, std::string>& genFiles,
- std::multimap<std::string, std::string>& collisions) const
+void cmQtAutoGenerators::LogError(cmQtAutoGen::Generator genType,
+ std::string const& message) const
{
- typedef std::map<std::string, std::string>::const_iterator Iter;
- typedef std::map<std::string, std::string>::value_type VType;
- for (Iter ait = genFiles.begin(); ait != genFiles.end(); ++ait) {
- bool first_match(true);
- for (Iter bit = (++Iter(ait)); bit != genFiles.end(); ++bit) {
- if (ait->second == bit->second) {
- if (first_match) {
- if (collisions.find(ait->second) != collisions.end()) {
- // We already know of this collision from before
- break;
- }
- collisions.insert(VType(ait->second, ait->first));
- first_match = false;
- }
- collisions.insert(VType(bit->second, bit->first));
- }
- }
+ std::string msg;
+ msg.push_back('\n');
+ msg += HeadLine(cmQtAutoGen::GeneratorName(genType) + " error");
+ // Message
+ msg += message;
+ if (msg.back() != '\n') {
+ msg.push_back('\n');
}
+ msg.push_back('\n');
+ cmSystemTools::Stderr(msg.c_str(), msg.size());
+}
- return !collisions.empty();
+void cmQtAutoGenerators::LogFileError(cmQtAutoGen::Generator genType,
+ std::string const& filename,
+ std::string const& message) const
+{
+ std::string emsg = " ";
+ emsg += cmQtAutoGen::Quoted(filename);
+ emsg += '\n';
+ // Message
+ emsg += message;
+ this->LogError(genType, emsg);
}
-/**
- * @brief Generates a file path based on the checksum of the source file path
- * @return The path
- */
-std::string cmQtAutoGenerators::ChecksumedPath(
- const std::string& sourceFile, const std::string& basePrefix,
- const std::string& baseSuffix) const
+void cmQtAutoGenerators::LogCommandError(
+ cmQtAutoGen::Generator genType, std::string const& message,
+ std::vector<std::string> const& command, std::string const& output) const
{
- std::string res = FPathChecksum.getPart(sourceFile);
- res += "/";
- res += basePrefix;
- res += cmsys::SystemTools::GetFilenameWithoutLastExtension(sourceFile);
- res += baseSuffix;
- return res;
+ std::string msg;
+ msg.push_back('\n');
+ msg += HeadLine(cmQtAutoGen::GeneratorName(genType) + " subprocess error");
+ msg += message;
+ if (msg.back() != '\n') {
+ msg.push_back('\n');
+ }
+ msg.push_back('\n');
+ msg += HeadLine("Command");
+ msg += QuotedCommand(command);
+ if (msg.back() != '\n') {
+ msg.push_back('\n');
+ }
+ msg.push_back('\n');
+ msg += HeadLine("Output");
+ msg += output;
+ if (msg.back() != '\n') {
+ msg.push_back('\n');
+ }
+ msg.push_back('\n');
+ cmSystemTools::Stderr(msg.c_str(), msg.size());
}
/**
* @brief Generates the parent directory of the given file on demand
* @return True on success
*/
-bool cmQtAutoGenerators::MakeParentDirectory(const char* logPrefix,
- const std::string& filename) const
+bool cmQtAutoGenerators::MakeParentDirectory(cmQtAutoGen::Generator genType,
+ std::string const& filename) const
{
bool success = true;
- const std::string dirName = cmSystemTools::GetFilenamePath(filename);
+ std::string const dirName = cmSystemTools::GetFilenamePath(filename);
if (!dirName.empty()) {
- success = cmsys::SystemTools::MakeDirectory(dirName);
- if (!success) {
- std::string error = logPrefix;
- error += ": Error: Parent directory creation failed for ";
- error += Quoted(filename);
- this->LogError(error);
+ if (!cmSystemTools::MakeDirectory(dirName)) {
+ this->LogFileError(genType, filename,
+ "Could not create parent directory");
+ success = false;
}
}
return success;
}
-bool cmQtAutoGenerators::FileDiffers(const std::string& filename,
- const std::string& content)
+bool cmQtAutoGenerators::FileDiffers(std::string const& filename,
+ std::string const& content)
{
bool differs = true;
{
std::string oldContents;
- if (ReadAll(oldContents, filename)) {
+ if (ReadFile(oldContents, filename)) {
differs = (oldContents != content);
}
}
return differs;
}
-bool cmQtAutoGenerators::FileWrite(const char* logPrefix,
- const std::string& filename,
- const std::string& content)
+bool cmQtAutoGenerators::FileWrite(cmQtAutoGen::Generator genType,
+ std::string const& filename,
+ std::string const& content)
{
std::string error;
// Make sure the parent directory exists
- if (this->MakeParentDirectory(logPrefix, filename)) {
+ if (this->MakeParentDirectory(genType, filename)) {
cmsys::ofstream outfile;
- outfile.open(filename.c_str(), std::ios::trunc);
+ outfile.open(filename.c_str(),
+ (std::ios::out | std::ios::binary | std::ios::trunc));
if (outfile) {
outfile << content;
// Check for write errors
if (!outfile.good()) {
- error = logPrefix;
- error += ": Error writing ";
- error += Quoted(filename);
+ error = "File writing failed";
}
} else {
- error = logPrefix;
- error = ": Error opening ";
- error += Quoted(filename);
+ error = "Opening file for writing failed";
}
}
if (!error.empty()) {
- this->LogError(error);
+ this->LogFileError(genType, filename, error);
return false;
}
return true;
@@ -1972,18 +2295,19 @@ bool cmQtAutoGenerators::FileWrite(const char* logPrefix,
* @brief Runs a command and returns true on success
* @return True on success
*/
-bool cmQtAutoGenerators::RunCommand(const std::vector<std::string>& command,
- std::string& output, bool verbose) const
+bool cmQtAutoGenerators::RunCommand(std::vector<std::string> const& command,
+ std::string& output) const
{
// Log command
if (this->Verbose) {
- this->LogInfo(QuotedCommand(command));
+ std::string qcmd = QuotedCommand(command);
+ qcmd.push_back('\n');
+ cmSystemTools::Stdout(qcmd.c_str(), qcmd.size());
}
// Execute command
int retVal = 0;
bool res = cmSystemTools::RunSingleCommand(
- command, &output, &output, &retVal, CM_NULLPTR,
- verbose ? cmSystemTools::OUTPUT_MERGE : cmSystemTools::OUTPUT_NONE);
+ command, &output, &output, &retVal, nullptr, cmSystemTools::OUTPUT_NONE);
return (res && (retVal == 0));
}
@@ -1993,71 +2317,16 @@ bool cmQtAutoGenerators::RunCommand(const std::vector<std::string>& command,
* @return True on success
*/
bool cmQtAutoGenerators::FindHeader(std::string& header,
- const std::string& testBasePath) const
+ std::string const& testBasePath) const
{
- for (std::vector<std::string>::const_iterator ext =
- this->HeaderExtensions.begin();
- ext != this->HeaderExtensions.end(); ++ext) {
+ for (std::string const& ext : this->HeaderExtensions) {
std::string testFilePath(testBasePath);
- testFilePath += '.';
- testFilePath += (*ext);
- if (cmsys::SystemTools::FileExists(testFilePath.c_str())) {
+ testFilePath.push_back('.');
+ testFilePath += ext;
+ if (cmSystemTools::FileExists(testFilePath.c_str())) {
header = testFilePath;
return true;
}
}
return false;
}
-
-std::string cmQtAutoGenerators::MocFindHeader(
- const std::string& sourcePath, const std::string& includeBase) const
-{
- std::string header;
- // Search in vicinity of the source
- if (!this->FindHeader(header, sourcePath + includeBase)) {
- // Search in include directories
- for (std::vector<std::string>::const_iterator iit =
- this->MocIncludePaths.begin();
- iit != this->MocIncludePaths.end(); ++iit) {
- const std::string fullPath = ((*iit) + '/' + includeBase);
- if (FindHeader(header, fullPath)) {
- break;
- }
- }
- }
- // Sanitize
- if (!header.empty()) {
- header = cmsys::SystemTools::GetRealPath(header);
- }
- return header;
-}
-
-bool cmQtAutoGenerators::MocFindIncludedFile(
- std::string& absFile, const std::string& sourcePath,
- const std::string& includeString) const
-{
- bool success = false;
- // Search in vicinity of the source
- {
- std::string testPath = sourcePath;
- testPath += includeString;
- if (cmsys::SystemTools::FileExists(testPath.c_str())) {
- absFile = cmsys::SystemTools::GetRealPath(testPath);
- success = true;
- }
- }
- // Search in include directories
- if (!success) {
- for (std::vector<std::string>::const_iterator iit =
- this->MocIncludePaths.begin();
- iit != this->MocIncludePaths.end(); ++iit) {
- const std::string fullPath = ((*iit) + '/' + includeString);
- if (cmsys::SystemTools::FileExists(fullPath.c_str())) {
- absFile = cmsys::SystemTools::GetRealPath(fullPath);
- success = true;
- break;
- }
- }
- }
- return success;
-}
diff --git a/Source/cmQtAutoGenerators.h b/Source/cmQtAutoGenerators.h
index 337aa17fd..a7bb53840 100644
--- a/Source/cmQtAutoGenerators.h
+++ b/Source/cmQtAutoGenerators.h
@@ -6,160 +6,194 @@
#include "cmConfigure.h" // IWYU pragma: keep
#include "cmFilePathChecksum.h"
+#include "cmQtAutoGen.h"
#include "cmsys/RegularExpression.hxx"
#include <map>
+#include <memory> // IWYU pragma: keep
#include <set>
#include <string>
-#include <utility>
#include <vector>
class cmMakefile;
class cmQtAutoGenerators
{
+ CM_DISABLE_COPY(cmQtAutoGenerators)
public:
cmQtAutoGenerators();
- bool Run(const std::string& targetDirectory, const std::string& config);
+ bool Run(std::string const& targetDirectory, std::string const& config);
private:
// -- Types
- /// @brief Used to extract additional dependencies from content text
- struct MocDependFilter
+ /// @brief Search key plus regular expression pair
+ struct KeyRegExp
{
- std::string key;
- cmsys::RegularExpression regExp;
+ KeyRegExp() = default;
+
+ KeyRegExp(const char* key, const char* regExp)
+ : Key(key)
+ , RegExp(regExp)
+ {
+ }
+
+ KeyRegExp(std::string const& key, std::string const& regExp)
+ : Key(key)
+ , RegExp(regExp)
+ {
+ }
+
+ std::string Key;
+ cmsys::RegularExpression RegExp;
};
- typedef std::pair<std::string, cmsys::RegularExpression> MocMacroFilter;
- // -- Configuration
- bool MocDependFilterPush(const std::string& key, const std::string& regExp);
- bool ReadAutogenInfoFile(cmMakefile* makefile,
- const std::string& targetDirectory,
- const std::string& config);
+ /// @brief Source file job
+ struct SourceJob
+ {
+ bool Moc = false;
+ bool Uic = false;
+ };
- bool MocEnabled() const { return !this->MocExecutable.empty(); }
- bool UicEnabled() const { return !this->UicExecutable.empty(); }
- bool RccEnabled() const { return !this->RccExecutable.empty(); }
+ /// @brief MOC job
+ struct MocJobAuto
+ {
+ std::string SourceFile;
+ std::string BuildFileRel;
+ std::set<std::string> Depends;
+ };
+
+ /// @brief MOC job
+ struct MocJobIncluded : MocJobAuto
+ {
+ bool DependsValid = false;
+ std::string Includer;
+ std::string IncludeString;
+ };
+
+ /// @brief UIC job
+ struct UicJob
+ {
+ std::string SourceFile;
+ std::string BuildFileRel;
+ std::string Includer;
+ std::string IncludeString;
+ };
+
+ /// @brief RCC job
+ struct RccJob
+ {
+ std::string QrcFile;
+ std::string RccFile;
+ std::vector<std::string> Options;
+ std::vector<std::string> Inputs;
+ };
+
+ // -- Initialization
+ bool InitInfoFile(cmMakefile* makefile, std::string const& targetDirectory,
+ std::string const& config);
// -- Settings file
void SettingsFileRead(cmMakefile* makefile);
bool SettingsFileWrite();
-
- bool AnySettingsChanged() const
+ bool SettingsChanged() const
{
return (this->MocSettingsChanged || this->RccSettingsChanged ||
this->UicSettingsChanged);
}
- // -- Init and run
- void Init(cmMakefile* makefile);
- bool RunAutogen();
-
- // -- Content analysis
- bool MocRequired(const std::string& contentText,
- std::string* macroName = CM_NULLPTR);
- void MocFindDepends(
- const std::string& absFilename, const std::string& contentText,
- std::map<std::string, std::set<std::string> >& mocDepends);
-
- bool MocSkip(const std::string& absFilename) const;
- bool UicSkip(const std::string& absFilename) const;
-
- bool ParseSourceFile(
- const std::string& absFilename,
- std::map<std::string, std::string>& mocsIncluded,
- std::map<std::string, std::set<std::string> >& mocDepends,
- std::map<std::string, std::vector<std::string> >& includedUis,
- bool relaxed);
-
- void SearchHeadersForSourceFile(const std::string& absFilename,
- std::set<std::string>& mocHeaderFiles,
- std::set<std::string>& uicHeaderFiles) const;
-
- bool ParseHeaders(
- const std::set<std::string>& mocHeaderFiles,
- const std::set<std::string>& uicHeaderFiles,
- const std::map<std::string, std::string>& mocsIncluded,
- std::map<std::string, std::string>& mocsNotIncluded,
- std::map<std::string, std::set<std::string> >& mocDepends,
- std::map<std::string, std::vector<std::string> >& includedUis);
-
- void UicParseContent(
- const std::string& fileName, const std::string& contentText,
- std::map<std::string, std::vector<std::string> >& includedUis);
-
- bool MocParseSourceContent(
- const std::string& absFilename, const std::string& contentText,
- std::map<std::string, std::string>& mocsIncluded,
- std::map<std::string, std::set<std::string> >& mocDepends, bool relaxed);
-
- void MocParseHeaderContent(
- const std::string& absFilename, const std::string& contentText,
- std::map<std::string, std::string>& mocsNotIncluded,
- std::map<std::string, std::set<std::string> >& mocDepends);
-
- // -- Moc file generation
- bool MocGenerateAll(
- const std::map<std::string, std::string>& mocsIncluded,
- const std::map<std::string, std::string>& mocsNotIncluded,
- const std::map<std::string, std::set<std::string> >& mocDepends);
- bool MocGenerateFile(
- const std::string& sourceFile, const std::string& mocFileName,
- const std::map<std::string, std::set<std::string> >& mocDepends,
- bool included);
-
- // -- Uic file generation
- bool UicFindIncludedFile(std::string& absFile, const std::string& sourceFile,
- const std::string& searchPath,
- const std::string& searchFile);
- bool UicGenerateAll(
- const std::map<std::string, std::vector<std::string> >& includedUis);
- bool UicGenerateFile(const std::string& realName,
- const std::string& uiInputFile,
- const std::string& uiOutputFile);
-
- // -- Rcc file generation
+ // -- Central processing
+ bool Process();
+
+ // -- Source parsing
+ bool ParseSourceFile(std::string const& absFilename, const SourceJob& job);
+ bool ParseHeaderFile(std::string const& absFilename, const SourceJob& job);
+ bool ParsePostprocess();
+
+ // -- Moc
+ bool MocEnabled() const { return !this->MocExecutable.empty(); }
+ bool MocSkip(std::string const& absFilename) const;
+ bool MocRequired(std::string const& contentText,
+ std::string* macroName = nullptr);
+ // Moc strings
+ std::string MocStringMacros() const;
+ std::string MocStringHeaders(std::string const& fileBase) const;
+ std::string MocFindIncludedHeader(std::string const& sourcePath,
+ std::string const& includeBase) const;
+ bool MocFindIncludedFile(std::string& absFile, std::string const& sourceFile,
+ std::string const& includeString) const;
+ // Moc depends
+ bool MocDependFilterPush(std::string const& key, std::string const& regExp);
+ void MocFindDepends(std::string const& absFilename,
+ std::string const& contentText,
+ std::set<std::string>& depends);
+ // Moc
+ bool MocParseSourceContent(std::string const& absFilename,
+ std::string const& contentText);
+ void MocParseHeaderContent(std::string const& absFilename,
+ std::string const& contentText);
+
+ bool MocGenerateAll();
+ bool MocGenerateFile(const MocJobAuto& mocJob, bool* generated = nullptr);
+
+ // -- Uic
+ bool UicEnabled() const { return !this->UicExecutable.empty(); }
+ bool UicSkip(std::string const& absFilename) const;
+ bool UicParseContent(std::string const& fileName,
+ std::string const& contentText);
+ bool UicFindIncludedFile(std::string& absFile, std::string const& sourceFile,
+ std::string const& includeString);
+ bool UicGenerateAll();
+ bool UicGenerateFile(const UicJob& uicJob);
+
+ // -- Rcc
+ bool RccEnabled() const { return !this->RccExecutable.empty(); }
bool RccGenerateAll();
- bool RccGenerateFile(const std::string& qrcInputFile,
- const std::string& qrcOutputFile, bool unique_n);
-
- // -- Logging
- void LogErrorNameCollision(
- const std::string& message,
- const std::multimap<std::string, std::string>& collisions) const;
- void LogBold(const std::string& message) const;
- void LogInfo(const std::string& message) const;
- void LogWarning(const std::string& message) const;
- void LogError(const std::string& message) const;
- void LogCommand(const std::vector<std::string>& command) const;
+ bool RccGenerateFile(const RccJob& rccJob);
+
+ // -- Log info
+ void LogBold(std::string const& message) const;
+ void LogInfo(cmQtAutoGen::Generator genType,
+ std::string const& message) const;
+ // -- Log warning
+ void LogWarning(cmQtAutoGen::Generator genType,
+ std::string const& message) const;
+ void LogFileWarning(cmQtAutoGen::Generator genType,
+ std::string const& filename,
+ std::string const& message) const;
+ // -- Log error
+ void LogError(cmQtAutoGen::Generator genType,
+ std::string const& message) const;
+ void LogFileError(cmQtAutoGen::Generator genType,
+ std::string const& filename,
+ std::string const& message) const;
+ void LogCommandError(cmQtAutoGen::Generator genType,
+ std::string const& message,
+ std::vector<std::string> const& command,
+ std::string const& output) const;
// -- Utility
- bool NameCollisionTest(
- const std::map<std::string, std::string>& genFiles,
- std::multimap<std::string, std::string>& collisions) const;
- std::string ChecksumedPath(const std::string& sourceFile,
- const std::string& basePrefix,
- const std::string& baseSuffix) const;
- bool MakeParentDirectory(const char* logPrefix,
- const std::string& filename) const;
- bool FileDiffers(const std::string& filename, const std::string& content);
- bool FileWrite(const char* logPrefix, const std::string& filename,
- const std::string& content);
-
- bool RunCommand(const std::vector<std::string>& command, std::string& output,
- bool verbose = true) const;
-
- bool FindHeader(std::string& header, const std::string& testBasePath) const;
-
- std::string MocFindHeader(const std::string& sourcePath,
- const std::string& includeBase) const;
- bool MocFindIncludedFile(std::string& absFile, const std::string& sourceFile,
- const std::string& includeString) const;
+ bool MakeParentDirectory(cmQtAutoGen::Generator genType,
+ std::string const& filename) const;
+ bool FileDiffers(std::string const& filename, std::string const& content);
+ bool FileWrite(cmQtAutoGen::Generator genType, std::string const& filename,
+ std::string const& content);
+ bool FindHeader(std::string& header, std::string const& testBasePath) const;
+ bool RunCommand(std::vector<std::string> const& command,
+ std::string& output) const;
// -- Meta
+ std::string InfoFile;
std::string ConfigSuffix;
+ cmQtAutoGen::MultiConfig MultiConfig;
+ // -- Settings
+ bool IncludeProjectDirsBefore;
+ bool Verbose;
+ bool ColorOutput;
+ std::string SettingsFile;
+ std::string SettingsStringMoc;
+ std::string SettingsStringUic;
+ std::string SettingsStringRcc;
// -- Directories
std::string ProjectSourceDir;
std::string ProjectBinaryDir;
@@ -169,27 +203,19 @@ private:
std::string AutogenIncludeDir;
// -- Qt environment
std::string QtMajorVersion;
+ std::string QtMinorVersion;
std::string MocExecutable;
std::string UicExecutable;
std::string RccExecutable;
// -- File lists
- std::vector<std::string> Sources;
- std::vector<std::string> Headers;
+ std::map<std::string, SourceJob> HeaderJobs;
+ std::map<std::string, SourceJob> SourceJobs;
std::vector<std::string> HeaderExtensions;
- cmFilePathChecksum FPathChecksum;
- // -- Settings
- bool IncludeProjectDirsBefore;
- bool Verbose;
- bool ColorOutput;
- std::string SettingsFile;
- std::string SettingsStringMoc;
- std::string SettingsStringUic;
- std::string SettingsStringRcc;
+ cmFilePathChecksum FilePathChecksum;
// -- Moc
bool MocSettingsChanged;
bool MocPredefsChanged;
bool MocRelaxedMode;
- bool MocRunFailed;
std::string MocCompFileRel;
std::string MocCompFileAbs;
std::string MocPredefsFileRel;
@@ -199,24 +225,24 @@ private:
std::vector<std::string> MocIncludes;
std::vector<std::string> MocDefinitions;
std::vector<std::string> MocOptions;
+ std::vector<std::string> MocAllOptions;
std::vector<std::string> MocPredefsCmd;
- std::vector<MocDependFilter> MocDependFilters;
- MocMacroFilter MocMacroFilters[2];
+ std::vector<KeyRegExp> MocDependFilters;
+ std::vector<KeyRegExp> MocMacroFilters;
cmsys::RegularExpression MocRegExpInclude;
+ std::vector<std::unique_ptr<MocJobIncluded>> MocJobsIncluded;
+ std::vector<std::unique_ptr<MocJobAuto>> MocJobsAuto;
// -- Uic
bool UicSettingsChanged;
- bool UicRunFailed;
std::vector<std::string> UicSkipList;
std::vector<std::string> UicTargetOptions;
- std::map<std::string, std::string> UicOptions;
+ std::map<std::string, std::vector<std::string>> UicOptions;
std::vector<std::string> UicSearchPaths;
cmsys::RegularExpression UicRegExpInclude;
+ std::vector<std::unique_ptr<UicJob>> UicJobs;
// -- Rcc
bool RccSettingsChanged;
- bool RccRunFailed;
- std::vector<std::string> RccSources;
- std::map<std::string, std::string> RccOptions;
- std::map<std::string, std::vector<std::string> > RccInputs;
+ std::vector<RccJob> RccJobs;
};
#endif
diff --git a/Source/cmRST.cxx b/Source/cmRST.cxx
index 5364f76f4..112be4d37 100644
--- a/Source/cmRST.cxx
+++ b/Source/cmRST.cxx
@@ -86,7 +86,7 @@ void cmRST::ProcessModule(std::istream& is)
if (line[0] != '#') {
this->ProcessLine(line.substr(0, pos));
}
- rst = "";
+ rst.clear();
this->Reset();
this->OutputLinePending = true;
}
@@ -101,7 +101,7 @@ void cmRST::ProcessModule(std::istream& is)
this->ProcessLine(line.substr(2));
continue;
}
- rst = "";
+ rst.clear();
this->Reset();
this->OutputLinePending = true;
}
@@ -292,9 +292,7 @@ std::string cmRST::ReplaceSubstitutions(std::string const& line)
void cmRST::OutputMarkupLines(bool inlineMarkup)
{
- for (std::vector<std::string>::iterator i = this->MarkupLines.begin();
- i != this->MarkupLines.end(); ++i) {
- std::string line = *i;
+ for (auto line : this->MarkupLines) {
if (!line.empty()) {
line = " " + line;
}
@@ -347,15 +345,13 @@ void cmRST::ProcessDirectiveReplace()
// Record markup lines as replacement text.
std::string& replacement = this->Replace[this->ReplaceName];
replacement += cmJoin(this->MarkupLines, " ");
- this->ReplaceName = "";
+ this->ReplaceName.clear();
}
void cmRST::ProcessDirectiveTocTree()
{
// Process documents referenced by toctree directive.
- for (std::vector<std::string>::iterator i = this->MarkupLines.begin();
- i != this->MarkupLines.end(); ++i) {
- std::string const& line = *i;
+ for (std::string const& line : this->MarkupLines) {
if (!line.empty() && line[0] != ':') {
if (this->TocTreeLink.find(line)) {
std::string const& link = this->TocTreeLink.match(1);
diff --git a/Source/cmRemoveCommand.cxx b/Source/cmRemoveCommand.cxx
index 1db84414a..bb14e687d 100644
--- a/Source/cmRemoveCommand.cxx
+++ b/Source/cmRemoveCommand.cxx
@@ -37,10 +37,10 @@ bool cmRemoveCommand::InitialPass(std::vector<std::string> const& args,
// now create the new value
std::string value;
- for (unsigned int j = 0; j < varArgsExpanded.size(); ++j) {
+ for (std::string const& varArgExpanded : varArgsExpanded) {
int found = 0;
- for (unsigned int k = 0; k < argsExpanded.size(); ++k) {
- if (varArgsExpanded[j] == argsExpanded[k]) {
+ for (std::string const& argExpanded : argsExpanded) {
+ if (varArgExpanded == argExpanded) {
found = 1;
break;
}
@@ -49,7 +49,7 @@ bool cmRemoveCommand::InitialPass(std::vector<std::string> const& args,
if (!value.empty()) {
value += ";";
}
- value += varArgsExpanded[j];
+ value += varArgExpanded;
}
}
diff --git a/Source/cmRemoveCommand.h b/Source/cmRemoveCommand.h
index f2e89f6e1..7b118497b 100644
--- a/Source/cmRemoveCommand.h
+++ b/Source/cmRemoveCommand.h
@@ -3,7 +3,7 @@
#ifndef cmRemoveCommand_h
#define cmRemoveCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmRemoveCommand; }
+ cmCommand* Clone() override { return new cmRemoveCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmRemoveDefinitionsCommand.cxx b/Source/cmRemoveDefinitionsCommand.cxx
index f5fe2dfb7..8311b4b2f 100644
--- a/Source/cmRemoveDefinitionsCommand.cxx
+++ b/Source/cmRemoveDefinitionsCommand.cxx
@@ -15,9 +15,8 @@ bool cmRemoveDefinitionsCommand::InitialPass(
return true;
}
- for (std::vector<std::string>::const_iterator i = args.begin();
- i != args.end(); ++i) {
- this->Makefile->RemoveDefineFlag(i->c_str());
+ for (std::string const& i : args) {
+ this->Makefile->RemoveDefineFlag(i.c_str());
}
return true;
}
diff --git a/Source/cmRemoveDefinitionsCommand.h b/Source/cmRemoveDefinitionsCommand.h
index 9a9a5d535..a5cb2044d 100644
--- a/Source/cmRemoveDefinitionsCommand.h
+++ b/Source/cmRemoveDefinitionsCommand.h
@@ -3,7 +3,7 @@
#ifndef cmRemoveDefinitionsCommand_h
#define cmRemoveDefinitionsCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -25,14 +25,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmRemoveDefinitionsCommand; }
+ cmCommand* Clone() override { return new cmRemoveDefinitionsCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmReturnCommand.h b/Source/cmReturnCommand.h
index 87900e7e9..ef3961459 100644
--- a/Source/cmReturnCommand.h
+++ b/Source/cmReturnCommand.h
@@ -3,7 +3,7 @@
#ifndef cmReturnCommand_h
#define cmReturnCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmReturnCommand; }
+ cmCommand* Clone() override { return new cmReturnCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmScriptGenerator.cxx b/Source/cmScriptGenerator.cxx
index 753a1ba6f..2cae71436 100644
--- a/Source/cmScriptGenerator.cxx
+++ b/Source/cmScriptGenerator.cxx
@@ -10,7 +10,7 @@ cmScriptGenerator::cmScriptGenerator(
: RuntimeConfigVariable(config_var)
, Configurations(configurations)
, ConfigurationName("")
- , ConfigurationTypes(CM_NULLPTR)
+ , ConfigurationTypes(nullptr)
, ActionsPerConfig(false)
{
}
@@ -26,8 +26,8 @@ void cmScriptGenerator::Generate(
this->ConfigurationName = config;
this->ConfigurationTypes = &configurationTypes;
this->GenerateScript(os);
- this->ConfigurationName = "";
- this->ConfigurationTypes = CM_NULLPTR;
+ this->ConfigurationName.clear();
+ this->ConfigurationTypes = nullptr;
}
static void cmScriptGeneratorEncodeConfig(const std::string& config,
@@ -69,11 +69,10 @@ std::string cmScriptGenerator::CreateConfigTest(
result += this->RuntimeConfigVariable;
result += "}\" MATCHES \"^(";
const char* sep = "";
- for (std::vector<std::string>::const_iterator ci = configs.begin();
- ci != configs.end(); ++ci) {
+ for (std::string const& config : configs) {
result += sep;
sep = "|";
- cmScriptGeneratorEncodeConfig(*ci, result);
+ cmScriptGeneratorEncodeConfig(config, result);
}
result += ")$\"";
return result;
@@ -123,10 +122,8 @@ bool cmScriptGenerator::GeneratesForConfig(const std::string& config)
// This is a configuration-specific rule. Check if the config
// matches this rule.
std::string config_upper = cmSystemTools::UpperCase(config);
- for (std::vector<std::string>::const_iterator i =
- this->Configurations.begin();
- i != this->Configurations.end(); ++i) {
- if (cmSystemTools::UpperCase(*i) == config_upper) {
+ for (std::string const& cfg : this->Configurations) {
+ if (cmSystemTools::UpperCase(cfg) == config_upper) {
return true;
}
}
@@ -163,15 +160,12 @@ void cmScriptGenerator::GenerateScriptActionsPerConfig(std::ostream& os,
// in a block for each configuration that is built. We restrict
// the list of configurations to those to which this rule applies.
bool first = true;
- for (std::vector<std::string>::const_iterator i =
- this->ConfigurationTypes->begin();
- i != this->ConfigurationTypes->end(); ++i) {
- const char* config = i->c_str();
- if (this->GeneratesForConfig(config)) {
+ for (std::string const& cfgType : *this->ConfigurationTypes) {
+ if (this->GeneratesForConfig(cfgType)) {
// Generate a per-configuration block.
- std::string config_test = this->CreateConfigTest(config);
+ std::string config_test = this->CreateConfigTest(cfgType);
os << indent << (first ? "if(" : "elseif(") << config_test << ")\n";
- this->GenerateScriptForConfig(os, config, indent.Next());
+ this->GenerateScriptForConfig(os, cfgType, indent.Next());
first = false;
}
}
diff --git a/Source/cmScriptGenerator.h b/Source/cmScriptGenerator.h
index d0879c687..c8fed1950 100644
--- a/Source/cmScriptGenerator.h
+++ b/Source/cmScriptGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmScriptGenerator_h
#define cmScriptGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <ostream>
#include <string>
diff --git a/Source/cmSearchPath.cxx b/Source/cmSearchPath.cxx
index 0df6e0c06..a40c98706 100644
--- a/Source/cmSearchPath.cxx
+++ b/Source/cmSearchPath.cxx
@@ -27,10 +27,9 @@ void cmSearchPath::ExtractWithout(const std::set<std::string>& ignore,
if (clear) {
outPaths.clear();
}
- for (std::vector<std::string>::const_iterator p = this->Paths.begin();
- p != this->Paths.end(); ++p) {
- if (ignore.count(*p) == 0) {
- outPaths.push_back(*p);
+ for (std::string const& path : this->Paths) {
+ if (ignore.count(path) == 0) {
+ outPaths.push_back(path);
}
}
}
@@ -42,7 +41,7 @@ void cmSearchPath::AddPath(const std::string& path)
void cmSearchPath::AddUserPath(const std::string& path)
{
- assert(this->FC != CM_NULLPTR);
+ assert(this->FC != nullptr);
std::vector<std::string> outPaths;
@@ -69,24 +68,22 @@ void cmSearchPath::AddUserPath(const std::string& path)
}
// Process them all from the current directory
- for (std::vector<std::string>::const_iterator p = outPaths.begin();
- p != outPaths.end(); ++p) {
- this->AddPathInternal(*p, this->FC->Makefile->GetCurrentSourceDirectory());
+ for (std::string const& p : outPaths) {
+ this->AddPathInternal(p, this->FC->Makefile->GetCurrentSourceDirectory());
}
}
void cmSearchPath::AddCMakePath(const std::string& variable)
{
- assert(this->FC != CM_NULLPTR);
+ assert(this->FC != nullptr);
// Get a path from a CMake variable.
if (const char* value = this->FC->Makefile->GetDefinition(variable)) {
std::vector<std::string> expanded;
cmSystemTools::ExpandListArgument(value, expanded);
- for (std::vector<std::string>::const_iterator p = expanded.begin();
- p != expanded.end(); ++p) {
- this->AddPathInternal(*p,
+ for (std::string const& p : expanded) {
+ this->AddPathInternal(p,
this->FC->Makefile->GetCurrentSourceDirectory());
}
}
@@ -96,15 +93,14 @@ void cmSearchPath::AddEnvPath(const std::string& variable)
{
std::vector<std::string> expanded;
cmSystemTools::GetPath(expanded, variable.c_str());
- for (std::vector<std::string>::const_iterator p = expanded.begin();
- p != expanded.end(); ++p) {
- this->AddPathInternal(*p);
+ for (std::string const& p : expanded) {
+ this->AddPathInternal(p);
}
}
void cmSearchPath::AddCMakePrefixPath(const std::string& variable)
{
- assert(this->FC != CM_NULLPTR);
+ assert(this->FC != nullptr);
// Get a path from a CMake variable.
if (const char* value = this->FC->Makefile->GetDefinition(variable)) {
@@ -142,33 +138,31 @@ void cmSearchPath::AddSuffixes(const std::vector<std::string>& suffixes)
inPaths.swap(this->Paths);
this->Paths.reserve(inPaths.size() * (suffixes.size() + 1));
- for (std::vector<std::string>::iterator ip = inPaths.begin();
- ip != inPaths.end(); ++ip) {
- cmSystemTools::ConvertToUnixSlashes(*ip);
+ for (std::string& inPath : inPaths) {
+ cmSystemTools::ConvertToUnixSlashes(inPath);
// if *i is only / then do not add a //
// this will get incorrectly considered a network
// path on windows and cause huge delays.
- std::string p = *ip;
+ std::string p = inPath;
if (!p.empty() && *p.rbegin() != '/') {
p += "/";
}
// Combine with all the suffixes
- for (std::vector<std::string>::const_iterator s = suffixes.begin();
- s != suffixes.end(); ++s) {
- this->Paths.push_back(p + *s);
+ for (std::string const& suffix : suffixes) {
+ this->Paths.push_back(p + suffix);
}
// And now the original w/o any suffix
- this->Paths.push_back(*ip);
+ this->Paths.push_back(inPath);
}
}
void cmSearchPath::AddPrefixPaths(const std::vector<std::string>& paths,
const char* base)
{
- assert(this->FC != CM_NULLPTR);
+ assert(this->FC != nullptr);
// default for programs
std::string subdir = "bin";
@@ -178,12 +172,11 @@ void cmSearchPath::AddPrefixPaths(const std::vector<std::string>& paths,
} else if (this->FC->CMakePathName == "LIBRARY") {
subdir = "lib";
} else if (this->FC->CMakePathName == "FRAMEWORK") {
- subdir = ""; // ? what to do for frameworks ?
+ subdir.clear(); // ? what to do for frameworks ?
}
- for (std::vector<std::string>::const_iterator p = paths.begin();
- p != paths.end(); ++p) {
- std::string dir = *p;
+ for (std::string const& path : paths) {
+ std::string dir = path;
if (!subdir.empty() && !dir.empty() && *dir.rbegin() != '/') {
dir += "/";
}
@@ -201,15 +194,15 @@ void cmSearchPath::AddPrefixPaths(const std::vector<std::string>& paths,
if (subdir == "bin") {
this->AddPathInternal(dir + "sbin", base);
}
- if (!subdir.empty() && *p != "/") {
- this->AddPathInternal(*p, base);
+ if (!subdir.empty() && path != "/") {
+ this->AddPathInternal(path, base);
}
}
}
void cmSearchPath::AddPathInternal(const std::string& path, const char* base)
{
- assert(this->FC != CM_NULLPTR);
+ assert(this->FC != nullptr);
std::string collapsed = cmSystemTools::CollapseFullPath(path, base);
diff --git a/Source/cmSearchPath.h b/Source/cmSearchPath.h
index 932022aa1..fd0c7c52e 100644
--- a/Source/cmSearchPath.h
+++ b/Source/cmSearchPath.h
@@ -3,7 +3,7 @@
#ifndef cmSearchPath_h
#define cmSearchPath_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <set>
#include <string>
@@ -23,7 +23,7 @@ public:
// cmSearchPath must be initialized from a valid pointer. The only reason
// for the default is to allow it to be easily used in stl containers.
// Attempting to initialize with a NULL value will fail an assertion
- cmSearchPath(cmFindCommon* findCmd = CM_NULLPTR);
+ cmSearchPath(cmFindCommon* findCmd = nullptr);
~cmSearchPath();
const std::vector<std::string>& GetPaths() const { return this->Paths; }
@@ -42,8 +42,8 @@ public:
protected:
void AddPrefixPaths(const std::vector<std::string>& paths,
- const char* base = CM_NULLPTR);
- void AddPathInternal(const std::string& path, const char* base = CM_NULLPTR);
+ const char* base = nullptr);
+ void AddPathInternal(const std::string& path, const char* base = nullptr);
cmFindCommon* FC;
std::vector<std::string> Paths;
diff --git a/Source/cmSeparateArgumentsCommand.cxx b/Source/cmSeparateArgumentsCommand.cxx
index 7b222a041..28cbdc0ad 100644
--- a/Source/cmSeparateArgumentsCommand.cxx
+++ b/Source/cmSeparateArgumentsCommand.cxx
@@ -36,29 +36,29 @@ bool cmSeparateArgumentsCommand::InitialPass(
DoingCommand
};
Doing doing = DoingVariable;
- for (unsigned int i = 0; i < args.size(); ++i) {
+ for (std::string const& arg : args) {
if (doing == DoingVariable) {
- var = args[i];
+ var = arg;
doing = DoingMode;
- } else if (doing == DoingMode && args[i] == "NATIVE_COMMAND") {
+ } else if (doing == DoingMode && arg == "NATIVE_COMMAND") {
#ifdef _WIN32
mode = ModeWindows;
#else
mode = ModeUnix;
#endif
doing = DoingCommand;
- } else if (doing == DoingMode && args[i] == "UNIX_COMMAND") {
+ } else if (doing == DoingMode && arg == "UNIX_COMMAND") {
mode = ModeUnix;
doing = DoingCommand;
- } else if (doing == DoingMode && args[i] == "WINDOWS_COMMAND") {
+ } else if (doing == DoingMode && arg == "WINDOWS_COMMAND") {
mode = ModeWindows;
doing = DoingCommand;
} else if (doing == DoingCommand) {
- command = args[i];
+ command = arg;
doing = DoingNone;
} else {
std::ostringstream e;
- e << "given unknown argument " << args[i];
+ e << "given unknown argument " << arg;
this->SetError(e.str());
return false;
}
@@ -84,19 +84,17 @@ bool cmSeparateArgumentsCommand::InitialPass(
// Construct the result list value.
std::string value;
const char* sep = "";
- for (std::vector<std::string>::const_iterator vi = vec.begin();
- vi != vec.end(); ++vi) {
+ for (std::string const& vi : vec) {
// Separate from the previous argument.
value += sep;
sep = ";";
// Preserve semicolons.
- for (std::string::const_iterator si = vi->begin(); si != vi->end();
- ++si) {
- if (*si == ';') {
+ for (char si : vi) {
+ if (si == ';') {
value += '\\';
}
- value += *si;
+ value += si;
}
}
this->Makefile->AddDefinition(var, value.c_str());
diff --git a/Source/cmSeparateArgumentsCommand.h b/Source/cmSeparateArgumentsCommand.h
index 6bf8549cf..988ad23ae 100644
--- a/Source/cmSeparateArgumentsCommand.h
+++ b/Source/cmSeparateArgumentsCommand.h
@@ -3,7 +3,7 @@
#ifndef cmSeparateArgumentsCommand_h
#define cmSeparateArgumentsCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmSeparateArgumentsCommand; }
+ cmCommand* Clone() override { return new cmSeparateArgumentsCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmServer.cxx b/Source/cmServer.cxx
index 7fc6ed755..e923c228a 100644
--- a/Source/cmServer.cxx
+++ b/Source/cmServer.cxx
@@ -2,7 +2,9 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmServer.h"
-#include "cmServerConnection.h"
+#include "cmAlgorithms.h"
+#include "cmConnection.h"
+#include "cmFileMonitor.h"
#include "cmServerDictionary.h"
#include "cmServerProtocol.h"
#include "cmSystemTools.h"
@@ -14,8 +16,24 @@
#include <algorithm>
#include <cassert>
#include <cstdint>
+#include <iostream>
+#include <memory>
#include <utility>
+void on_signal(uv_signal_t* signal, int signum)
+{
+ auto conn = reinterpret_cast<cmServerBase*>(signal->data);
+ conn->OnSignal(signum);
+}
+
+static void on_walk_to_shutdown(uv_handle_t* handle, void* arg)
+{
+ (void)arg;
+ if (!uv_is_closing(handle)) {
+ uv_close(handle, &cmEventBasedConnection::on_close);
+ }
+}
+
class cmServer::DebugInfo
{
public:
@@ -30,59 +48,46 @@ public:
uint64_t StartTime;
};
-cmServer::cmServer(cmServerConnection* conn, bool supportExperimental)
- : Connection(conn)
+cmServer::cmServer(cmConnection* conn, bool supportExperimental)
+ : cmServerBase(conn)
, SupportExperimental(supportExperimental)
{
- this->Connection->SetServer(this);
// Register supported protocols:
- this->RegisterProtocol(new cmServerProtocol1_0);
+ this->RegisterProtocol(new cmServerProtocol1);
}
cmServer::~cmServer()
{
- if (!this->Protocol) { // Server was never fully started!
- return;
- }
-
for (cmServerProtocol* p : this->SupportedProtocols) {
delete p;
}
-
- delete this->Connection;
}
-void cmServer::PopOne()
+void cmServer::ProcessRequest(cmConnection* connection,
+ const std::string& input)
{
- if (this->Queue.empty()) {
- return;
- }
-
Json::Reader reader;
Json::Value value;
- const std::string input = this->Queue.front();
- this->Queue.erase(this->Queue.begin());
-
if (!reader.parse(input, value)) {
- this->WriteParseError("Failed to parse JSON input.");
+ this->WriteParseError(connection, "Failed to parse JSON input.");
return;
}
std::unique_ptr<DebugInfo> debug;
Json::Value debugValue = value["debug"];
if (!debugValue.isNull()) {
- debug = std::make_unique<DebugInfo>();
+ debug = cm::make_unique<DebugInfo>();
debug->OutputFile = debugValue["dumpToFile"].asString();
debug->PrintStatistics = debugValue["showStats"].asBool();
}
- const cmServerRequest request(this, value[kTYPE_KEY].asString(),
+ const cmServerRequest request(this, connection, value[kTYPE_KEY].asString(),
value[kCOOKIE_KEY].asString(), value);
- if (request.Type == "") {
+ if (request.Type.empty()) {
cmServerResponse response(request);
response.SetError("No type given in request.");
- this->WriteResponse(response, nullptr);
+ this->WriteResponse(connection, response, nullptr);
return;
}
@@ -91,15 +96,18 @@ void cmServer::PopOne()
if (this->Protocol) {
this->Protocol->CMakeInstance()->SetProgressCallback(
reportProgress, const_cast<cmServerRequest*>(&request));
- this->WriteResponse(this->Protocol->Process(request), debug.get());
+ this->WriteResponse(connection, this->Protocol->Process(request),
+ debug.get());
} else {
- this->WriteResponse(this->SetProtocolVersion(request), debug.get());
+ this->WriteResponse(connection, this->SetProtocolVersion(request),
+ debug.get());
}
}
void cmServer::RegisterProtocol(cmServerProtocol* protocol)
{
if (protocol->IsExperimental() && !this->SupportExperimental) {
+ delete protocol;
return;
}
auto version = protocol->ProtocolVersion();
@@ -115,7 +123,7 @@ void cmServer::RegisterProtocol(cmServerProtocol* protocol)
}
}
-void cmServer::PrintHello() const
+void cmServer::PrintHello(cmConnection* connection) const
{
Json::Value hello = Json::objectValue;
hello[kTYPE_KEY] = "hello";
@@ -134,13 +142,7 @@ void cmServer::PrintHello() const
protocolVersions.append(tmp);
}
- this->WriteJsonObject(hello, nullptr);
-}
-
-void cmServer::QueueRequest(const std::string& request)
-{
- this->Queue.push_back(request);
- this->PopOne();
+ this->WriteJsonObject(connection, hello, nullptr);
}
void cmServer::reportProgress(const char* msg, float progress, void* data)
@@ -216,7 +218,7 @@ cmServerResponse cmServer::SetProtocolVersion(const cmServerRequest& request)
std::string errorMessage;
if (!this->Protocol->Activate(this, request, &errorMessage)) {
- this->Protocol = CM_NULLPTR;
+ this->Protocol = nullptr;
return request.ReportError("Failed to activate protocol version: " +
errorMessage);
}
@@ -232,17 +234,28 @@ bool cmServer::Serve(std::string* errorMessage)
}
assert(!this->Protocol);
- return Connection->ProcessEvents(errorMessage);
+ return cmServerBase::Serve(errorMessage);
}
cmFileMonitor* cmServer::FileMonitor() const
{
- return Connection->FileMonitor();
+ return fileMonitor.get();
}
void cmServer::WriteJsonObject(const Json::Value& jsonValue,
const DebugInfo* debug) const
{
+ uv_rwlock_rdlock(&ConnectionsMutex);
+ for (auto& connection : this->Connections) {
+ WriteJsonObject(connection.get(), jsonValue, debug);
+ }
+ uv_rwlock_rdunlock(&ConnectionsMutex);
+}
+
+void cmServer::WriteJsonObject(cmConnection* connection,
+ const Json::Value& jsonValue,
+ const DebugInfo* debug) const
+{
Json::FastWriter writer;
auto beforeJson = uv_hrtime();
@@ -272,8 +285,7 @@ void cmServer::WriteJsonObject(const Json::Value& jsonValue,
}
}
- Connection->WriteData(std::string("\n") + kSTART_MAGIC + std::string("\n") +
- result + kEND_MAGIC + std::string("\n"));
+ connection->WriteData(result);
}
cmServerProtocol* cmServer::FindMatchingProtocol(
@@ -311,7 +323,7 @@ void cmServer::WriteProgress(const cmServerRequest& request, int min,
obj[kPROGRESS_MAXIMUM_KEY] = max;
obj[kPROGRESS_CURRENT_KEY] = current;
- this->WriteJsonObject(obj, nullptr);
+ this->WriteJsonObject(request.Connection, obj, nullptr);
}
void cmServer::WriteMessage(const cmServerRequest& request,
@@ -331,10 +343,11 @@ void cmServer::WriteMessage(const cmServerRequest& request,
obj[kTITLE_KEY] = title;
}
- WriteJsonObject(obj, nullptr);
+ WriteJsonObject(request.Connection, obj, nullptr);
}
-void cmServer::WriteParseError(const std::string& message) const
+void cmServer::WriteParseError(cmConnection* connection,
+ const std::string& message) const
{
Json::Value obj = Json::objectValue;
obj[kTYPE_KEY] = kERROR_TYPE;
@@ -342,7 +355,7 @@ void cmServer::WriteParseError(const std::string& message) const
obj[kREPLY_TO_KEY] = "";
obj[kCOOKIE_KEY] = "";
- this->WriteJsonObject(obj, nullptr);
+ this->WriteJsonObject(connection, obj, nullptr);
}
void cmServer::WriteSignal(const std::string& name,
@@ -358,7 +371,8 @@ void cmServer::WriteSignal(const std::string& name,
WriteJsonObject(obj, nullptr);
}
-void cmServer::WriteResponse(const cmServerResponse& response,
+void cmServer::WriteResponse(cmConnection* connection,
+ const cmServerResponse& response,
const DebugInfo* debug) const
{
assert(response.IsComplete());
@@ -371,5 +385,188 @@ void cmServer::WriteResponse(const cmServerResponse& response,
obj[kERROR_MESSAGE_KEY] = response.ErrorMessage();
}
- this->WriteJsonObject(obj, debug);
+ this->WriteJsonObject(connection, obj, debug);
+}
+
+void cmServer::OnConnected(cmConnection* connection)
+{
+ PrintHello(connection);
+}
+
+void cmServer::OnServeStart()
+{
+ cmServerBase::OnServeStart();
+ fileMonitor = std::make_shared<cmFileMonitor>(GetLoop());
+}
+
+void cmServer::StartShutDown()
+{
+ if (fileMonitor) {
+ fileMonitor->StopMonitoring();
+ fileMonitor.reset();
+ }
+ cmServerBase::StartShutDown();
+}
+
+static void __start_thread(void* arg)
+{
+ auto server = reinterpret_cast<cmServerBase*>(arg);
+ std::string error;
+ bool success = server->Serve(&error);
+ if (!success || error.empty() == false) {
+ std::cerr << "Error during serve: " << error << std::endl;
+ }
+}
+
+static void __shutdownThread(uv_async_t* arg)
+{
+ auto server = reinterpret_cast<cmServerBase*>(arg->data);
+ on_walk_to_shutdown(reinterpret_cast<uv_handle_t*>(arg), nullptr);
+ server->StartShutDown();
+}
+
+bool cmServerBase::StartServeThread()
+{
+ ServeThreadRunning = true;
+ uv_async_init(&Loop, &this->ShutdownSignal, __shutdownThread);
+ this->ShutdownSignal.data = this;
+ uv_thread_create(&ServeThread, __start_thread, this);
+ return true;
+}
+
+bool cmServerBase::Serve(std::string* errorMessage)
+{
+#ifndef NDEBUG
+ uv_thread_t blank_thread_t = {};
+ assert(uv_thread_equal(&blank_thread_t, &ServeThreadId));
+ ServeThreadId = uv_thread_self();
+#endif
+
+ errorMessage->clear();
+
+ uv_signal_init(&Loop, &this->SIGINTHandler);
+ uv_signal_init(&Loop, &this->SIGHUPHandler);
+
+ this->SIGINTHandler.data = this;
+ this->SIGHUPHandler.data = this;
+
+ uv_signal_start(&this->SIGINTHandler, &on_signal, SIGINT);
+ uv_signal_start(&this->SIGHUPHandler, &on_signal, SIGHUP);
+
+ OnServeStart();
+
+ {
+ uv_rwlock_rdlock(&ConnectionsMutex);
+ for (auto& connection : Connections) {
+ if (!connection->OnServeStart(errorMessage)) {
+ uv_rwlock_rdunlock(&ConnectionsMutex);
+ return false;
+ }
+ }
+ uv_rwlock_rdunlock(&ConnectionsMutex);
+ }
+
+ if (uv_run(&Loop, UV_RUN_DEFAULT) != 0) {
+ // It is important we don't ever let the event loop exit with open handles
+ // at best this is a memory leak, but it can also introduce race conditions
+ // which can hang the program.
+ assert(false && "Event loop stopped in unclean state.");
+
+ *errorMessage = "Internal Error: Event loop stopped in unclean state.";
+ return false;
+ }
+
+ ServeThreadRunning = false;
+ return true;
+}
+
+void cmServerBase::OnConnected(cmConnection*)
+{
+}
+
+void cmServerBase::OnServeStart()
+{
+}
+
+void cmServerBase::StartShutDown()
+{
+ if (!uv_is_closing(
+ reinterpret_cast<const uv_handle_t*>(&this->SIGINTHandler))) {
+ uv_signal_stop(&this->SIGINTHandler);
+ }
+
+ if (!uv_is_closing(
+ reinterpret_cast<const uv_handle_t*>(&this->SIGHUPHandler))) {
+ uv_signal_stop(&this->SIGHUPHandler);
+ }
+
+ {
+ uv_rwlock_wrlock(&ConnectionsMutex);
+ for (auto& connection : Connections) {
+ connection->OnConnectionShuttingDown();
+ }
+ Connections.clear();
+ uv_rwlock_wrunlock(&ConnectionsMutex);
+ }
+
+ uv_walk(&Loop, on_walk_to_shutdown, nullptr);
+}
+
+bool cmServerBase::OnSignal(int signum)
+{
+ (void)signum;
+ StartShutDown();
+ return true;
+}
+
+cmServerBase::cmServerBase(cmConnection* connection)
+{
+ auto err = uv_loop_init(&Loop);
+ (void)err;
+ assert(err == 0);
+
+ err = uv_rwlock_init(&ConnectionsMutex);
+ assert(err == 0);
+
+ AddNewConnection(connection);
+}
+
+cmServerBase::~cmServerBase()
+{
+
+ if (ServeThreadRunning) {
+ uv_async_send(&this->ShutdownSignal);
+ uv_thread_join(&ServeThread);
+ }
+
+ uv_loop_close(&Loop);
+ uv_rwlock_destroy(&ConnectionsMutex);
+}
+
+void cmServerBase::AddNewConnection(cmConnection* ownedConnection)
+{
+ uv_rwlock_wrlock(&ConnectionsMutex);
+ Connections.emplace_back(ownedConnection);
+ uv_rwlock_wrunlock(&ConnectionsMutex);
+ ownedConnection->SetServer(this);
+}
+
+uv_loop_t* cmServerBase::GetLoop()
+{
+ return &Loop;
+}
+
+void cmServerBase::OnDisconnect(cmConnection* pConnection)
+{
+ auto pred = [pConnection](const std::unique_ptr<cmConnection>& m) {
+ return m.get() == pConnection;
+ };
+ uv_rwlock_wrlock(&ConnectionsMutex);
+ Connections.erase(
+ std::remove_if(Connections.begin(), Connections.end(), pred),
+ Connections.end());
+ uv_rwlock_wrunlock(&ConnectionsMutex);
+ if (Connections.empty()) {
+ StartShutDown();
+ }
}
diff --git a/Source/cmServer.h b/Source/cmServer.h
index b8140504c..15fd2baee 100644
--- a/Source/cmServer.h
+++ b/Source/cmServer.h
@@ -2,31 +2,98 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#pragma once
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cm_jsoncpp_value.h"
#include "cm_uv.h"
+#include <memory> // IWYU pragma: keep
#include <string>
#include <vector>
+class cmConnection;
class cmFileMonitor;
-class cmServerConnection;
class cmServerProtocol;
class cmServerRequest;
class cmServerResponse;
-class cmServer
+/***
+ * This essentially hold and manages a libuv event queue and responds to
+ * messages
+ * on any of its connections.
+ */
+class cmServerBase
+{
+public:
+ cmServerBase(cmConnection* connection);
+ virtual ~cmServerBase();
+
+ virtual void AddNewConnection(cmConnection* ownedConnection);
+
+ /***
+ * The main override responsible for tailoring behavior towards
+ * whatever the given server is supposed to do
+ *
+ * This should almost always be called by the given connections
+ * directly.
+ *
+ * @param connection The connection the request was received on
+ * @param request The actual request
+ */
+ virtual void ProcessRequest(cmConnection* connection,
+ const std::string& request) = 0;
+ virtual void OnConnected(cmConnection* connection);
+
+ /***
+ * Start a dedicated thread. If this is used to start the server, it will
+ * join on the
+ * servers dtor.
+ */
+ virtual bool StartServeThread();
+ virtual bool Serve(std::string* errorMessage);
+
+ virtual void OnServeStart();
+ virtual void StartShutDown();
+
+ virtual bool OnSignal(int signum);
+ uv_loop_t* GetLoop();
+
+ void OnDisconnect(cmConnection* pConnection);
+
+protected:
+ mutable uv_rwlock_t ConnectionsMutex;
+ std::vector<std::unique_ptr<cmConnection>> Connections;
+
+ bool ServeThreadRunning = false;
+ uv_thread_t ServeThread;
+ uv_async_t ShutdownSignal;
+#ifndef NDEBUG
+public:
+ // When the server starts it will mark down it's current thread ID,
+ // which is useful in other contexts to just assert that operations
+ // are performed on that same thread.
+ uv_thread_t ServeThreadId = {};
+
+protected:
+#endif
+
+ uv_loop_t Loop;
+
+ uv_signal_t SIGINTHandler;
+ uv_signal_t SIGHUPHandler;
+};
+
+class cmServer : public cmServerBase
{
CM_DISABLE_COPY(cmServer)
public:
class DebugInfo;
- cmServer(cmServerConnection* conn, bool supportExperimental);
- ~cmServer();
+ cmServer(cmConnection* conn, bool supportExperimental);
+ ~cmServer() override;
- bool Serve(std::string* errorMessage);
+ bool Serve(std::string* errorMessage) override;
cmFileMonitor* FileMonitor() const;
@@ -34,9 +101,20 @@ private:
void RegisterProtocol(cmServerProtocol* protocol);
// Callbacks from cmServerConnection:
- void PopOne();
- void QueueRequest(const std::string& request);
+ void ProcessRequest(cmConnection* connection,
+ const std::string& request) override;
+ std::shared_ptr<cmFileMonitor> fileMonitor;
+
+public:
+ void OnServeStart() override;
+
+ void StartShutDown() override;
+
+public:
+ void OnConnected(cmConnection* connection) override;
+
+private:
static void reportProgress(const char* msg, float progress, void* data);
static void reportMessage(const char* msg, const char* title, bool& cancel,
void* data);
@@ -44,50 +122,34 @@ private:
// Handle requests:
cmServerResponse SetProtocolVersion(const cmServerRequest& request);
- void PrintHello() const;
+ void PrintHello(cmConnection* connection) const;
// Write responses:
void WriteProgress(const cmServerRequest& request, int min, int current,
int max, const std::string& message) const;
void WriteMessage(const cmServerRequest& request, const std::string& message,
const std::string& title) const;
- void WriteResponse(const cmServerResponse& response,
+ void WriteResponse(cmConnection* connection,
+ const cmServerResponse& response,
const DebugInfo* debug) const;
- void WriteParseError(const std::string& message) const;
+ void WriteParseError(cmConnection* connection,
+ const std::string& message) const;
void WriteSignal(const std::string& name, const Json::Value& obj) const;
void WriteJsonObject(Json::Value const& jsonValue,
const DebugInfo* debug) const;
+ void WriteJsonObject(cmConnection* connection, Json::Value const& jsonValue,
+ const DebugInfo* debug) const;
+
static cmServerProtocol* FindMatchingProtocol(
const std::vector<cmServerProtocol*>& protocols, int major, int minor);
- cmServerConnection* Connection = nullptr;
const bool SupportExperimental;
cmServerProtocol* Protocol = nullptr;
std::vector<cmServerProtocol*> SupportedProtocols;
- std::vector<std::string> Queue;
-
- std::string DataBuffer;
- std::string JsonData;
-
- uv_loop_t* Loop = nullptr;
-
- typedef union
- {
- uv_tty_t tty;
- uv_pipe_t pipe;
- } InOutUnion;
-
- InOutUnion Input;
- InOutUnion Output;
- uv_stream_t* InputStream = nullptr;
- uv_stream_t* OutputStream = nullptr;
-
- mutable bool Writing = false;
- friend class cmServerConnection;
friend class cmServerProtocol;
friend class cmServerRequest;
};
diff --git a/Source/cmServerConnection.cxx b/Source/cmServerConnection.cxx
index 36312edf4..44af75f82 100644
--- a/Source/cmServerConnection.cxx
+++ b/Source/cmServerConnection.cxx
@@ -2,376 +2,193 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmServerConnection.h"
-#include "cmFileMonitor.h"
+#include "cmConfigure.h"
#include "cmServer.h"
#include "cmServerDictionary.h"
+#ifdef _WIN32
+#include "io.h"
+#else
+#include <unistd.h>
+#endif
+#include <cassert>
-#include <assert.h>
-#include <string.h>
-
-namespace {
-
-struct write_req_t
-{
- uv_write_t req;
- uv_buf_t buf;
-};
-
-void on_alloc_buffer(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf)
+cmStdIoConnection::cmStdIoConnection(
+ cmConnectionBufferStrategy* bufferStrategy)
+ : cmEventBasedConnection(bufferStrategy)
{
- (void)(handle);
- char* rawBuffer = new char[suggested_size];
- *buf = uv_buf_init(rawBuffer, static_cast<unsigned int>(suggested_size));
}
-void on_read(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf)
+void cmStdIoConnection::SetupStream(uv_stream_t*& stream, int file_id)
{
- auto conn = reinterpret_cast<cmServerConnection*>(stream->data);
- if (nread >= 0) {
- conn->ReadData(std::string(buf->base, buf->base + nread));
- } else {
- conn->TriggerShutdown();
+ assert(stream == nullptr);
+ switch (uv_guess_handle(file_id)) {
+ case UV_TTY: {
+ auto tty = new uv_tty_t();
+ uv_tty_init(this->Server->GetLoop(), tty, file_id, file_id == 0);
+ uv_tty_set_mode(tty, UV_TTY_MODE_NORMAL);
+ stream = reinterpret_cast<uv_stream_t*>(tty);
+ break;
+ }
+ case UV_FILE:
+ if (file_id == 0) {
+ return;
+ }
+ // Intentional fallthrough; stdin can _not_ be treated as a named
+ // pipe, however stdout can be.
+ CM_FALLTHROUGH;
+ case UV_NAMED_PIPE: {
+ auto pipe = new uv_pipe_t();
+ uv_pipe_init(this->Server->GetLoop(), pipe, 0);
+ uv_pipe_open(pipe, file_id);
+ stream = reinterpret_cast<uv_stream_t*>(pipe);
+ break;
+ }
+ default:
+ assert(false && "Unable to determine stream type");
+ return;
}
-
- delete[](buf->base);
+ stream->data = static_cast<cmEventBasedConnection*>(this);
}
-void on_write(uv_write_t* req, int status)
+void cmStdIoConnection::SetServer(cmServerBase* s)
{
- (void)(status);
- auto conn = reinterpret_cast<cmServerConnection*>(req->data);
-
- // Free req and buffer
- write_req_t* wr = reinterpret_cast<write_req_t*>(req);
- delete[](wr->buf.base);
- delete wr;
+ cmConnection::SetServer(s);
+ if (!s) {
+ return;
+ }
- conn->ProcessNextRequest();
+ SetupStream(this->ReadStream, 0);
+ SetupStream(this->WriteStream, 1);
}
-void on_new_connection(uv_stream_t* stream, int status)
+void shutdown_connection(uv_prepare_t* prepare)
{
- (void)(status);
- auto conn = reinterpret_cast<cmServerConnection*>(stream->data);
- conn->Connect(stream);
-}
+ cmStdIoConnection* connection =
+ reinterpret_cast<cmStdIoConnection*>(prepare->data);
-void on_signal(uv_signal_t* signal, int signum)
-{
- auto conn = reinterpret_cast<cmServerConnection*>(signal->data);
- (void)(signum);
- conn->TriggerShutdown();
+ if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(prepare))) {
+ uv_close(reinterpret_cast<uv_handle_t*>(prepare),
+ &cmEventBasedConnection::on_close_delete<uv_prepare_t>);
+ }
+ connection->OnDisconnect(0);
}
-void on_signal_close(uv_handle_t* handle)
+bool cmStdIoConnection::OnServeStart(std::string* pString)
{
- delete reinterpret_cast<uv_signal_t*>(handle);
-}
+ Server->OnConnected(this);
+ if (this->ReadStream) {
+ uv_read_start(this->ReadStream, on_alloc_buffer, on_read);
+ } else if (uv_guess_handle(0) == UV_FILE) {
+ char buffer[1024];
+ while (auto len = read(0, buffer, sizeof(buffer))) {
+ ReadData(std::string(buffer, buffer + len));
+ }
-void on_pipe_close(uv_handle_t* handle)
-{
- delete reinterpret_cast<uv_pipe_t*>(handle);
+ // We can't start the disconnect from here, add a prepare hook to do that
+ // for us
+ auto prepare = new uv_prepare_t();
+ prepare->data = this;
+ uv_prepare_init(Server->GetLoop(), prepare);
+ uv_prepare_start(prepare, shutdown_connection);
+ }
+ return cmConnection::OnServeStart(pString);
}
-void on_tty_close(uv_handle_t* handle)
+void cmStdIoConnection::ShutdownStream(uv_stream_t*& stream)
{
- delete reinterpret_cast<uv_tty_t*>(handle);
-}
+ if (!stream) {
+ return;
+ }
+ switch (stream->type) {
+ case UV_TTY: {
+ assert(!uv_is_closing(reinterpret_cast<uv_handle_t*>(stream)));
+ if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(stream))) {
+ uv_close(reinterpret_cast<uv_handle_t*>(stream),
+ &on_close_delete<uv_tty_t>);
+ }
+ break;
+ }
+ case UV_FILE:
+ case UV_NAMED_PIPE: {
+ assert(!uv_is_closing(reinterpret_cast<uv_handle_t*>(stream)));
+ if (!uv_is_closing(reinterpret_cast<uv_handle_t*>(stream))) {
+ uv_close(reinterpret_cast<uv_handle_t*>(stream),
+ &on_close_delete<uv_pipe_t>);
+ }
+ break;
+ }
+ default:
+ assert(false && "Unable to determine stream type");
+ }
-} // namespace
+ stream = nullptr;
+}
-class LoopGuard
+bool cmStdIoConnection::OnConnectionShuttingDown()
{
-public:
- LoopGuard(cmServerConnection* connection)
- : Connection(connection)
- {
- this->Connection->mLoop = uv_default_loop();
- if (!this->Connection->mLoop) {
- return;
- }
- this->Connection->mFileMonitor =
- new cmFileMonitor(this->Connection->mLoop);
+ if (ReadStream) {
+ uv_read_stop(ReadStream);
}
- ~LoopGuard()
- {
- if (!this->Connection->mLoop) {
- return;
- }
+ ShutdownStream(ReadStream);
+ ShutdownStream(WriteStream);
- if (this->Connection->mFileMonitor) {
- delete this->Connection->mFileMonitor;
- }
- uv_loop_close(this->Connection->mLoop);
- this->Connection->mLoop = nullptr;
- }
+ cmEventBasedConnection::OnConnectionShuttingDown();
-private:
- cmServerConnection* Connection;
-};
+ return true;
+}
-cmServerConnection::cmServerConnection()
+cmServerPipeConnection::cmServerPipeConnection(const std::string& name)
+ : cmPipeConnection(name, new cmServerBufferStrategy)
{
}
-cmServerConnection::~cmServerConnection()
+cmServerStdIoConnection::cmServerStdIoConnection()
+ : cmStdIoConnection(new cmServerBufferStrategy)
{
}
-void cmServerConnection::SetServer(cmServer* s)
+cmConnectionBufferStrategy::~cmConnectionBufferStrategy()
{
- this->Server = s;
}
-bool cmServerConnection::ProcessEvents(std::string* errorMessage)
+void cmConnectionBufferStrategy::clear()
{
- assert(this->Server);
- errorMessage->clear();
-
- this->RawReadBuffer.clear();
- this->RequestBuffer.clear();
-
- LoopGuard guard(this);
- (void)(guard);
- if (!this->mLoop) {
- *errorMessage = "Internal Error: Failed to create event loop.";
- return false;
- }
-
- this->SIGINTHandler = new uv_signal_t;
- uv_signal_init(this->mLoop, this->SIGINTHandler);
- this->SIGINTHandler->data = static_cast<void*>(this);
- uv_signal_start(this->SIGINTHandler, &on_signal, SIGINT);
-
- this->SIGHUPHandler = new uv_signal_t;
- uv_signal_init(this->mLoop, this->SIGHUPHandler);
- this->SIGHUPHandler->data = static_cast<void*>(this);
- uv_signal_start(this->SIGHUPHandler, &on_signal, SIGHUP);
-
- if (!DoSetup(errorMessage)) {
- return false;
- }
-
- if (uv_run(this->mLoop, UV_RUN_DEFAULT) != 0) {
- *errorMessage = "Internal Error: Event loop stopped in unclean state.";
- return false;
- }
-
- // These need to be cleaned up by now:
- assert(!this->ReadStream);
- assert(!this->WriteStream);
-
- this->RawReadBuffer.clear();
- this->RequestBuffer.clear();
-
- return true;
}
-void cmServerConnection::ReadData(const std::string& data)
+std::string cmServerBufferStrategy::BufferOutMessage(
+ const std::string& rawBuffer) const
{
- this->RawReadBuffer += data;
+ return std::string("\n") + kSTART_MAGIC + std::string("\n") + rawBuffer +
+ kEND_MAGIC + std::string("\n");
+}
+std::string cmServerBufferStrategy::BufferMessage(std::string& RawReadBuffer)
+{
for (;;) {
- auto needle = this->RawReadBuffer.find('\n');
+ auto needle = RawReadBuffer.find('\n');
if (needle == std::string::npos) {
- return;
+ return "";
}
- std::string line = this->RawReadBuffer.substr(0, needle);
+ std::string line = RawReadBuffer.substr(0, needle);
const auto ls = line.size();
if (ls > 1 && line.at(ls - 1) == '\r') {
line.erase(ls - 1, 1);
}
- this->RawReadBuffer.erase(this->RawReadBuffer.begin(),
- this->RawReadBuffer.begin() +
- static_cast<long>(needle) + 1);
+ RawReadBuffer.erase(RawReadBuffer.begin(),
+ RawReadBuffer.begin() + static_cast<long>(needle) + 1);
if (line == kSTART_MAGIC) {
- this->RequestBuffer.clear();
+ RequestBuffer.clear();
continue;
}
if (line == kEND_MAGIC) {
- this->Server->QueueRequest(this->RequestBuffer);
- this->RequestBuffer.clear();
- } else {
- this->RequestBuffer += line;
- this->RequestBuffer += "\n";
+ std::string rtn;
+ rtn.swap(this->RequestBuffer);
+ return rtn;
}
- }
-}
-
-void cmServerConnection::TriggerShutdown()
-{
- this->FileMonitor()->StopMonitoring();
-
- uv_signal_stop(this->SIGINTHandler);
- uv_signal_stop(this->SIGHUPHandler);
-
- uv_close(reinterpret_cast<uv_handle_t*>(this->SIGINTHandler),
- &on_signal_close); // delete handle
- uv_close(reinterpret_cast<uv_handle_t*>(this->SIGHUPHandler),
- &on_signal_close); // delete handle
-
- this->SIGINTHandler = nullptr;
- this->SIGHUPHandler = nullptr;
- this->TearDown();
-}
-
-void cmServerConnection::WriteData(const std::string& data)
-{
- assert(this->WriteStream);
-
- auto ds = data.size();
-
- write_req_t* req = new write_req_t;
- req->req.data = this;
- req->buf = uv_buf_init(new char[ds], static_cast<unsigned int>(ds));
- memcpy(req->buf.base, data.c_str(), ds);
-
- uv_write(reinterpret_cast<uv_write_t*>(req),
- static_cast<uv_stream_t*>(this->WriteStream), &req->buf, 1,
- on_write);
-}
-
-void cmServerConnection::ProcessNextRequest()
-{
- Server->PopOne();
-}
-
-void cmServerConnection::SendGreetings()
-{
- Server->PrintHello();
-}
-
-cmServerStdIoConnection::cmServerStdIoConnection()
-{
- this->Input.tty = nullptr;
- this->Output.tty = nullptr;
-}
-
-bool cmServerStdIoConnection::DoSetup(std::string* errorMessage)
-{
- (void)(errorMessage);
-
- if (uv_guess_handle(1) == UV_TTY) {
- usesTty = true;
- this->Input.tty = new uv_tty_t;
- uv_tty_init(this->Loop(), this->Input.tty, 0, 1);
- uv_tty_set_mode(this->Input.tty, UV_TTY_MODE_NORMAL);
- Input.tty->data = this;
- this->ReadStream = reinterpret_cast<uv_stream_t*>(this->Input.tty);
-
- this->Output.tty = new uv_tty_t;
- uv_tty_init(this->Loop(), this->Output.tty, 1, 0);
- uv_tty_set_mode(this->Output.tty, UV_TTY_MODE_NORMAL);
- Output.tty->data = this;
- this->WriteStream = reinterpret_cast<uv_stream_t*>(this->Output.tty);
- } else {
- usesTty = false;
- this->Input.pipe = new uv_pipe_t;
- uv_pipe_init(this->Loop(), this->Input.pipe, 0);
- uv_pipe_open(this->Input.pipe, 0);
- Input.pipe->data = this;
- this->ReadStream = reinterpret_cast<uv_stream_t*>(this->Input.pipe);
-
- this->Output.pipe = new uv_pipe_t;
- uv_pipe_init(this->Loop(), this->Output.pipe, 0);
- uv_pipe_open(this->Output.pipe, 1);
- Output.pipe->data = this;
- this->WriteStream = reinterpret_cast<uv_stream_t*>(this->Output.pipe);
- }
-
- SendGreetings();
- uv_read_start(this->ReadStream, on_alloc_buffer, on_read);
-
- return true;
-}
-
-void cmServerStdIoConnection::TearDown()
-{
- if (usesTty) {
- uv_close(reinterpret_cast<uv_handle_t*>(this->Input.tty), &on_tty_close);
- uv_close(reinterpret_cast<uv_handle_t*>(this->Output.tty), &on_tty_close);
- this->Input.tty = nullptr;
- this->Output.tty = nullptr;
- } else {
- uv_close(reinterpret_cast<uv_handle_t*>(this->Input.pipe), &on_pipe_close);
- uv_close(reinterpret_cast<uv_handle_t*>(this->Output.pipe),
- &on_pipe_close);
- this->Input.pipe = nullptr;
- this->Input.pipe = nullptr;
+ this->RequestBuffer += line;
+ this->RequestBuffer += "\n";
}
- this->ReadStream = nullptr;
- this->WriteStream = nullptr;
-}
-
-cmServerPipeConnection::cmServerPipeConnection(const std::string& name)
- : PipeName(name)
-{
-}
-
-bool cmServerPipeConnection::DoSetup(std::string* errorMessage)
-{
- this->ServerPipe = new uv_pipe_t;
- uv_pipe_init(this->Loop(), this->ServerPipe, 0);
- this->ServerPipe->data = this;
-
- int r;
- if ((r = uv_pipe_bind(this->ServerPipe, this->PipeName.c_str())) != 0) {
- *errorMessage = std::string("Internal Error with ") + this->PipeName +
- ": " + uv_err_name(r);
- return false;
- }
- auto serverStream = reinterpret_cast<uv_stream_t*>(this->ServerPipe);
- if ((r = uv_listen(serverStream, 1, on_new_connection)) != 0) {
- *errorMessage = std::string("Internal Error listening on ") +
- this->PipeName + ": " + uv_err_name(r);
- return false;
- }
-
- return true;
-}
-
-void cmServerPipeConnection::TearDown()
-{
- if (this->ClientPipe) {
- uv_close(reinterpret_cast<uv_handle_t*>(this->ClientPipe), &on_pipe_close);
- this->WriteStream->data = nullptr;
- }
- uv_close(reinterpret_cast<uv_handle_t*>(this->ServerPipe), &on_pipe_close);
-
- this->ClientPipe = nullptr;
- this->ServerPipe = nullptr;
- this->WriteStream = nullptr;
- this->ReadStream = nullptr;
-}
-
-void cmServerPipeConnection::Connect(uv_stream_t* server)
-{
- if (this->ClientPipe) {
- // Accept and close all pipes but the first:
- uv_pipe_t* rejectPipe = new uv_pipe_t;
-
- uv_pipe_init(this->Loop(), rejectPipe, 0);
- auto rejecter = reinterpret_cast<uv_stream_t*>(rejectPipe);
- uv_accept(server, rejecter);
- uv_close(reinterpret_cast<uv_handle_t*>(rejecter), &on_pipe_close);
- return;
- }
-
- this->ClientPipe = new uv_pipe_t;
- uv_pipe_init(this->Loop(), this->ClientPipe, 0);
- this->ClientPipe->data = this;
- auto client = reinterpret_cast<uv_stream_t*>(this->ClientPipe);
- if (uv_accept(server, client) != 0) {
- uv_close(reinterpret_cast<uv_handle_t*>(client), nullptr);
- return;
- }
- this->ReadStream = client;
- this->WriteStream = client;
-
- uv_read_start(this->ReadStream, on_alloc_buffer, on_read);
-
- this->SendGreetings();
}
diff --git a/Source/cmServerConnection.h b/Source/cmServerConnection.h
index b96bf3c54..4ca908ddf 100644
--- a/Source/cmServerConnection.h
+++ b/Source/cmServerConnection.h
@@ -2,94 +2,66 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#pragma once
-#include "cmConfigure.h"
-
-#include "cm_uv.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
-class cmFileMonitor;
-class cmServer;
+#include "cmConnection.h"
+#include "cmPipeConnection.h"
+#include "cm_uv.h"
-class cmServerConnection
-{
- CM_DISABLE_COPY(cmServerConnection)
+class cmServerBase;
+/***
+ * This connection buffer strategy accepts messages in the form of
+ * [== "CMake Server" ==[
+{
+ ... some JSON message ...
+}
+]== "CMake Server" ==]
+ * and only passes on the core json; it discards the envelope.
+ */
+class cmServerBufferStrategy : public cmConnectionBufferStrategy
+{
public:
- cmServerConnection();
- virtual ~cmServerConnection();
-
- void SetServer(cmServer* s);
+ std::string BufferMessage(std::string& rawBuffer) override;
+ std::string BufferOutMessage(const std::string& rawBuffer) const override;
- bool ProcessEvents(std::string* errorMessage);
-
- void ReadData(const std::string& data);
- void TriggerShutdown();
- void WriteData(const std::string& data);
- void ProcessNextRequest();
-
- virtual void Connect(uv_stream_t* server) { (void)(server); }
-
- cmFileMonitor* FileMonitor() const { return this->mFileMonitor; }
-
-protected:
- virtual bool DoSetup(std::string* errorMessage) = 0;
- virtual void TearDown() = 0;
+private:
+ std::string RequestBuffer;
+};
- void SendGreetings();
+/***
+ * Generic connection over std io interfaces -- tty
+ */
+class cmStdIoConnection : public cmEventBasedConnection
+{
+public:
+ cmStdIoConnection(cmConnectionBufferStrategy* bufferStrategy);
- uv_loop_t* Loop() const { return mLoop; }
+ void SetServer(cmServerBase* s) override;
-protected:
- std::string RawReadBuffer;
- std::string RequestBuffer;
+ bool OnConnectionShuttingDown() override;
- uv_stream_t* ReadStream = nullptr;
- uv_stream_t* WriteStream = nullptr;
+ bool OnServeStart(std::string* pString) override;
private:
- uv_loop_t* mLoop = nullptr;
- cmFileMonitor* mFileMonitor = nullptr;
- cmServer* Server = nullptr;
- uv_signal_t* SIGINTHandler = nullptr;
- uv_signal_t* SIGHUPHandler = nullptr;
-
- friend class LoopGuard;
+ void SetupStream(uv_stream_t*& stream, int file_id);
+ void ShutdownStream(uv_stream_t*& stream);
};
-class cmServerStdIoConnection : public cmServerConnection
+/***
+ * These specific connections use the cmake server
+ * buffering strategy.
+ */
+class cmServerStdIoConnection : public cmStdIoConnection
{
public:
cmServerStdIoConnection();
- bool DoSetup(std::string* errorMessage) override;
-
- void TearDown() override;
-
-private:
- typedef union
- {
- uv_tty_t* tty;
- uv_pipe_t* pipe;
- } InOutUnion;
-
- bool usesTty = false;
-
- InOutUnion Input;
- InOutUnion Output;
};
-class cmServerPipeConnection : public cmServerConnection
+class cmServerPipeConnection : public cmPipeConnection
{
public:
cmServerPipeConnection(const std::string& name);
- bool DoSetup(std::string* errorMessage) override;
-
- void TearDown() override;
-
- void Connect(uv_stream_t* server) override;
-
-private:
- const std::string PipeName;
- uv_pipe_t* ServerPipe = nullptr;
- uv_pipe_t* ClientPipe = nullptr;
};
diff --git a/Source/cmServerDictionary.h b/Source/cmServerDictionary.h
index e6a7ae6ca..405ff6b12 100644
--- a/Source/cmServerDictionary.h
+++ b/Source/cmServerDictionary.h
@@ -89,6 +89,11 @@ static const std::string kWARN_UNUSED_KEY = "warnUnused";
static const std::string kWATCHED_DIRECTORIES_KEY = "watchedDirectories";
static const std::string kWATCHED_FILES_KEY = "watchedFiles";
+static const std::string kTARGET_CROSS_REFERENCES_KEY = "crossReferences";
+static const std::string kLINE_NUMBER_KEY = "line";
+static const std::string kBACKTRACE_KEY = "backtrace";
+static const std::string kRELATED_STATEMENTS_KEY = "relatedStatements";
+
static const std::string kSTART_MAGIC = "[== \"CMake Server\" ==[";
static const std::string kEND_MAGIC = "]== \"CMake Server\" ==]";
diff --git a/Source/cmServerProtocol.cxx b/Source/cmServerProtocol.cxx
index c5b7f6064..e835b7a2c 100644
--- a/Source/cmServerProtocol.cxx
+++ b/Source/cmServerProtocol.cxx
@@ -2,12 +2,14 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmServerProtocol.h"
+#include "cmAlgorithms.h"
#include "cmExternalMakefileProjectGenerator.h"
#include "cmFileMonitor.h"
#include "cmGeneratorExpression.h"
#include "cmGeneratorTarget.h"
#include "cmGlobalGenerator.h"
#include "cmLinkLineComputer.h"
+#include "cmListFileCache.h"
#include "cmLocalGenerator.h"
#include "cmMakefile.h"
#include "cmServer.h"
@@ -18,6 +20,7 @@
#include "cmStateSnapshot.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
+#include "cmTarget.h"
#include "cm_uv.h"
#include "cmake.h"
@@ -63,7 +66,7 @@ template <class T>
Json::Value fromStringList(const T& in)
{
Json::Value result = Json::arrayValue;
- for (const std::string& i : in) {
+ for (std::string const& i : in) {
result.append(i);
}
return result;
@@ -72,7 +75,7 @@ Json::Value fromStringList(const T& in)
std::vector<std::string> toStringList(const Json::Value& in)
{
std::vector<std::string> result;
- for (const auto& it : in) {
+ for (auto const& it : in) {
result.push_back(it.asString());
}
return result;
@@ -86,19 +89,17 @@ void getCMakeInputs(const cmGlobalGenerator* gg, const std::string& sourceDir,
{
const std::string cmakeRootDir = cmSystemTools::GetCMakeRoot() + '/';
std::vector<cmMakefile*> const& makefiles = gg->GetMakefiles();
- for (auto it = makefiles.begin(); it != makefiles.end(); ++it) {
- const std::vector<std::string> listFiles = (*it)->GetListFiles();
+ for (cmMakefile const* mf : makefiles) {
+ for (std::string const& lf : mf->GetListFiles()) {
- for (auto jt = listFiles.begin(); jt != listFiles.end(); ++jt) {
-
- const std::string startOfFile = jt->substr(0, cmakeRootDir.size());
+ const std::string startOfFile = lf.substr(0, cmakeRootDir.size());
const bool isInternal = (startOfFile == cmakeRootDir);
- const bool isTemporary = !isInternal && (jt->find(buildDir + '/') == 0);
+ const bool isTemporary = !isInternal && (lf.find(buildDir + '/') == 0);
- std::string toAdd = *jt;
+ std::string toAdd = lf;
if (!sourceDir.empty()) {
const std::string& relative =
- cmSystemTools::RelativePath(sourceDir.c_str(), jt->c_str());
+ cmSystemTools::RelativePath(sourceDir.c_str(), lf.c_str());
if (toAdd.size() > relative.size()) {
toAdd = relative;
}
@@ -125,11 +126,13 @@ void getCMakeInputs(const cmGlobalGenerator* gg, const std::string& sourceDir,
} // namespace
-cmServerRequest::cmServerRequest(cmServer* server, const std::string& t,
- const std::string& c, const Json::Value& d)
+cmServerRequest::cmServerRequest(cmServer* server, cmConnection* connection,
+ const std::string& t, const std::string& c,
+ const Json::Value& d)
: Type(t)
, Cookie(c)
, Data(d)
+ , Connection(connection)
, m_Server(server)
{
}
@@ -215,10 +218,10 @@ bool cmServerProtocol::Activate(cmServer* server,
{
assert(server);
this->m_Server = server;
- this->m_CMakeInstance = std::make_unique<cmake>(cmake::RoleProject);
+ this->m_CMakeInstance = cm::make_unique<cmake>(cmake::RoleProject);
const bool result = this->DoActivate(request, errorMessage);
if (!result) {
- this->m_CMakeInstance = CM_NULLPTR;
+ this->m_CMakeInstance = nullptr;
}
return result;
}
@@ -247,9 +250,9 @@ bool cmServerProtocol::DoActivate(const cmServerRequest& /*request*/,
return true;
}
-std::pair<int, int> cmServerProtocol1_0::ProtocolVersion() const
+std::pair<int, int> cmServerProtocol1::ProtocolVersion() const
{
- return std::make_pair(1, 0);
+ return std::make_pair(1, 1);
}
static void setErrorMessage(std::string* errorMessage, const std::string& text)
@@ -264,6 +267,10 @@ static bool testHomeDirectory(cmState* state, std::string& value,
{
const std::string cachedValue =
std::string(state->GetCacheEntryValue("CMAKE_HOME_DIRECTORY"));
+ if (value.empty()) {
+ value = cachedValue;
+ return true;
+ }
const std::string suffix = "/CMakeLists.txt";
const std::string cachedValueCML = cachedValue + suffix;
const std::string valueCML = value + suffix;
@@ -274,9 +281,6 @@ static bool testHomeDirectory(cmState* state, std::string& value,
"source directory value."));
return false;
}
- if (value.empty()) {
- value = cachedValue;
- }
return true;
}
@@ -287,20 +291,20 @@ static bool testValue(cmState* state, const std::string& key,
const char* entry = state->GetCacheEntryValue(key);
const std::string cachedValue =
entry == nullptr ? std::string() : std::string(entry);
- if (!cachedValue.empty() && !value.empty() && cachedValue != value) {
+ if (value.empty()) {
+ value = cachedValue;
+ }
+ if (!cachedValue.empty() && cachedValue != value) {
setErrorMessage(errorMessage, std::string("\"") + key +
"\" is set but incompatible with configured " +
keyDescription + " value.");
return false;
}
- if (value.empty()) {
- value = cachedValue;
- }
return true;
}
-bool cmServerProtocol1_0::DoActivate(const cmServerRequest& request,
- std::string* errorMessage)
+bool cmServerProtocol1::DoActivate(const cmServerRequest& request,
+ std::string* errorMessage)
{
std::string sourceDirectory = request.Data[kSOURCE_DIRECTORY_KEY].asString();
const std::string buildDirectory =
@@ -419,8 +423,8 @@ bool cmServerProtocol1_0::DoActivate(const cmServerRequest& request,
return true;
}
-void cmServerProtocol1_0::HandleCMakeFileChanges(const std::string& path,
- int event, int status)
+void cmServerProtocol1::HandleCMakeFileChanges(const std::string& path,
+ int event, int status)
{
assert(status == 0);
static_cast<void>(status);
@@ -443,7 +447,7 @@ void cmServerProtocol1_0::HandleCMakeFileChanges(const std::string& path,
SendSignal(kFILE_CHANGE_SIGNAL, obj);
}
-const cmServerResponse cmServerProtocol1_0::Process(
+const cmServerResponse cmServerProtocol1::Process(
const cmServerRequest& request)
{
assert(this->m_State >= STATE_ACTIVE);
@@ -476,18 +480,14 @@ const cmServerResponse cmServerProtocol1_0::Process(
return request.ReportError("Unknown command!");
}
-bool cmServerProtocol1_0::IsExperimental() const
+bool cmServerProtocol1::IsExperimental() const
{
return true;
}
-cmServerResponse cmServerProtocol1_0::ProcessCache(
+cmServerResponse cmServerProtocol1::ProcessCache(
const cmServerRequest& request)
{
- if (this->m_State < STATE_CONFIGURED) {
- return request.ReportError("This project was not configured yet.");
- }
-
cmState* state = this->CMakeInstance()->GetState();
Json::Value result = Json::objectValue;
@@ -499,14 +499,14 @@ cmServerResponse cmServerProtocol1_0::ProcessCache(
if (keys.empty()) {
keys = allKeys;
} else {
- for (const auto& i : keys) {
+ for (auto const& i : keys) {
if (std::find(allKeys.begin(), allKeys.end(), i) == allKeys.end()) {
return request.ReportError("Key \"" + i + "\" not found in cache.");
}
}
}
std::sort(keys.begin(), keys.end());
- for (const auto& key : keys) {
+ for (auto const& key : keys) {
Json::Value entry = Json::objectValue;
entry[kKEY_KEY] = key;
entry[kTYPE_KEY] =
@@ -515,7 +515,7 @@ cmServerResponse cmServerProtocol1_0::ProcessCache(
Json::Value props = Json::objectValue;
bool haveProperties = false;
- for (const auto& prop : state->GetCacheEntryPropertyList(key)) {
+ for (auto const& prop : state->GetCacheEntryPropertyList(key)) {
haveProperties = true;
props[prop] = state->GetCacheEntryProperty(key, prop);
}
@@ -530,7 +530,7 @@ cmServerResponse cmServerProtocol1_0::ProcessCache(
return request.Reply(result);
}
-cmServerResponse cmServerProtocol1_0::ProcessCMakeInputs(
+cmServerResponse cmServerProtocol1::ProcessCMakeInputs(
const cmServerRequest& request)
{
if (this->m_State < STATE_CONFIGURED) {
@@ -589,7 +589,7 @@ public:
std::string Language;
std::string Flags;
std::vector<std::string> Defines;
- std::vector<std::pair<std::string, bool> > IncludePathList;
+ std::vector<std::pair<std::string, bool>> IncludePathList;
};
bool LanguageData::operator==(const LanguageData& other) const
@@ -602,11 +602,12 @@ bool LanguageData::operator==(const LanguageData& other) const
void LanguageData::SetDefines(const std::set<std::string>& defines)
{
std::vector<std::string> result;
- for (const auto& i : defines) {
+ result.reserve(defines.size());
+ for (std::string const& i : defines) {
result.push_back(i);
}
std::sort(result.begin(), result.end());
- Defines = result;
+ Defines = std::move(result);
}
namespace std {
@@ -619,11 +620,11 @@ struct hash<LanguageData>
using std::hash;
size_t result =
hash<std::string>()(in.Language) ^ hash<std::string>()(in.Flags);
- for (const auto& i : in.IncludePathList) {
+ for (auto const& i : in.IncludePathList) {
result = result ^ (hash<std::string>()(i.first) ^
(i.second ? std::numeric_limits<size_t>::max() : 0));
}
- for (const auto& i : in.Defines) {
+ for (auto const& i : in.Defines) {
result = result ^ hash<std::string>()(i);
}
result =
@@ -647,7 +648,7 @@ static Json::Value DumpSourceFileGroup(const LanguageData& data,
}
if (!data.IncludePathList.empty()) {
Json::Value includes = Json::arrayValue;
- for (const auto& i : data.IncludePathList) {
+ for (auto const& i : data.IncludePathList) {
Json::Value tmp = Json::objectValue;
tmp[kPATH_KEY] = i.first;
if (i.second) {
@@ -665,7 +666,7 @@ static Json::Value DumpSourceFileGroup(const LanguageData& data,
result[kIS_GENERATED_KEY] = data.IsGenerated;
Json::Value sourcesValue = Json::arrayValue;
- for (const auto& i : files) {
+ for (auto const& i : files) {
const std::string relPath =
cmSystemTools::RelativePath(baseDir.c_str(), i.c_str());
sourcesValue.append(relPath.size() < i.size() ? relPath : i);
@@ -684,7 +685,7 @@ static Json::Value DumpSourceFilesList(
std::vector<cmSourceFile*> files;
target->GetSourceFiles(files, config);
- std::unordered_map<LanguageData, std::vector<std::string> > fileGroups;
+ std::unordered_map<LanguageData, std::vector<std::string>> fileGroups;
for (cmSourceFile* file : files) {
LanguageData fileData;
fileData.Language = file->GetLanguage();
@@ -721,8 +722,8 @@ static Json::Value DumpSourceFilesList(
const std::string baseDir = target->Makefile->GetCurrentSourceDirectory();
Json::Value result = Json::arrayValue;
- for (auto it = fileGroups.begin(); it != fileGroups.end(); ++it) {
- Json::Value group = DumpSourceFileGroup(it->first, it->second, baseDir);
+ for (auto const& it : fileGroups) {
+ Json::Value group = DumpSourceFileGroup(it.first, it.second, baseDir);
if (!group.isNull()) {
result.append(group);
}
@@ -731,6 +732,37 @@ static Json::Value DumpSourceFilesList(
return result;
}
+static Json::Value DumpBacktrace(const cmListFileBacktrace& backtrace)
+{
+ Json::Value result = Json::arrayValue;
+
+ cmListFileBacktrace backtraceCopy = backtrace;
+ while (!backtraceCopy.Top().FilePath.empty()) {
+ Json::Value entry = Json::objectValue;
+ entry[kPATH_KEY] = backtraceCopy.Top().FilePath;
+ if (backtraceCopy.Top().Line) {
+ entry[kLINE_NUMBER_KEY] = static_cast<int>(backtraceCopy.Top().Line);
+ }
+ if (!backtraceCopy.Top().Name.empty()) {
+ entry[kNAME_KEY] = backtraceCopy.Top().Name;
+ }
+ result.append(entry);
+ backtraceCopy = backtraceCopy.Pop();
+ }
+ return result;
+}
+
+static void DumpBacktraceRange(Json::Value& result, const std::string& type,
+ cmBacktraceRange range)
+{
+ for (auto const& bt : range) {
+ Json::Value obj = Json::objectValue;
+ obj[kTYPE_KEY] = type;
+ obj[kBACKTRACE_KEY] = DumpBacktrace(bt);
+ result.append(obj);
+ }
+}
+
static Json::Value DumpTarget(cmGeneratorTarget* target,
const std::string& config)
{
@@ -765,6 +797,22 @@ static Json::Value DumpTarget(cmGeneratorTarget* target,
result[kFULL_NAME_KEY] = target->GetFullName(config);
+ Json::Value crossRefs = Json::objectValue;
+ crossRefs[kBACKTRACE_KEY] = DumpBacktrace(target->Target->GetBacktrace());
+
+ Json::Value statements = Json::arrayValue;
+ DumpBacktraceRange(statements, "target_compile_definitions",
+ target->Target->GetCompileDefinitionsBacktraces());
+ DumpBacktraceRange(statements, "target_include_directories",
+ target->Target->GetIncludeDirectoriesBacktraces());
+ DumpBacktraceRange(statements, "target_compile_options",
+ target->Target->GetCompileOptionsBacktraces());
+ DumpBacktraceRange(statements, "target_link_libraries",
+ target->Target->GetLinkImplementationBacktraces());
+
+ crossRefs[kRELATED_STATEMENTS_KEY] = std::move(statements);
+ result[kTARGET_CROSS_REFERENCES_KEY] = std::move(crossRefs);
+
if (target->HaveWellDefinedOutputFiles()) {
Json::Value artifacts = Json::arrayValue;
artifacts.append(
@@ -823,7 +871,7 @@ static Json::Value DumpTarget(cmGeneratorTarget* target,
std::set<std::string> languages;
target->GetLanguages(languages, config);
std::map<std::string, LanguageData> languageDataMap;
- for (const auto& lang : languages) {
+ for (std::string const& lang : languages) {
LanguageData& ld = languageDataMap[lang];
ld.Language = lang;
lg->GetTargetCompileFlags(target, config, lang, ld.Flags);
@@ -832,7 +880,7 @@ static Json::Value DumpTarget(cmGeneratorTarget* target,
ld.SetDefines(defines);
std::vector<std::string> includePathList;
lg->GetIncludeDirectories(includePathList, target, lang, config, true);
- for (auto i : includePathList) {
+ for (std::string const& i : includePathList) {
ld.IncludePathList.push_back(
std::make_pair(i, target->IsSystemIncludeDirectory(i, config)));
}
@@ -853,8 +901,8 @@ static Json::Value DumpTargetsList(
Json::Value result = Json::arrayValue;
std::vector<cmGeneratorTarget*> targetList;
- for (const auto& lgIt : generators) {
- auto list = lgIt->GetGeneratorTargets();
+ for (auto const& lgIt : generators) {
+ const auto& list = lgIt->GetGeneratorTargets();
targetList.insert(targetList.end(), list.begin(), list.end());
}
std::sort(targetList.begin(), targetList.end());
@@ -875,7 +923,7 @@ static Json::Value DumpProjectList(const cmake* cm, std::string const& config)
auto globalGen = cm->GetGlobalGenerator();
- for (const auto& projectIt : globalGen->GetProjectMap()) {
+ for (auto const& projectIt : globalGen->GetProjectMap()) {
Json::Value pObj = Json::objectValue;
pObj[kNAME_KEY] = projectIt.first;
@@ -910,14 +958,14 @@ static Json::Value DumpConfigurationsList(const cmake* cm)
{
Json::Value result = Json::arrayValue;
- for (const std::string& c : getConfigurations(cm)) {
+ for (std::string const& c : getConfigurations(cm)) {
result.append(DumpConfiguration(cm, c));
}
return result;
}
-cmServerResponse cmServerProtocol1_0::ProcessCodeModel(
+cmServerResponse cmServerProtocol1::ProcessCodeModel(
const cmServerRequest& request)
{
if (this->m_State != STATE_COMPUTED) {
@@ -929,7 +977,7 @@ cmServerResponse cmServerProtocol1_0::ProcessCodeModel(
return request.Reply(result);
}
-cmServerResponse cmServerProtocol1_0::ProcessCompute(
+cmServerResponse cmServerProtocol1::ProcessCompute(
const cmServerRequest& request)
{
if (this->m_State > STATE_CONFIGURED) {
@@ -949,7 +997,7 @@ cmServerResponse cmServerProtocol1_0::ProcessCompute(
return request.Reply(Json::Value());
}
-cmServerResponse cmServerProtocol1_0::ProcessConfigure(
+cmServerResponse cmServerProtocol1::ProcessConfigure(
const cmServerRequest& request)
{
if (this->m_State == STATE_INACTIVE) {
@@ -973,12 +1021,12 @@ cmServerResponse cmServerProtocol1_0::ProcessConfigure(
if (passedArgs.isString()) {
cacheArgs.push_back(passedArgs.asString());
} else if (passedArgs.isArray()) {
- for (auto i = passedArgs.begin(); i != passedArgs.end(); ++i) {
- if (!i->isString()) {
+ for (auto const& arg : passedArgs) {
+ if (!arg.isString()) {
cacheArgumentsError = true;
break;
}
- cacheArgs.push_back(i->asString());
+ cacheArgs.push_back(arg.asString());
}
} else {
cacheArgumentsError = true;
@@ -1055,7 +1103,7 @@ cmServerResponse cmServerProtocol1_0::ProcessConfigure(
return request.Reply(Json::Value());
}
-cmServerResponse cmServerProtocol1_0::ProcessGlobalSettings(
+cmServerResponse cmServerProtocol1::ProcessGlobalSettings(
const cmServerRequest& request)
{
cmake* cm = this->CMakeInstance();
@@ -1091,7 +1139,7 @@ static void setBool(const cmServerRequest& request, const std::string& key,
setter(request.Data[key].asBool());
}
-cmServerResponse cmServerProtocol1_0::ProcessSetGlobalSettings(
+cmServerResponse cmServerProtocol1::ProcessSetGlobalSettings(
const cmServerRequest& request)
{
const std::vector<std::string> boolValues = {
@@ -1099,7 +1147,7 @@ cmServerResponse cmServerProtocol1_0::ProcessSetGlobalSettings(
kWARN_UNINITIALIZED_KEY, kWARN_UNUSED_KEY, kWARN_UNUSED_CLI_KEY,
kCHECK_SYSTEM_VARS_KEY
};
- for (const auto& i : boolValues) {
+ for (std::string const& i : boolValues) {
if (!request.Data[i].isNull() && !request.Data[i].isBool()) {
return request.ReportError("\"" + i +
"\" must be unset or a bool value.");
@@ -1123,17 +1171,17 @@ cmServerResponse cmServerProtocol1_0::ProcessSetGlobalSettings(
return request.Reply(Json::Value());
}
-cmServerResponse cmServerProtocol1_0::ProcessFileSystemWatchers(
+cmServerResponse cmServerProtocol1::ProcessFileSystemWatchers(
const cmServerRequest& request)
{
const cmFileMonitor* const fm = FileMonitor();
Json::Value result = Json::objectValue;
Json::Value files = Json::arrayValue;
- for (const auto& f : fm->WatchedFiles()) {
+ for (auto const& f : fm->WatchedFiles()) {
files.append(f);
}
Json::Value directories = Json::arrayValue;
- for (const auto& d : fm->WatchedDirectories()) {
+ for (auto const& d : fm->WatchedDirectories()) {
directories.append(d);
}
result[kWATCHED_FILES_KEY] = files;
@@ -1142,7 +1190,7 @@ cmServerResponse cmServerProtocol1_0::ProcessFileSystemWatchers(
return request.Reply(result);
}
-cmServerProtocol1_0::GeneratorInformation::GeneratorInformation(
+cmServerProtocol1::GeneratorInformation::GeneratorInformation(
const std::string& generatorName, const std::string& extraGeneratorName,
const std::string& toolset, const std::string& platform,
const std::string& sourceDirectory, const std::string& buildDirectory)
@@ -1155,7 +1203,7 @@ cmServerProtocol1_0::GeneratorInformation::GeneratorInformation(
{
}
-void cmServerProtocol1_0::GeneratorInformation::SetupGenerator(
+void cmServerProtocol1::GeneratorInformation::SetupGenerator(
cmake* cm, std::string* errorMessage)
{
const std::string fullGeneratorName =
diff --git a/Source/cmServerProtocol.h b/Source/cmServerProtocol.h
index 83b3d58de..124ac7f67 100644
--- a/Source/cmServerProtocol.h
+++ b/Source/cmServerProtocol.h
@@ -2,7 +2,7 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#pragma once
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cm_jsoncpp_value.h"
#include "cmake.h"
@@ -11,6 +11,7 @@
#include <string>
#include <utility>
+class cmConnection;
class cmFileMonitor;
class cmServer;
class cmServerRequest;
@@ -52,9 +53,11 @@ public:
const std::string Type;
const std::string Cookie;
const Json::Value Data;
+ cmConnection* Connection;
private:
- cmServerRequest(cmServer* server, const std::string& t, const std::string& c,
+ cmServerRequest(cmServer* server, cmConnection* connection,
+ const std::string& t, const std::string& c,
const Json::Value& d);
void ReportProgress(int min, int current, int max,
@@ -98,7 +101,7 @@ private:
friend class cmServer;
};
-class cmServerProtocol1_0 : public cmServerProtocol
+class cmServerProtocol1 : public cmServerProtocol
{
public:
std::pair<int, int> ProtocolVersion() const override;
diff --git a/Source/cmSetCommand.cxx b/Source/cmSetCommand.cxx
index 820e7f695..b32cda3cd 100644
--- a/Source/cmSetCommand.cxx
+++ b/Source/cmSetCommand.cxx
@@ -61,7 +61,7 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args,
// SET (VAR PARENT_SCOPE) // Removes the definition of VAR
// in the parent scope.
if (args.size() == 2 && args[args.size() - 1] == "PARENT_SCOPE") {
- this->Makefile->RaiseScope(variable, CM_NULLPTR);
+ this->Makefile->RaiseScope(variable, nullptr);
return true;
}
@@ -75,8 +75,8 @@ bool cmSetCommand::InitialPass(std::vector<std::string> const& args,
bool force = false; // optional
bool parentScope = false;
cmStateEnums::CacheEntryType type =
- cmStateEnums::STRING; // required if cache
- const char* docstring = CM_NULLPTR; // required if cache
+ cmStateEnums::STRING; // required if cache
+ const char* docstring = nullptr; // required if cache
unsigned int ignoreLastArgs = 0;
// look for PARENT_SCOPE argument
diff --git a/Source/cmSetCommand.h b/Source/cmSetCommand.h
index c0858b15b..76e3eae9b 100644
--- a/Source/cmSetCommand.h
+++ b/Source/cmSetCommand.h
@@ -3,7 +3,7 @@
#ifndef cmSetCommand_h
#define cmSetCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmSetCommand; }
+ cmCommand* Clone() override { return new cmSetCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmSetDirectoryPropertiesCommand.h b/Source/cmSetDirectoryPropertiesCommand.h
index 8832b3389..473347c1a 100644
--- a/Source/cmSetDirectoryPropertiesCommand.h
+++ b/Source/cmSetDirectoryPropertiesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmSetDirectoryPropertiesCommand_h
#define cmSetDirectoryPropertiesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -16,17 +16,14 @@ class cmMakefile;
class cmSetDirectoryPropertiesCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE
- {
- return new cmSetDirectoryPropertiesCommand;
- }
+ cmCommand* Clone() override { return new cmSetDirectoryPropertiesCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
/**
* Static entry point for use by other commands
diff --git a/Source/cmSetPropertyCommand.cxx b/Source/cmSetPropertyCommand.cxx
index b57f62a50..7efcc0403 100644
--- a/Source/cmSetPropertyCommand.cxx
+++ b/Source/cmSetPropertyCommand.cxx
@@ -141,7 +141,7 @@ bool cmSetPropertyCommand::HandleGlobalMode()
std::string const& name = this->PropertyName;
const char* value = this->PropertyValue.c_str();
if (this->Remove) {
- value = CM_NULLPTR;
+ value = nullptr;
}
if (this->AppendMode) {
cm->AppendProperty(name, value ? value : "", this->AppendAsString);
@@ -191,7 +191,7 @@ bool cmSetPropertyCommand::HandleDirectoryMode()
std::string const& name = this->PropertyName;
const char* value = this->PropertyValue.c_str();
if (this->Remove) {
- value = CM_NULLPTR;
+ value = nullptr;
}
if (this->AppendMode) {
mf->AppendProperty(name, value ? value : "", this->AppendAsString);
@@ -204,20 +204,19 @@ bool cmSetPropertyCommand::HandleDirectoryMode()
bool cmSetPropertyCommand::HandleTargetMode()
{
- for (std::set<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
- if (this->Makefile->IsAlias(*ni)) {
+ for (std::string const& name : this->Names) {
+ if (this->Makefile->IsAlias(name)) {
this->SetError("can not be used on an ALIAS target.");
return false;
}
- if (cmTarget* target = this->Makefile->FindTargetToUse(*ni)) {
+ if (cmTarget* target = this->Makefile->FindTargetToUse(name)) {
// Handle the current target.
if (!this->HandleTarget(target)) {
return false;
}
} else {
std::ostringstream e;
- e << "could not find TARGET " << *ni
+ e << "could not find TARGET " << name
<< ". Perhaps it has not yet been created.";
this->SetError(e.str());
return false;
@@ -232,7 +231,7 @@ bool cmSetPropertyCommand::HandleTarget(cmTarget* target)
std::string const& name = this->PropertyName;
const char* value = this->PropertyValue.c_str();
if (this->Remove) {
- value = CM_NULLPTR;
+ value = nullptr;
}
if (this->AppendMode) {
target->AppendProperty(name, value, this->AppendAsString);
@@ -248,16 +247,15 @@ bool cmSetPropertyCommand::HandleTarget(cmTarget* target)
bool cmSetPropertyCommand::HandleSourceMode()
{
- for (std::set<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
+ for (std::string const& name : this->Names) {
// Get the source file.
- if (cmSourceFile* sf = this->Makefile->GetOrCreateSource(*ni)) {
+ if (cmSourceFile* sf = this->Makefile->GetOrCreateSource(name)) {
if (!this->HandleSource(sf)) {
return false;
}
} else {
std::ostringstream e;
- e << "given SOURCE name that could not be found or created: " << *ni;
+ e << "given SOURCE name that could not be found or created: " << name;
this->SetError(e.str());
return false;
}
@@ -271,7 +269,7 @@ bool cmSetPropertyCommand::HandleSource(cmSourceFile* sf)
std::string const& name = this->PropertyName;
const char* value = this->PropertyValue.c_str();
if (this->Remove) {
- value = CM_NULLPTR;
+ value = nullptr;
}
if (this->AppendMode) {
@@ -303,9 +301,8 @@ bool cmSetPropertyCommand::HandleTestMode()
if (!this->Names.empty()) {
std::ostringstream e;
e << "given TEST names that do not exist:\n";
- for (std::set<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
- e << " " << *ni << "\n";
+ for (std::string const& name : this->Names) {
+ e << " " << name << "\n";
}
this->SetError(e.str());
return false;
@@ -319,7 +316,7 @@ bool cmSetPropertyCommand::HandleTest(cmTest* test)
std::string const& name = this->PropertyName;
const char* value = this->PropertyValue.c_str();
if (this->Remove) {
- value = CM_NULLPTR;
+ value = nullptr;
}
if (this->AppendMode) {
test->AppendProperty(name, value, this->AppendAsString);
@@ -359,19 +356,18 @@ bool cmSetPropertyCommand::HandleCacheMode()
return false;
}
- for (std::set<std::string>::const_iterator ni = this->Names.begin();
- ni != this->Names.end(); ++ni) {
+ for (std::string const& name : this->Names) {
// Get the source file.
cmMakefile* mf = this->GetMakefile();
cmake* cm = mf->GetCMakeInstance();
- const char* existingValue = cm->GetState()->GetCacheEntryValue(*ni);
+ const char* existingValue = cm->GetState()->GetCacheEntryValue(name);
if (existingValue) {
- if (!this->HandleCacheEntry(*ni)) {
+ if (!this->HandleCacheEntry(name)) {
return false;
}
} else {
std::ostringstream e;
- e << "could not find CACHE variable " << *ni
+ e << "could not find CACHE variable " << name
<< ". Perhaps it has not yet been created.";
this->SetError(e.str());
return false;
@@ -403,16 +399,15 @@ bool cmSetPropertyCommand::HandleInstallMode()
{
cmake* cm = this->Makefile->GetCMakeInstance();
- for (std::set<std::string>::const_iterator i = this->Names.begin();
- i != this->Names.end(); ++i) {
+ for (std::string const& name : this->Names) {
if (cmInstalledFile* file =
- cm->GetOrCreateInstalledFile(this->Makefile, *i)) {
+ cm->GetOrCreateInstalledFile(this->Makefile, name)) {
if (!this->HandleInstall(file)) {
return false;
}
} else {
std::ostringstream e;
- e << "given INSTALL name that could not be found or created: " << *i;
+ e << "given INSTALL name that could not be found or created: " << name;
this->SetError(e.str());
return false;
}
diff --git a/Source/cmSetPropertyCommand.h b/Source/cmSetPropertyCommand.h
index 08158244a..f1126bb7e 100644
--- a/Source/cmSetPropertyCommand.h
+++ b/Source/cmSetPropertyCommand.h
@@ -3,7 +3,7 @@
#ifndef cmSetsPropertiesCommand_h
#define cmSetsPropertiesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <set>
#include <string>
@@ -22,14 +22,14 @@ class cmSetPropertyCommand : public cmCommand
public:
cmSetPropertyCommand();
- cmCommand* Clone() CM_OVERRIDE { return new cmSetPropertyCommand; }
+ cmCommand* Clone() override { return new cmSetPropertyCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
std::set<std::string> Names;
diff --git a/Source/cmSetSourceFilesPropertiesCommand.h b/Source/cmSetSourceFilesPropertiesCommand.h
index 2e22dc9ef..afb19f6e6 100644
--- a/Source/cmSetSourceFilesPropertiesCommand.h
+++ b/Source/cmSetSourceFilesPropertiesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmSetSourceFilesPropertiesCommand_h
#define cmSetSourceFilesPropertiesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -16,17 +16,14 @@ class cmMakefile;
class cmSetSourceFilesPropertiesCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE
- {
- return new cmSetSourceFilesPropertiesCommand;
- }
+ cmCommand* Clone() override { return new cmSetSourceFilesPropertiesCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
static bool RunCommand(cmMakefile* mf,
std::vector<std::string>::const_iterator filebeg,
diff --git a/Source/cmSetTargetPropertiesCommand.h b/Source/cmSetTargetPropertiesCommand.h
index 425618157..c9755da91 100644
--- a/Source/cmSetTargetPropertiesCommand.h
+++ b/Source/cmSetTargetPropertiesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmSetTargetsPropertiesCommand_h
#define cmSetTargetsPropertiesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -16,14 +16,14 @@ class cmMakefile;
class cmSetTargetPropertiesCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmSetTargetPropertiesCommand; }
+ cmCommand* Clone() override { return new cmSetTargetPropertiesCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
/**
* Used by this command and cmSetPropertiesCommand
diff --git a/Source/cmSetTestsPropertiesCommand.h b/Source/cmSetTestsPropertiesCommand.h
index 90f004c34..84b2645b3 100644
--- a/Source/cmSetTestsPropertiesCommand.h
+++ b/Source/cmSetTestsPropertiesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmSetTestsPropertiesCommand_h
#define cmSetTestsPropertiesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -16,14 +16,14 @@ class cmMakefile;
class cmSetTestsPropertiesCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmSetTestsPropertiesCommand; }
+ cmCommand* Clone() override { return new cmSetTestsPropertiesCommand; }
/**
* This is called when the command is first encountered in
* the input file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
static bool SetOneTest(const std::string& tname,
std::vector<std::string>& propertyPairs,
diff --git a/Source/cmSiteNameCommand.cxx b/Source/cmSiteNameCommand.cxx
index 7eace268f..d2e83a6aa 100644
--- a/Source/cmSiteNameCommand.cxx
+++ b/Source/cmSiteNameCommand.cxx
@@ -52,8 +52,8 @@ bool cmSiteNameCommand::InitialPass(std::vector<std::string> const& args,
// try to find the hostname for this computer
if (!cmSystemTools::IsOff(hostname_cmd.c_str())) {
std::string host;
- cmSystemTools::RunSingleCommand(hostname_cmd.c_str(), &host, CM_NULLPTR,
- CM_NULLPTR, CM_NULLPTR,
+ cmSystemTools::RunSingleCommand(hostname_cmd.c_str(), &host, nullptr,
+ nullptr, nullptr,
cmSystemTools::OUTPUT_NONE);
// got the hostname
diff --git a/Source/cmSiteNameCommand.h b/Source/cmSiteNameCommand.h
index 6c65480ed..2d8dc1768 100644
--- a/Source/cmSiteNameCommand.h
+++ b/Source/cmSiteNameCommand.h
@@ -3,7 +3,7 @@
#ifndef cmSiteNameCommand_h
#define cmSiteNameCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmSiteNameCommand; }
+ cmCommand* Clone() override { return new cmSiteNameCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmSourceFile.cxx b/Source/cmSourceFile.cxx
index 5c4f18b40..0964bea6b 100644
--- a/Source/cmSourceFile.cxx
+++ b/Source/cmSourceFile.cxx
@@ -15,15 +15,13 @@
cmSourceFile::cmSourceFile(cmMakefile* mf, const std::string& name)
: Location(mf, name)
{
- this->CustomCommand = CM_NULLPTR;
+ this->CustomCommand = nullptr;
this->FindFullPathFailed = false;
- this->IsUiFile = (".ui" == cmSystemTools::GetFilenameLastExtension(
- this->Location.GetName()));
}
cmSourceFile::~cmSourceFile()
{
- this->SetCustomCommand(CM_NULLPTR);
+ this->SetCustomCommand(nullptr);
}
std::string const& cmSourceFile::GetExtension() const
@@ -131,17 +129,17 @@ bool cmSourceFile::FindFullPath(std::string* error)
// The file is not generated. It must exist on disk.
cmMakefile const* mf = this->Location.GetMakefile();
- const char* tryDirs[3] = { CM_NULLPTR, CM_NULLPTR, CM_NULLPTR };
+ const char* tryDirs[3] = { nullptr, nullptr, nullptr };
if (this->Location.DirectoryIsAmbiguous()) {
tryDirs[0] = mf->GetCurrentSourceDirectory();
tryDirs[1] = mf->GetCurrentBinaryDirectory();
} else {
tryDirs[0] = "";
}
- const std::vector<std::string>& srcExts =
- mf->GetCMakeInstance()->GetSourceExtensions();
- std::vector<std::string> hdrExts =
- mf->GetCMakeInstance()->GetHeaderExtensions();
+
+ cmake const* const cmakeInst = mf->GetCMakeInstance();
+ std::vector<std::string> const& srcExts = cmakeInst->GetSourceExtensions();
+ std::vector<std::string> const& hdrExts = cmakeInst->GetHeaderExtensions();
for (const char* const* di = tryDirs; *di; ++di) {
std::string tryPath = this->Location.GetDirectory();
if (!tryPath.empty()) {
@@ -152,15 +150,13 @@ bool cmSourceFile::FindFullPath(std::string* error)
if (this->TryFullPath(tryPath, "")) {
return true;
}
- for (std::vector<std::string>::const_iterator ei = srcExts.begin();
- ei != srcExts.end(); ++ei) {
- if (this->TryFullPath(tryPath, *ei)) {
+ for (std::string const& ext : srcExts) {
+ if (this->TryFullPath(tryPath, ext)) {
return true;
}
}
- for (std::vector<std::string>::const_iterator ei = hdrExts.begin();
- ei != hdrExts.end(); ++ei) {
- if (this->TryFullPath(tryPath, *ei)) {
+ for (std::string const& ext : hdrExts) {
+ if (this->TryFullPath(tryPath, ext)) {
return true;
}
}
@@ -173,13 +169,11 @@ bool cmSourceFile::FindFullPath(std::string* error)
}
missing += this->Location.GetName();
e << "Cannot find source file:\n " << missing << "\nTried extensions";
- for (std::vector<std::string>::const_iterator ext = srcExts.begin();
- ext != srcExts.end(); ++ext) {
- e << " ." << *ext;
+ for (std::string const& srcExt : srcExts) {
+ e << " ." << srcExt;
}
- for (std::vector<std::string>::const_iterator ext = hdrExts.begin();
- ext != hdrExts.end(); ++ext) {
- e << " ." << *ext;
+ for (std::string const& ext : hdrExts) {
+ e << " ." << ext;
}
if (error) {
*error = e.str();
@@ -245,13 +239,6 @@ bool cmSourceFile::Matches(cmSourceFileLocation const& loc)
void cmSourceFile::SetProperty(const std::string& prop, const char* value)
{
this->Properties.SetProperty(prop, value);
-
- if (this->IsUiFile) {
- cmMakefile const* mf = this->Location.GetMakefile();
- if (prop == "AUTOUIC_OPTIONS") {
- const_cast<cmMakefile*>(mf)->AddQtUiFileWithOptions(this);
- }
- }
}
void cmSourceFile::AppendProperty(const std::string& prop, const char* value,
@@ -290,7 +277,7 @@ const char* cmSourceFile::GetProperty(const std::string& prop) const
// Check for computed properties.
if (prop == "LOCATION") {
if (this->FullPath.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
return this->FullPath.c_str();
}
diff --git a/Source/cmSourceFile.h b/Source/cmSourceFile.h
index 0be659c5f..c2105d224 100644
--- a/Source/cmSourceFile.h
+++ b/Source/cmSourceFile.h
@@ -3,7 +3,7 @@
#ifndef cmSourceFile_h
#define cmSourceFile_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmPropertyMap.h"
#include "cmSourceFileLocation.h"
@@ -57,7 +57,7 @@ public:
* horrible interface, but is necessary for backwards
* compatibility).
*/
- std::string const& GetFullPath(std::string* error = CM_NULLPTR);
+ std::string const& GetFullPath(std::string* error = nullptr);
std::string const& GetFullPath() const;
/**
@@ -107,7 +107,6 @@ private:
std::string ObjectLibrary;
std::vector<std::string> Depends;
bool FindFullPathFailed;
- bool IsUiFile;
bool FindFullPath(std::string* error);
bool TryFullPath(const std::string& path, const std::string& ext);
@@ -120,4 +119,10 @@ private:
// TODO: Factor out into platform information modules.
#define CM_HEADER_REGEX "\\.(h|hh|h\\+\\+|hm|hpp|hxx|in|txx|inl)$"
+#define CM_SOURCE_REGEX \
+ "\\.(C|M|c|c\\+\\+|cc|cpp|cxx|f|f90|for|fpp|ftn|m|mm|rc|def|r|odl|idl|hpj" \
+ "|bat)$"
+
+#define CM_RESOURCE_REGEX "\\.(pdf|plist|png|jpeg|jpg|storyboard|xcassets)$"
+
#endif
diff --git a/Source/cmSourceFileLocation.cxx b/Source/cmSourceFileLocation.cxx
index 86711d784..4f337f246 100644
--- a/Source/cmSourceFileLocation.cxx
+++ b/Source/cmSourceFileLocation.cxx
@@ -2,8 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmSourceFileLocation.h"
-#include "cmConfigure.h"
-
#include "cmAlgorithms.h"
#include "cmGlobalGenerator.h"
#include "cmMakefile.h"
@@ -15,7 +13,7 @@
#include <vector>
cmSourceFileLocation::cmSourceFileLocation()
- : Makefile(CM_NULLPTR)
+ : Makefile(nullptr)
, AmbiguousDirectory(true)
, AmbiguousExtension(true)
{
@@ -30,21 +28,6 @@ cmSourceFileLocation::cmSourceFileLocation(const cmSourceFileLocation& loc)
this->Name = loc.Name;
}
-cmSourceFileLocation& cmSourceFileLocation::operator=(
- const cmSourceFileLocation& loc)
-{
- if (this == &loc) {
- return *this;
- }
- this->Makefile = loc.Makefile;
- this->AmbiguousDirectory = loc.AmbiguousDirectory;
- this->AmbiguousExtension = loc.AmbiguousExtension;
- this->Directory = loc.Directory;
- this->Name = loc.Name;
- this->UpdateExtension(this->Name);
- return *this;
-}
-
cmSourceFileLocation::cmSourceFileLocation(cmMakefile const* mf,
const std::string& name)
: Makefile(mf)
diff --git a/Source/cmSourceFileLocation.h b/Source/cmSourceFileLocation.h
index 6dbc2daed..467682db9 100644
--- a/Source/cmSourceFileLocation.h
+++ b/Source/cmSourceFileLocation.h
@@ -29,7 +29,6 @@ public:
cmSourceFileLocation(cmMakefile const* mf, const std::string& name);
cmSourceFileLocation();
cmSourceFileLocation(const cmSourceFileLocation& loc);
- cmSourceFileLocation& operator=(const cmSourceFileLocation& loc);
/**
* Return whether the given source file location could refers to the
@@ -79,7 +78,7 @@ public:
*/
cmMakefile const* GetMakefile() const { return this->Makefile; }
private:
- cmMakefile const* Makefile;
+ cmMakefile const* const Makefile;
bool AmbiguousDirectory;
bool AmbiguousExtension;
std::string Directory;
@@ -90,6 +89,8 @@ private:
// Update the location with additional knowledge.
void Update(cmSourceFileLocation const& loc);
void UpdateExtension(const std::string& name);
+
+ cmSourceFileLocation& operator=(const cmSourceFileLocation& loc) = delete;
};
#endif
diff --git a/Source/cmSourceGroup.cxx b/Source/cmSourceGroup.cxx
index 104e959a9..fba4c31d3 100644
--- a/Source/cmSourceGroup.cxx
+++ b/Source/cmSourceGroup.cxx
@@ -114,7 +114,7 @@ cmSourceGroup* cmSourceGroup::LookupChild(const char* name) const
}
// if no child with this name was found return NULL
- return CM_NULLPTR;
+ return nullptr;
}
cmSourceGroup* cmSourceGroup::MatchChildrenFiles(const char* name)
@@ -134,7 +134,7 @@ cmSourceGroup* cmSourceGroup::MatchChildrenFiles(const char* name)
return result;
}
}
- return CM_NULLPTR;
+ return nullptr;
}
cmSourceGroup* cmSourceGroup::MatchChildrenRegex(const char* name)
@@ -155,7 +155,7 @@ cmSourceGroup* cmSourceGroup::MatchChildrenRegex(const char* name)
return this;
}
- return CM_NULLPTR;
+ return nullptr;
}
std::vector<cmSourceGroup> const& cmSourceGroup::GetGroupChildren() const
diff --git a/Source/cmSourceGroup.h b/Source/cmSourceGroup.h
index 97affed6e..e8bd69767 100644
--- a/Source/cmSourceGroup.h
+++ b/Source/cmSourceGroup.h
@@ -3,7 +3,7 @@
#ifndef cmSourceGroup_h
#define cmSourceGroup_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmsys/RegularExpression.hxx"
#include <set>
@@ -27,7 +27,7 @@ class cmSourceGroup
{
public:
cmSourceGroup(const char* name, const char* regex,
- const char* parentName = CM_NULLPTR);
+ const char* parentName = nullptr);
cmSourceGroup(cmSourceGroup const& r);
~cmSourceGroup();
cmSourceGroup& operator=(cmSourceGroup const&);
diff --git a/Source/cmSourceGroupCommand.cxx b/Source/cmSourceGroupCommand.cxx
index a966300c0..69983a875 100644
--- a/Source/cmSourceGroupCommand.cxx
+++ b/Source/cmSourceGroupCommand.cxx
@@ -41,8 +41,8 @@ std::set<std::string> getSourceGroupFilesPaths(
std::set<std::string> ret;
const std::string::size_type rootLength = root.length();
- for (size_t i = 0; i < files.size(); ++i) {
- ret.insert(files[i].substr(rootLength + 1)); // +1 to also omnit last '/'
+ for (std::string const& file : files) {
+ ret.insert(file.substr(rootLength + 1)); // +1 to also omnit last '/'
}
return ret;
@@ -51,9 +51,9 @@ std::set<std::string> getSourceGroupFilesPaths(
bool rootIsPrefix(const std::string& root,
const std::vector<std::string>& files, std::string& error)
{
- for (size_t i = 0; i < files.size(); ++i) {
- if (!cmSystemTools::StringStartsWith(files[i], root.c_str())) {
- error = "ROOT: " + root + " is not a prefix of file: " + files[i];
+ for (std::string const& file : files) {
+ if (!cmSystemTools::StringStartsWith(file, root.c_str())) {
+ error = "ROOT: " + root + " is not a prefix of file: " + file;
return false;
}
}
@@ -61,23 +61,6 @@ bool rootIsPrefix(const std::string& root,
return true;
}
-cmSourceGroup* addSourceGroup(const std::vector<std::string>& tokenizedPath,
- cmMakefile& makefile)
-{
- cmSourceGroup* sg;
-
- sg = makefile.GetSourceGroup(tokenizedPath);
- if (!sg) {
- makefile.AddSourceGroup(tokenizedPath);
- sg = makefile.GetSourceGroup(tokenizedPath);
- if (!sg) {
- return CM_NULLPTR;
- }
- }
-
- return sg;
-}
-
std::string prepareFilePathForTree(const std::string& path,
const std::string& currentSourceDir)
{
@@ -108,26 +91,25 @@ bool addFilesToItsSourceGroups(const std::string& root,
{
cmSourceGroup* sg;
- for (std::set<std::string>::const_iterator it = sgFilesPaths.begin();
- it != sgFilesPaths.end(); ++it) {
+ for (std::string const& sgFilesPath : sgFilesPaths) {
std::vector<std::string> tokenizedPath;
if (!prefix.empty()) {
- tokenizedPath = tokenizePath(prefix + '/' + *it);
+ tokenizedPath = tokenizePath(prefix + '/' + sgFilesPath);
} else {
- tokenizedPath = tokenizePath(*it);
+ tokenizedPath = tokenizePath(sgFilesPath);
}
if (tokenizedPath.size() > 1) {
tokenizedPath.pop_back();
- sg = addSourceGroup(tokenizedPath, makefile);
+ sg = makefile.GetOrCreateSourceGroup(tokenizedPath);
if (!sg) {
- errorMsg = "Could not create source group for file: " + *it;
+ errorMsg = "Could not create source group for file: " + sgFilesPath;
return false;
}
- const std::string fullPath = getFullFilePath(root, *it);
+ const std::string fullPath = getFullFilePath(root, sgFilesPath);
sg->AddGroupFile(fullPath);
}
}
@@ -158,20 +140,7 @@ bool cmSourceGroupCommand::InitialPass(std::vector<std::string> const& args,
return true;
}
- std::string delimiter = "\\";
- if (this->Makefile->GetDefinition("SOURCE_GROUP_DELIMITER")) {
- delimiter = this->Makefile->GetDefinition("SOURCE_GROUP_DELIMITER");
- }
-
- std::vector<std::string> folders =
- cmSystemTools::tokenize(args[0], delimiter);
-
- cmSourceGroup* sg = CM_NULLPTR;
- sg = this->Makefile->GetSourceGroup(folders);
- if (!sg) {
- this->Makefile->AddSourceGroup(folders);
- sg = this->Makefile->GetSourceGroup(folders);
- }
+ cmSourceGroup* sg = this->Makefile->GetOrCreateSourceGroup(args[0]);
if (!sg) {
this->SetError("Could not create or find source group");
diff --git a/Source/cmSourceGroupCommand.h b/Source/cmSourceGroupCommand.h
index 7d56b0d65..ed02ca59a 100644
--- a/Source/cmSourceGroupCommand.h
+++ b/Source/cmSourceGroupCommand.h
@@ -3,7 +3,7 @@
#ifndef cmSourceGroupCommand_h
#define cmSourceGroupCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmSourceGroupCommand; }
+ cmCommand* Clone() override { return new cmSourceGroupCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
bool processTree(const std::vector<std::string>& args,
diff --git a/Source/cmState.cxx b/Source/cmState.cxx
index 92e47f748..5957b5bb2 100644
--- a/Source/cmState.cxx
+++ b/Source/cmState.cxx
@@ -63,12 +63,12 @@ const char* cmState::GetTargetTypeName(cmStateEnums::TargetType targetType)
return "UNKNOWN_LIBRARY";
}
assert(false && "Unexpected target type");
- return CM_NULLPTR;
+ return nullptr;
}
const char* cmCacheEntryTypes[] = { "BOOL", "PATH", "FILEPATH",
"STRING", "INTERNAL", "STATIC",
- "UNINITIALIZED", CM_NULLPTR };
+ "UNINITIALIZED", nullptr };
const char* cmState::CacheEntryTypeToString(cmStateEnums::CacheEntryType type)
{
@@ -132,7 +132,7 @@ const char* cmState::GetCacheEntryValue(std::string const& key) const
{
cmCacheManager::CacheEntry* e = this->CacheManager->GetCacheEntry(key);
if (!e) {
- return CM_NULLPTR;
+ return nullptr;
}
return e->Value.c_str();
}
@@ -188,7 +188,7 @@ const char* cmState::GetCacheEntryProperty(std::string const& key,
cmCacheManager::CacheIterator it =
this->CacheManager->GetCacheIterator(key.c_str());
if (!it.PropertyExists(propertyName)) {
- return CM_NULLPTR;
+ return nullptr;
}
return it.GetProperty(propertyName);
}
@@ -224,7 +224,7 @@ void cmState::RemoveCacheEntryProperty(std::string const& key,
std::string const& propertyName)
{
this->CacheManager->GetCacheIterator(key.c_str())
- .SetProperty(propertyName, (void*)CM_NULLPTR);
+ .SetProperty(propertyName, nullptr);
}
cmStateSnapshot cmState::Reset()
@@ -303,7 +303,7 @@ cmPropertyDefinition const* cmState::GetPropertyDefinition(
this->PropertyDefinitions.find(scope)->second;
return &defs.find(name)->second;
}
- return CM_NULLPTR;
+ return nullptr;
}
bool cmState::IsPropertyDefined(const std::string& name,
@@ -436,7 +436,7 @@ cmCommand* cmState::GetCommand(std::string const& name) const
if (pos != this->BuiltinCommands.end()) {
return pos->second;
}
- return CM_NULLPTR;
+ return nullptr;
}
std::vector<std::string> cmState::GetCommandNames() const
@@ -444,15 +444,11 @@ std::vector<std::string> cmState::GetCommandNames() const
std::vector<std::string> commandNames;
commandNames.reserve(this->BuiltinCommands.size() +
this->ScriptedCommands.size());
- for (std::map<std::string, cmCommand*>::const_iterator cmds =
- this->BuiltinCommands.begin();
- cmds != this->BuiltinCommands.end(); ++cmds) {
- commandNames.push_back(cmds->first);
+ for (auto const& bc : this->BuiltinCommands) {
+ commandNames.push_back(bc.first);
}
- for (std::map<std::string, cmCommand*>::const_iterator cmds =
- this->ScriptedCommands.begin();
- cmds != this->ScriptedCommands.end(); ++cmds) {
- commandNames.push_back(cmds->first);
+ for (auto const& sc : this->ScriptedCommands) {
+ commandNames.push_back(sc.first);
}
std::sort(commandNames.begin(), commandNames.end());
commandNames.erase(std::unique(commandNames.begin(), commandNames.end()),
diff --git a/Source/cmStateDirectory.cxx b/Source/cmStateDirectory.cxx
index 46a185848..85e6366d9 100644
--- a/Source/cmStateDirectory.cxx
+++ b/Source/cmStateDirectory.cxx
@@ -6,7 +6,6 @@
#include <algorithm>
#include <assert.h>
#include <iterator>
-#include <map>
#include <utility>
#include "cmProperty.h"
@@ -81,7 +80,7 @@ void cmStateDirectory::ComputeRelativePathTopBinary()
if (result.size() < 2 || result.substr(0, 2) != "//") {
this->DirectoryState->RelativePathTopBinary = result;
} else {
- this->DirectoryState->RelativePathTopBinary = "";
+ this->DirectoryState->RelativePathTopBinary.clear();
}
}
@@ -423,7 +422,7 @@ const char* cmStateDirectory::GetProperty(const std::string& prop,
bool chain) const
{
static std::string output;
- output = "";
+ output.clear();
if (prop == "PARENT_DIRECTORY") {
cmStateSnapshot parent = this->Snapshot_.GetBuildsystemDirectoryParent();
if (parent.IsValid()) {
@@ -443,9 +442,9 @@ const char* cmStateDirectory::GetProperty(const std::string& prop,
std::vector<std::string> child_dirs;
std::vector<cmStateSnapshot> const& children =
this->DirectoryState->Children;
- for (std::vector<cmStateSnapshot>::const_iterator ci = children.begin();
- ci != children.end(); ++ci) {
- child_dirs.push_back(ci->GetDirectory().GetCurrentSource());
+ child_dirs.reserve(children.size());
+ for (cmStateSnapshot const& ci : children) {
+ child_dirs.push_back(ci.GetDirectory().GetCurrentSource());
}
output = cmJoin(child_dirs, ";");
return output.c_str();
@@ -514,10 +513,8 @@ std::vector<std::string> cmStateDirectory::GetPropertyKeys() const
{
std::vector<std::string> keys;
keys.reserve(this->DirectoryState->Properties.size());
- for (cmPropertyMap::const_iterator it =
- this->DirectoryState->Properties.begin();
- it != this->DirectoryState->Properties.end(); ++it) {
- keys.push_back(it->first);
+ for (auto const& it : this->DirectoryState->Properties) {
+ keys.push_back(it.first);
}
return keys;
}
diff --git a/Source/cmStateSnapshot.cxx b/Source/cmStateSnapshot.cxx
index 77413c7b5..bdef3e529 100644
--- a/Source/cmStateSnapshot.cxx
+++ b/Source/cmStateSnapshot.cxx
@@ -220,7 +220,7 @@ void cmStateSnapshot::SetDefinition(std::string const& name,
void cmStateSnapshot::RemoveDefinition(std::string const& name)
{
- this->Position->Vars->Set(name, CM_NULLPTR);
+ this->Position->Vars->Set(name, nullptr);
}
std::vector<std::string> cmStateSnapshot::UnusedKeys() const
diff --git a/Source/cmStateSnapshot.h b/Source/cmStateSnapshot.h
index 6293803b9..94d6274b9 100644
--- a/Source/cmStateSnapshot.h
+++ b/Source/cmStateSnapshot.h
@@ -19,7 +19,7 @@ class cmStateDirectory;
class cmStateSnapshot
{
public:
- cmStateSnapshot(cmState* state = CM_NULLPTR);
+ cmStateSnapshot(cmState* state = nullptr);
cmStateSnapshot(cmState* state, cmStateDetail::PositionType position);
const char* GetDefinition(std::string const& name) const;
diff --git a/Source/cmStringCommand.cxx b/Source/cmStringCommand.cxx
index 7a097ba21..55af0785d 100644
--- a/Source/cmStringCommand.cxx
+++ b/Source/cmStringCommand.cxx
@@ -4,6 +4,7 @@
#include "cmsys/RegularExpression.hxx"
#include <ctype.h>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
@@ -15,7 +16,6 @@
#include "cmSystemTools.h"
#include "cmTimestamp.h"
#include "cmUuid.h"
-#include "cm_auto_ptr.hxx"
class cmExecutionStatus;
@@ -62,6 +62,9 @@ bool cmStringCommand::InitialPass(std::vector<std::string> const& args,
if (subCommand == "APPEND") {
return this->HandleAppendCommand(args);
}
+ if (subCommand == "PREPEND") {
+ return this->HandlePrependCommand(args);
+ }
if (subCommand == "CONCAT") {
return this->HandleConcatCommand(args);
}
@@ -105,8 +108,8 @@ bool cmStringCommand::HandleHashCommand(std::vector<std::string> const& args)
return false;
}
- CM_AUTO_PTR<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
- if (hash.get()) {
+ std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0].c_str()));
+ if (hash) {
std::string out = hash->HashString(args[2]);
this->Makefile->AddDefinition(args[1], out.c_str());
return true;
@@ -309,6 +312,7 @@ bool cmStringCommand::RegexMatchAll(std::vector<std::string> const& args)
std::string output;
const char* p = input.c_str();
while (re.find(p)) {
+ this->Makefile->ClearMatches();
this->Makefile->StoreMatches(re);
std::string::size_type l = re.start();
std::string::size_type r = re.end();
@@ -391,6 +395,7 @@ bool cmStringCommand::RegexReplace(std::vector<std::string> const& args)
std::string output;
std::string::size_type base = 0;
while (re.find(input.c_str() + base)) {
+ this->Makefile->ClearMatches();
this->Makefile->StoreMatches(re);
std::string::size_type l2 = re.start();
std::string::size_type r = re.end();
@@ -407,13 +412,13 @@ bool cmStringCommand::RegexReplace(std::vector<std::string> const& args)
}
// Concatenate the replacement for the match.
- for (unsigned int i = 0; i < replacement.size(); ++i) {
- if (replacement[i].number < 0) {
+ for (RegexReplacement const& i : replacement) {
+ if (i.number < 0) {
// This is just a plain-text part of the replacement.
- output += replacement[i].value;
+ output += i.value;
} else {
// Replace with part of the match.
- int n = replacement[i].number;
+ int n = i.number;
std::string::size_type start = re.start(n);
std::string::size_type end = re.end(n);
std::string::size_type len = input.length() - base;
@@ -641,6 +646,30 @@ bool cmStringCommand::HandleAppendCommand(std::vector<std::string> const& args)
return true;
}
+bool cmStringCommand::HandlePrependCommand(
+ std::vector<std::string> const& args)
+{
+ if (args.size() < 2) {
+ this->SetError("sub-command PREPEND requires at least one argument.");
+ return false;
+ }
+
+ // Skip if nothing to prepend.
+ if (args.size() < 3) {
+ return true;
+ }
+
+ const std::string& variable = args[1];
+
+ std::string value = cmJoin(cmMakeRange(args).advance(2), std::string());
+ const char* oldValue = this->Makefile->GetDefinition(variable);
+ if (oldValue) {
+ value += oldValue;
+ }
+ this->Makefile->AddDefinition(variable, value.c_str());
+ return true;
+}
+
bool cmStringCommand::HandleConcatCommand(std::vector<std::string> const& args)
{
if (args.size() < 2) {
@@ -789,7 +818,7 @@ bool cmStringCommand::HandleRandomCommand(std::vector<std::string> const& args)
const char* alphaPtr = alphabet.c_str();
int cc;
for (cc = 0; cc < length; cc++) {
- int idx = (int)(sizeofAlphabet * rand() / (RAND_MAX + 1.0));
+ int idx = static_cast<int>(sizeofAlphabet * rand() / (RAND_MAX + 1.0));
result.push_back(*(alphaPtr + idx));
}
result.push_back(0);
diff --git a/Source/cmStringCommand.h b/Source/cmStringCommand.h
index 88015ad5e..b287e37b7 100644
--- a/Source/cmStringCommand.h
+++ b/Source/cmStringCommand.h
@@ -3,7 +3,7 @@
#ifndef cmStringCommand_h
#define cmStringCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -22,14 +22,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmStringCommand; }
+ cmCommand* Clone() override { return new cmStringCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
protected:
bool HandleConfigureCommand(std::vector<std::string> const& args);
@@ -46,6 +46,7 @@ protected:
bool HandleLengthCommand(std::vector<std::string> const& args);
bool HandleSubstringCommand(std::vector<std::string> const& args);
bool HandleAppendCommand(std::vector<std::string> const& args);
+ bool HandlePrependCommand(std::vector<std::string> const& args);
bool HandleConcatCommand(std::vector<std::string> const& args);
bool HandleStripCommand(std::vector<std::string> const& args);
bool HandleRandomCommand(std::vector<std::string> const& args);
diff --git a/Source/cmSubdirCommand.cxx b/Source/cmSubdirCommand.cxx
index 3727dfa25..c74ca59bb 100644
--- a/Source/cmSubdirCommand.cxx
+++ b/Source/cmSubdirCommand.cxx
@@ -18,36 +18,35 @@ bool cmSubdirCommand::InitialPass(std::vector<std::string> const& args,
bool res = true;
bool excludeFromAll = false;
- for (std::vector<std::string>::const_iterator i = args.begin();
- i != args.end(); ++i) {
- if (*i == "EXCLUDE_FROM_ALL") {
+ for (std::string const& i : args) {
+ if (i == "EXCLUDE_FROM_ALL") {
excludeFromAll = true;
continue;
}
- if (*i == "PREORDER") {
+ if (i == "PREORDER") {
// Ignored
continue;
}
// if they specified a relative path then compute the full
std::string srcPath =
- std::string(this->Makefile->GetCurrentSourceDirectory()) + "/" + *i;
+ std::string(this->Makefile->GetCurrentSourceDirectory()) + "/" + i;
if (cmSystemTools::FileIsDirectory(srcPath)) {
std::string binPath =
- std::string(this->Makefile->GetCurrentBinaryDirectory()) + "/" + *i;
+ std::string(this->Makefile->GetCurrentBinaryDirectory()) + "/" + i;
this->Makefile->AddSubDirectory(srcPath, binPath, excludeFromAll, false);
}
// otherwise it is a full path
- else if (cmSystemTools::FileIsDirectory(*i)) {
+ else if (cmSystemTools::FileIsDirectory(i)) {
// we must compute the binPath from the srcPath, we just take the last
// element from the source path and use that
std::string binPath =
std::string(this->Makefile->GetCurrentBinaryDirectory()) + "/" +
- cmSystemTools::GetFilenameName(*i);
- this->Makefile->AddSubDirectory(*i, binPath, excludeFromAll, false);
+ cmSystemTools::GetFilenameName(i);
+ this->Makefile->AddSubDirectory(i, binPath, excludeFromAll, false);
} else {
std::string error = "Incorrect SUBDIRS command. Directory: ";
- error += *i + " does not exist.";
+ error += i + " does not exist.";
this->SetError(error);
res = false;
}
diff --git a/Source/cmSubdirCommand.h b/Source/cmSubdirCommand.h
index a2af0fd58..adab75711 100644
--- a/Source/cmSubdirCommand.h
+++ b/Source/cmSubdirCommand.h
@@ -3,7 +3,7 @@
#ifndef cmSubdirCommand_h
#define cmSubdirCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -25,14 +25,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmSubdirCommand; }
+ cmCommand* Clone() override { return new cmSubdirCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmSubdirDependsCommand.h b/Source/cmSubdirDependsCommand.h
index d8ea9284f..2db28c66c 100644
--- a/Source/cmSubdirDependsCommand.h
+++ b/Source/cmSubdirDependsCommand.h
@@ -3,7 +3,7 @@
#ifndef cmSubdirDependsCommand_h
#define cmSubdirDependsCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,9 +15,9 @@ class cmExecutionStatus;
class cmSubdirDependsCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmSubdirDependsCommand; }
+ cmCommand* Clone() override { return new cmSubdirDependsCommand; }
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmSystemTools.cxx b/Source/cmSystemTools.cxx
index f7192e0b6..63c1452e6 100644
--- a/Source/cmSystemTools.cxx
+++ b/Source/cmSystemTools.cxx
@@ -353,8 +353,8 @@ bool cmSystemTools::IsInternallyOn(const char* val)
return false;
}
- for (std::string::iterator c = v.begin(); c != v.end(); c++) {
- *c = static_cast<char>(toupper(*c));
+ for (char& c : v) {
+ c = static_cast<char>(toupper(c));
}
return v == "I_ON";
}
@@ -378,8 +378,8 @@ bool cmSystemTools::IsOn(const char* val)
onValues.insert("TRUE");
onValues.insert("Y");
}
- for (std::string::iterator c = v.begin(); c != v.end(); c++) {
- *c = static_cast<char>(toupper(*c));
+ for (char& c : v) {
+ c = static_cast<char>(toupper(c));
}
return (onValues.count(v) > 0);
}
@@ -414,8 +414,8 @@ bool cmSystemTools::IsOff(const char* val)
}
// Try and avoid toupper().
std::string v(val, len);
- for (std::string::iterator c = v.begin(); c != v.end(); c++) {
- *c = static_cast<char>(toupper(*c));
+ for (char& c : v) {
+ c = static_cast<char>(toupper(c));
}
return (offValues.count(v) > 0);
}
@@ -458,7 +458,7 @@ void cmSystemTools::ParseWindowsCommandLine(const char* command,
arg.append(1, *c);
} else if (in_argument) {
args.push_back(arg);
- arg = "";
+ arg.clear();
in_argument = false;
}
} else {
@@ -559,7 +559,7 @@ std::vector<std::string> cmSystemTools::ParseArguments(const char* command)
while (*c == ' ' || *c == '\t') {
++c;
}
- arg = "";
+ arg.clear();
if (*c == '"') {
// Parse a quoted argument.
++c;
@@ -603,6 +603,56 @@ std::vector<std::string> cmSystemTools::ParseArguments(const char* command)
return args;
}
+bool cmSystemTools::SplitProgramFromArgs(std::string const& command,
+ std::string& program,
+ std::string& args)
+{
+ const char* c = command.c_str();
+
+ // Skip leading whitespace.
+ while (isspace(static_cast<unsigned char>(*c))) {
+ ++c;
+ }
+
+ // Parse one command-line element up to an unquoted space.
+ bool in_escape = false;
+ bool in_double = false;
+ bool in_single = false;
+ for (; *c; ++c) {
+ if (in_single) {
+ if (*c == '\'') {
+ in_single = false;
+ } else {
+ program += *c;
+ }
+ } else if (in_escape) {
+ in_escape = false;
+ program += *c;
+ } else if (*c == '\\') {
+ in_escape = true;
+ } else if (in_double) {
+ if (*c == '"') {
+ in_double = false;
+ } else {
+ program += *c;
+ }
+ } else if (*c == '"') {
+ in_double = true;
+ } else if (*c == '\'') {
+ in_single = true;
+ } else if (isspace(static_cast<unsigned char>(*c))) {
+ break;
+ } else {
+ program += *c;
+ }
+ }
+
+ // The remainder of the command line holds unparsed arguments.
+ args = c;
+
+ return !in_single && !in_escape && !in_double;
+}
+
size_t cmSystemTools::CalculateCommandLineLengthLimit()
{
size_t sz =
@@ -650,11 +700,11 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
double timeout, Encoding encoding)
{
std::vector<const char*> argv;
- for (std::vector<std::string>::const_iterator a = command.begin();
- a != command.end(); ++a) {
- argv.push_back(a->c_str());
+ argv.reserve(command.size() + 1);
+ for (std::string const& cmd : command) {
+ argv.push_back(cmd.c_str());
}
- argv.push_back(CM_NULLPTR);
+ argv.push_back(nullptr);
cmsysProcess* cp = cmsysProcess_New();
cmsysProcess_SetCommand(cp, &*argv.begin());
@@ -666,12 +716,12 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
if (outputflag == OUTPUT_PASSTHROUGH) {
cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
- captureStdOut = CM_NULLPTR;
- captureStdErr = CM_NULLPTR;
+ captureStdOut = nullptr;
+ captureStdErr = nullptr;
} else if (outputflag == OUTPUT_MERGE ||
(captureStdErr && captureStdErr == captureStdOut)) {
cmsysProcess_SetOption(cp, cmsysProcess_Option_MergeOutput, 1);
- captureStdErr = CM_NULLPTR;
+ captureStdErr = nullptr;
}
assert(!captureStdErr || captureStdErr != captureStdOut);
@@ -687,7 +737,7 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
std::string strdata;
if (outputflag != OUTPUT_PASSTHROUGH &&
(captureStdOut || captureStdErr || outputflag != OUTPUT_NONE)) {
- while ((pipe = cmsysProcess_WaitForData(cp, &data, &length, CM_NULLPTR)) >
+ while ((pipe = cmsysProcess_WaitForData(cp, &data, &length, nullptr)) >
0) {
// Translate NULL characters in the output into valid text.
for (int i = 0; i < length; ++i) {
@@ -727,7 +777,7 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
}
}
- cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ cmsysProcess_WaitForExit(cp, nullptr);
if (captureStdOut) {
captureStdOut->assign(tempStdOut.begin(), tempStdOut.end());
@@ -754,6 +804,8 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
}
if (captureStdErr) {
captureStdErr->append(exception_str, strlen(exception_str));
+ } else if (captureStdOut) {
+ captureStdOut->append(exception_str, strlen(exception_str));
}
result = false;
} else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Error) {
@@ -763,6 +815,8 @@ bool cmSystemTools::RunSingleCommand(std::vector<std::string> const& command,
}
if (captureStdErr) {
captureStdErr->append(error_str, strlen(error_str));
+ } else if (captureStdOut) {
+ captureStdOut->append(error_str, strlen(error_str));
}
result = false;
} else if (cmsysProcess_GetState(cp) == cmsysProcess_State_Expired) {
@@ -814,11 +868,10 @@ bool cmSystemTools::DoesFileExistWithExtensions(
{
std::string hname;
- for (std::vector<std::string>::const_iterator ext = headerExts.begin();
- ext != headerExts.end(); ++ext) {
+ for (std::string const& headerExt : headerExts) {
hname = name;
hname += ".";
- hname += *ext;
+ hname += headerExt;
if (cmSystemTools::FileExists(hname.c_str())) {
return true;
}
@@ -934,19 +987,17 @@ bool cmSystemTools::RenameFile(const char* oldname, const char* newname)
#endif
}
-bool cmSystemTools::ComputeFileMD5(const std::string& source, char* md5out)
+std::string cmSystemTools::ComputeFileHash(const std::string& source,
+ cmCryptoHash::Algo algo)
{
#if defined(CMAKE_BUILD_WITH_CMAKE)
- cmCryptoHash md5(cmCryptoHash::AlgoMD5);
- std::string const str = md5.HashFile(source);
- strncpy(md5out, str.c_str(), 32);
- return !str.empty();
+ cmCryptoHash hash(algo);
+ return hash.HashFile(source);
#else
(void)source;
- (void)md5out;
- cmSystemTools::Message("md5sum not supported in bootstrapping mode",
+ cmSystemTools::Message("hashsum not supported in bootstrapping mode",
"Error");
- return false;
+ return std::string();
#endif
}
@@ -1138,7 +1189,7 @@ void cmSystemTools::ExpandListArgument(const std::string& arg,
if (!newArg.empty() || emptyArgs) {
// Add the last argument if the string is not empty.
newargs.push_back(newArg);
- newArg = "";
+ newArg.clear();
}
}
} break;
@@ -1329,7 +1380,7 @@ std::string cmSystemTools::CollapseCombinedPath(std::string const& dir,
if (fileComponents.empty()) {
return dir;
}
- if (fileComponents[0] != "") {
+ if (!fileComponents[0].empty()) {
// File is not a relative path.
return file;
}
@@ -1369,9 +1420,8 @@ std::vector<std::string> cmSystemTools::GetEnvironmentVariables()
void cmSystemTools::AppendEnv(std::vector<std::string> const& env)
{
- for (std::vector<std::string>::const_iterator eit = env.begin();
- eit != env.end(); ++eit) {
- cmSystemTools::PutEnv(*eit);
+ for (std::string const& eit : env) {
+ cmSystemTools::PutEnv(eit);
}
}
@@ -1384,10 +1434,7 @@ cmSystemTools::SaveRestoreEnvironment::~SaveRestoreEnvironment()
{
// First clear everything in the current environment:
std::vector<std::string> currentEnv = GetEnvironmentVariables();
- for (std::vector<std::string>::const_iterator eit = currentEnv.begin();
- eit != currentEnv.end(); ++eit) {
- std::string var(*eit);
-
+ for (std::string var : currentEnv) {
std::string::size_type pos = var.find('=');
if (pos != std::string::npos) {
var = var.substr(0, pos);
@@ -1466,9 +1513,7 @@ bool cmSystemTools::CreateTar(const char* outFileName,
a.SetMTime(mtime);
a.SetVerbose(verbose);
- for (std::vector<std::string>::const_iterator i = files.begin();
- i != files.end(); ++i) {
- std::string path = *i;
+ for (auto path : files) {
if (cmSystemTools::FileIsFullPath(path.c_str())) {
// Get the relative path to the file.
path = cmSystemTools::RelativePath(cwd.c_str(), path.c_str());
@@ -1520,22 +1565,22 @@ void list_item_verbose(FILE* out, struct archive_entry* entry)
/* Use uname if it's present, else uid. */
p = archive_entry_uname(entry);
- if ((p == CM_NULLPTR) || (*p == '\0')) {
- sprintf(tmp, "%lu ", (unsigned long)archive_entry_uid(entry));
+ if ((p == nullptr) || (*p == '\0')) {
+ sprintf(tmp, "%lu ", static_cast<unsigned long>(archive_entry_uid(entry)));
p = tmp;
}
w = strlen(p);
if (w > u_width) {
u_width = w;
}
- fprintf(out, "%-*s ", (int)u_width, p);
+ fprintf(out, "%-*s ", static_cast<int>(u_width), p);
/* Use gname if it's present, else gid. */
p = archive_entry_gname(entry);
- if (p != CM_NULLPTR && p[0] != '\0') {
+ if (p != nullptr && p[0] != '\0') {
fprintf(out, "%s", p);
w = strlen(p);
} else {
- sprintf(tmp, "%lu", (unsigned long)archive_entry_gid(entry));
+ sprintf(tmp, "%lu", static_cast<unsigned long>(archive_entry_gid(entry)));
w = strlen(tmp);
fprintf(out, "%s", tmp);
}
@@ -1547,8 +1592,9 @@ void list_item_verbose(FILE* out, struct archive_entry* entry)
*/
if (archive_entry_filetype(entry) == AE_IFCHR ||
archive_entry_filetype(entry) == AE_IFBLK) {
- sprintf(tmp, "%lu,%lu", (unsigned long)archive_entry_rdevmajor(entry),
- (unsigned long)archive_entry_rdevminor(entry));
+ unsigned long rdevmajor = archive_entry_rdevmajor(entry);
+ unsigned long rdevminor = archive_entry_rdevminor(entry);
+ sprintf(tmp, "%lu,%lu", rdevmajor, rdevminor);
} else {
/*
* Note the use of platform-dependent macros to format
@@ -1556,12 +1602,12 @@ void list_item_verbose(FILE* out, struct archive_entry* entry)
* corresponding type for the cast.
*/
sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
- (BSDTAR_FILESIZE_TYPE)archive_entry_size(entry));
+ static_cast<BSDTAR_FILESIZE_TYPE>(archive_entry_size(entry)));
}
if (w + strlen(tmp) >= gs_width) {
gs_width = w + strlen(tmp) + 1;
}
- fprintf(out, "%*s", (int)(gs_width - w), tmp);
+ fprintf(out, "%*s", static_cast<int>(gs_width - w), tmp);
/* Format the time using 'ls -l' conventions. */
tim = archive_entry_mtime(entry);
@@ -1730,7 +1776,7 @@ int cmSystemTools::WaitForLine(cmsysProcess* process, std::string& line,
double timeout, std::vector<char>& out,
std::vector<char>& err)
{
- line = "";
+ line.clear();
std::vector<char>::iterator outiter = out.begin();
std::vector<char>::iterator erriter = err.begin();
cmProcessOutput processOutput;
@@ -1973,7 +2019,7 @@ unsigned int cmSystemTools::RandomSeed()
// Try using a real random source.
cmsys::ifstream fin;
- fin.rdbuf()->pubsetbuf(CM_NULLPTR, 0); // Unbuffered read.
+ fin.rdbuf()->pubsetbuf(nullptr, 0); // Unbuffered read.
fin.open("/dev/urandom");
if (fin.good() && fin.read(seed.bytes, sizeof(seed)) &&
fin.gcount() == sizeof(seed)) {
@@ -1982,7 +2028,7 @@ unsigned int cmSystemTools::RandomSeed()
// Fall back to the time and pid.
struct timeval t;
- gettimeofday(&t, CM_NULLPTR);
+ gettimeofday(&t, nullptr);
unsigned int pid = static_cast<unsigned int>(getpid());
unsigned int tv_sec = static_cast<unsigned int>(t.tv_sec);
unsigned int tv_usec = static_cast<unsigned int>(t.tv_usec);
@@ -2020,7 +2066,7 @@ void cmSystemTools::FindCMakeResources(const char* argv0)
#undef CM_EXE_PATH_LOCAL_SIZE
char* exe_path = exe_path_local;
if (_NSGetExecutablePath(exe_path, &exe_path_size) < 0) {
- exe_path = (char*)malloc(exe_path_size);
+ exe_path = static_cast<char*>(malloc(exe_path_size));
_NSGetExecutablePath(exe_path, &exe_path_size);
}
exe_dir =
@@ -2070,19 +2116,19 @@ void cmSystemTools::FindCMakeResources(const char* argv0)
cmSystemToolsCMakeGUICommand += "/cmake-gui";
cmSystemToolsCMakeGUICommand += cmSystemTools::GetExecutableExtension();
if (!cmSystemTools::FileExists(cmSystemToolsCMakeGUICommand.c_str())) {
- cmSystemToolsCMakeGUICommand = "";
+ cmSystemToolsCMakeGUICommand.clear();
}
cmSystemToolsCMakeCursesCommand = exe_dir;
cmSystemToolsCMakeCursesCommand += "/ccmake";
cmSystemToolsCMakeCursesCommand += cmSystemTools::GetExecutableExtension();
if (!cmSystemTools::FileExists(cmSystemToolsCMakeCursesCommand.c_str())) {
- cmSystemToolsCMakeCursesCommand = "";
+ cmSystemToolsCMakeCursesCommand.clear();
}
cmSystemToolsCMClDepsCommand = exe_dir;
cmSystemToolsCMClDepsCommand += "/cmcldeps";
cmSystemToolsCMClDepsCommand += cmSystemTools::GetExecutableExtension();
if (!cmSystemTools::FileExists(cmSystemToolsCMClDepsCommand.c_str())) {
- cmSystemToolsCMClDepsCommand = "";
+ cmSystemToolsCMClDepsCommand.clear();
}
#ifdef CMAKE_BUILD_WITH_CMAKE
@@ -2280,12 +2326,12 @@ struct cmSystemToolsRPathInfo
};
#endif
+#if defined(CMAKE_USE_ELF_PARSER)
bool cmSystemTools::ChangeRPath(std::string const& file,
std::string const& oldRPath,
std::string const& newRPath, std::string* emsg,
bool* changed)
{
-#if defined(CMAKE_USE_ELF_PARSER)
if (changed) {
*changed = false;
}
@@ -2298,8 +2344,8 @@ bool cmSystemTools::ChangeRPath(std::string const& file,
// Get the RPATH and RUNPATH entries from it.
int se_count = 0;
- cmELF::StringEntry const* se[2] = { CM_NULLPTR, CM_NULLPTR };
- const char* se_name[2] = { CM_NULLPTR, CM_NULLPTR };
+ cmELF::StringEntry const* se[2] = { nullptr, nullptr };
+ const char* se_name[2] = { nullptr, nullptr };
if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
se[se_count] = se_rpath;
se_name[se_count] = "RPATH";
@@ -2451,15 +2497,16 @@ bool cmSystemTools::ChangeRPath(std::string const& file,
*changed = true;
}
return true;
+}
#else
- (void)file;
- (void)oldRPath;
- (void)newRPath;
- (void)emsg;
- (void)changed;
+bool cmSystemTools::ChangeRPath(std::string const& /*file*/,
+ std::string const& /*oldRPath*/,
+ std::string const& /*newRPath*/,
+ std::string* /*emsg*/, bool* /*changed*/)
+{
return false;
-#endif
}
+#endif
bool cmSystemTools::VersionCompare(cmSystemTools::CompareOp op,
const char* lhss, const char* rhss)
@@ -2593,10 +2640,10 @@ int cmSystemTools::strverscmp(std::string const& lhs, std::string const& rhs)
return cm_strverscmp(lhs.c_str(), rhs.c_str());
}
+#if defined(CMAKE_USE_ELF_PARSER)
bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
bool* removed)
{
-#if defined(CMAKE_USE_ELF_PARSER)
if (removed) {
*removed = false;
}
@@ -2612,7 +2659,7 @@ bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
// Get the RPATH and RUNPATH entries from it and sort them by index
// in the dynamic section header.
int se_count = 0;
- cmELF::StringEntry const* se[2] = { CM_NULLPTR, CM_NULLPTR };
+ cmELF::StringEntry const* se[2] = { nullptr, nullptr };
if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
se[se_count++] = se_rpath;
}
@@ -2734,13 +2781,14 @@ bool cmSystemTools::RemoveRPath(std::string const& file, std::string* emsg,
*removed = true;
}
return true;
+}
#else
- (void)file;
- (void)emsg;
- (void)removed;
+bool cmSystemTools::RemoveRPath(std::string const& /*file*/,
+ std::string* /*emsg*/, bool* /*removed*/)
+{
return false;
-#endif
}
+#endif
bool cmSystemTools::CheckRPath(std::string const& file,
std::string const& newRPath)
diff --git a/Source/cmSystemTools.h b/Source/cmSystemTools.h
index 9de796728..e7082e6b1 100644
--- a/Source/cmSystemTools.h
+++ b/Source/cmSystemTools.h
@@ -3,8 +3,9 @@
#ifndef cmSystemTools_h
#define cmSystemTools_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
+#include "cmCryptoHash.h"
#include "cmProcessOutput.h"
#include "cmsys/Process.h"
#include "cmsys/SystemTools.hxx" // IWYU pragma: export
@@ -61,34 +62,34 @@ public:
* set to false, will disable furthur messages (cancel).
*/
static void SetMessageCallback(MessageCallback f,
- void* clientData = CM_NULLPTR);
+ void* clientData = nullptr);
/**
* Display an error message.
*/
- static void Error(const char* m, const char* m2 = CM_NULLPTR,
- const char* m3 = CM_NULLPTR, const char* m4 = CM_NULLPTR);
+ static void Error(const char* m, const char* m2 = nullptr,
+ const char* m3 = nullptr, const char* m4 = nullptr);
/**
* Display a message.
*/
- static void Message(const char* m, const char* title = CM_NULLPTR);
+ static void Message(const char* m, const char* title = nullptr);
typedef void (*OutputCallback)(const char*, size_t length, void*);
///! Send a string to stdout
static void Stdout(const char* s);
static void Stdout(const char* s, size_t length);
- static void SetStdoutCallback(OutputCallback, void* clientData = CM_NULLPTR);
+ static void SetStdoutCallback(OutputCallback, void* clientData = nullptr);
///! Send a string to stderr
static void Stderr(const char* s);
static void Stderr(const char* s, size_t length);
- static void SetStderrCallback(OutputCallback, void* clientData = CM_NULLPTR);
+ static void SetStderrCallback(OutputCallback, void* clientData = nullptr);
typedef bool (*InterruptCallback)(void*);
static void SetInterruptCallback(InterruptCallback f,
- void* clientData = CM_NULLPTR);
+ void* clientData = nullptr);
static bool GetInterruptFlag();
///! Return true if there was an error at any point.
@@ -179,8 +180,9 @@ public:
if possible). */
static bool RenameFile(const char* oldname, const char* newname);
- ///! Compute the md5sum of a file
- static bool ComputeFileMD5(const std::string& source, char* md5out);
+ ///! Compute the hash of a file
+ static std::string ComputeFileHash(const std::string& source,
+ cmCryptoHash::Algo algo);
/** Compute the md5sum of a string. */
static std::string ComputeStringMD5(const std::string& input);
@@ -218,10 +220,10 @@ public:
OUTPUT_PASSTHROUGH
};
static bool RunSingleCommand(const char* command,
- std::string* captureStdOut = CM_NULLPTR,
- std::string* captureStdErr = CM_NULLPTR,
- int* retVal = CM_NULLPTR,
- const char* dir = CM_NULLPTR,
+ std::string* captureStdOut = nullptr,
+ std::string* captureStdErr = nullptr,
+ int* retVal = nullptr,
+ const char* dir = nullptr,
OutputOption outputflag = OUTPUT_MERGE,
double timeout = 0.0);
/**
@@ -230,10 +232,10 @@ public:
* be in comand[1]...command[command.size()]
*/
static bool RunSingleCommand(std::vector<std::string> const& command,
- std::string* captureStdOut = CM_NULLPTR,
- std::string* captureStdErr = CM_NULLPTR,
- int* retVal = CM_NULLPTR,
- const char* dir = CM_NULLPTR,
+ std::string* captureStdOut = nullptr,
+ std::string* captureStdErr = nullptr,
+ int* retVal = nullptr,
+ const char* dir = nullptr,
OutputOption outputflag = OUTPUT_MERGE,
double timeout = 0.0,
Encoding encoding = cmProcessOutput::Auto);
@@ -253,6 +255,11 @@ public:
static void ParseUnixCommandLine(const char* command,
std::vector<std::string>& args);
+ /** Split a command-line string into the parsed command and the unparsed
+ arguments. Returns false on unfinished quoting or escaping. */
+ static bool SplitProgramFromArgs(std::string const& command,
+ std::string& program, std::string& args);
+
/**
* Handle response file in an argument list and return a new argument list
* **/
@@ -461,13 +468,12 @@ public:
/** Try to set the RPATH in an ELF binary. */
static bool ChangeRPath(std::string const& file, std::string const& oldRPath,
std::string const& newRPath,
- std::string* emsg = CM_NULLPTR,
- bool* changed = CM_NULLPTR);
+ std::string* emsg = nullptr,
+ bool* changed = nullptr);
/** Try to remove the RPATH from an ELF binary. */
- static bool RemoveRPath(std::string const& file,
- std::string* emsg = CM_NULLPTR,
- bool* removed = CM_NULLPTR);
+ static bool RemoveRPath(std::string const& file, std::string* emsg = nullptr,
+ bool* removed = nullptr);
/** Check whether the RPATH in an ELF binary contains the path
given. */
diff --git a/Source/cmTarget.cxx b/Source/cmTarget.cxx
index c95a3ca2c..c6cd5026f 100644
--- a/Source/cmTarget.cxx
+++ b/Source/cmTarget.cxx
@@ -5,10 +5,12 @@
#include "cmsys/RegularExpression.hxx"
#include <algorithm>
#include <assert.h>
+#include <iterator>
#include <map>
#include <set>
#include <sstream>
#include <string.h>
+#include <unordered_set>
#include "cmAlgorithms.h"
#include "cmGeneratorExpression.h"
@@ -26,7 +28,6 @@
#include "cmStateSnapshot.h"
#include "cmSystemTools.h"
#include "cmTargetPropertyComputer.h"
-#include "cm_unordered_set.hxx"
#include "cmake.h"
template <>
@@ -75,27 +76,23 @@ const char* cmTargetPropertyComputer::GetSources<cmTarget>(
{
cmStringRange entries = tgt->GetSourceEntries();
if (entries.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
std::ostringstream ss;
const char* sep = "";
- for (std::vector<std::string>::const_iterator i = entries.begin();
- i != entries.end(); ++i) {
- std::string const& entry = *i;
-
+ for (std::string const& entry : entries) {
std::vector<std::string> files;
cmSystemTools::ExpandListArgument(entry, files);
- for (std::vector<std::string>::const_iterator li = files.begin();
- li != files.end(); ++li) {
- if (cmHasLiteralPrefix(*li, "$<TARGET_OBJECTS:") &&
- (*li)[li->size() - 1] == '>') {
- std::string objLibName = li->substr(17, li->size() - 18);
+ for (std::string const& file : files) {
+ if (cmHasLiteralPrefix(file, "$<TARGET_OBJECTS:") &&
+ file[file.size() - 1] == '>') {
+ std::string objLibName = file.substr(17, file.size() - 18);
if (cmGeneratorExpression::Find(objLibName) != std::string::npos) {
ss << sep;
sep = ";";
- ss << *li;
+ ss << file;
continue;
}
@@ -130,14 +127,14 @@ const char* cmTargetPropertyComputer::GetSources<cmTarget>(
if (addContent) {
ss << sep;
sep = ";";
- ss << *li;
+ ss << file;
}
- } else if (cmGeneratorExpression::Find(*li) == std::string::npos) {
+ } else if (cmGeneratorExpression::Find(file) == std::string::npos) {
ss << sep;
sep = ";";
- ss << *li;
+ ss << file;
} else {
- cmSourceFile* sf = tgt->GetMakefile()->GetOrCreateSource(*li);
+ cmSourceFile* sf = tgt->GetMakefile()->GetOrCreateSource(file);
// Construct what is known about this source file location.
cmSourceFileLocation const& location = sf->GetLocation();
std::string sname = location.GetDirectory();
@@ -211,77 +208,79 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
// Setup default property values.
if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
this->GetType() != cmStateEnums::UTILITY) {
- this->SetPropertyDefault("ANDROID_API", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_API_MIN", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_ARCH", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_STL_TYPE", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_SKIP_ANT_STEP", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_PROCESS_MAX", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_PROGUARD", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_PROGUARD_CONFIG_PATH", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_SECURE_PROPS_PATH", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_NATIVE_LIB_DIRECTORIES", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_NATIVE_LIB_DEPENDENCIES", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_JAVA_SOURCE_DIR", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_JAR_DIRECTORIES", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_JAR_DEPENDENCIES", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_ASSETS_DIRECTORIES", CM_NULLPTR);
- this->SetPropertyDefault("ANDROID_ANT_ADDITIONAL_OPTIONS", CM_NULLPTR);
- this->SetPropertyDefault("BUILD_RPATH", CM_NULLPTR);
- this->SetPropertyDefault("INSTALL_NAME_DIR", CM_NULLPTR);
+ this->SetPropertyDefault("ANDROID_API", nullptr);
+ this->SetPropertyDefault("ANDROID_API_MIN", nullptr);
+ this->SetPropertyDefault("ANDROID_ARCH", nullptr);
+ this->SetPropertyDefault("ANDROID_STL_TYPE", nullptr);
+ this->SetPropertyDefault("ANDROID_SKIP_ANT_STEP", nullptr);
+ this->SetPropertyDefault("ANDROID_PROCESS_MAX", nullptr);
+ this->SetPropertyDefault("ANDROID_PROGUARD", nullptr);
+ this->SetPropertyDefault("ANDROID_PROGUARD_CONFIG_PATH", nullptr);
+ this->SetPropertyDefault("ANDROID_SECURE_PROPS_PATH", nullptr);
+ this->SetPropertyDefault("ANDROID_NATIVE_LIB_DIRECTORIES", nullptr);
+ this->SetPropertyDefault("ANDROID_NATIVE_LIB_DEPENDENCIES", nullptr);
+ this->SetPropertyDefault("ANDROID_JAVA_SOURCE_DIR", nullptr);
+ this->SetPropertyDefault("ANDROID_JAR_DIRECTORIES", nullptr);
+ this->SetPropertyDefault("ANDROID_JAR_DEPENDENCIES", nullptr);
+ this->SetPropertyDefault("ANDROID_ASSETS_DIRECTORIES", nullptr);
+ this->SetPropertyDefault("ANDROID_ANT_ADDITIONAL_OPTIONS", nullptr);
+ this->SetPropertyDefault("BUILD_RPATH", nullptr);
+ this->SetPropertyDefault("INSTALL_NAME_DIR", nullptr);
this->SetPropertyDefault("INSTALL_RPATH", "");
this->SetPropertyDefault("INSTALL_RPATH_USE_LINK_PATH", "OFF");
- this->SetPropertyDefault("INTERPROCEDURAL_OPTIMIZATION", CM_NULLPTR);
+ this->SetPropertyDefault("INTERPROCEDURAL_OPTIMIZATION", nullptr);
this->SetPropertyDefault("SKIP_BUILD_RPATH", "OFF");
this->SetPropertyDefault("BUILD_WITH_INSTALL_RPATH", "OFF");
- this->SetPropertyDefault("ARCHIVE_OUTPUT_DIRECTORY", CM_NULLPTR);
- this->SetPropertyDefault("LIBRARY_OUTPUT_DIRECTORY", CM_NULLPTR);
- this->SetPropertyDefault("RUNTIME_OUTPUT_DIRECTORY", CM_NULLPTR);
- this->SetPropertyDefault("PDB_OUTPUT_DIRECTORY", CM_NULLPTR);
- this->SetPropertyDefault("COMPILE_PDB_OUTPUT_DIRECTORY", CM_NULLPTR);
- this->SetPropertyDefault("Fortran_FORMAT", CM_NULLPTR);
- this->SetPropertyDefault("Fortran_MODULE_DIRECTORY", CM_NULLPTR);
- this->SetPropertyDefault("GNUtoMS", CM_NULLPTR);
- this->SetPropertyDefault("OSX_ARCHITECTURES", CM_NULLPTR);
- this->SetPropertyDefault("IOS_INSTALL_COMBINED", CM_NULLPTR);
- this->SetPropertyDefault("AUTOMOC", CM_NULLPTR);
- this->SetPropertyDefault("AUTOUIC", CM_NULLPTR);
- this->SetPropertyDefault("AUTORCC", CM_NULLPTR);
- this->SetPropertyDefault("AUTOMOC_DEPEND_FILTERS", CM_NULLPTR);
- this->SetPropertyDefault("AUTOMOC_MOC_OPTIONS", CM_NULLPTR);
- this->SetPropertyDefault("AUTOUIC_OPTIONS", CM_NULLPTR);
- this->SetPropertyDefault("AUTOUIC_SEARCH_PATHS", CM_NULLPTR);
- this->SetPropertyDefault("AUTORCC_OPTIONS", CM_NULLPTR);
- this->SetPropertyDefault("LINK_DEPENDS_NO_SHARED", CM_NULLPTR);
- this->SetPropertyDefault("LINK_INTERFACE_LIBRARIES", CM_NULLPTR);
- this->SetPropertyDefault("WIN32_EXECUTABLE", CM_NULLPTR);
- this->SetPropertyDefault("MACOSX_BUNDLE", CM_NULLPTR);
- this->SetPropertyDefault("MACOSX_RPATH", CM_NULLPTR);
- this->SetPropertyDefault("BUILD_WITH_INSTALL_NAME_DIR", CM_NULLPTR);
- this->SetPropertyDefault("C_CLANG_TIDY", CM_NULLPTR);
- this->SetPropertyDefault("C_COMPILER_LAUNCHER", CM_NULLPTR);
- this->SetPropertyDefault("C_CPPLINT", CM_NULLPTR);
- this->SetPropertyDefault("C_INCLUDE_WHAT_YOU_USE", CM_NULLPTR);
- this->SetPropertyDefault("LINK_WHAT_YOU_USE", CM_NULLPTR);
- this->SetPropertyDefault("C_STANDARD", CM_NULLPTR);
- this->SetPropertyDefault("C_STANDARD_REQUIRED", CM_NULLPTR);
- this->SetPropertyDefault("C_EXTENSIONS", CM_NULLPTR);
- this->SetPropertyDefault("CXX_CLANG_TIDY", CM_NULLPTR);
- this->SetPropertyDefault("CXX_COMPILER_LAUNCHER", CM_NULLPTR);
- this->SetPropertyDefault("CXX_CPPLINT", CM_NULLPTR);
- this->SetPropertyDefault("CXX_INCLUDE_WHAT_YOU_USE", CM_NULLPTR);
- this->SetPropertyDefault("CXX_STANDARD", CM_NULLPTR);
- this->SetPropertyDefault("CXX_STANDARD_REQUIRED", CM_NULLPTR);
- this->SetPropertyDefault("CXX_EXTENSIONS", CM_NULLPTR);
- this->SetPropertyDefault("CUDA_STANDARD", CM_NULLPTR);
- this->SetPropertyDefault("CUDA_STANDARD_REQUIRED", CM_NULLPTR);
- this->SetPropertyDefault("CUDA_EXTENSIONS", CM_NULLPTR);
- this->SetPropertyDefault("LINK_SEARCH_START_STATIC", CM_NULLPTR);
- this->SetPropertyDefault("LINK_SEARCH_END_STATIC", CM_NULLPTR);
- }
-
- if (this->GetType() != cmStateEnums::UTILITY) {
- this->SetPropertyDefault("NO_SYSTEM_FROM_IMPORTED", CM_NULLPTR);
+ this->SetPropertyDefault("ARCHIVE_OUTPUT_DIRECTORY", nullptr);
+ this->SetPropertyDefault("LIBRARY_OUTPUT_DIRECTORY", nullptr);
+ this->SetPropertyDefault("RUNTIME_OUTPUT_DIRECTORY", nullptr);
+ this->SetPropertyDefault("PDB_OUTPUT_DIRECTORY", nullptr);
+ this->SetPropertyDefault("COMPILE_PDB_OUTPUT_DIRECTORY", nullptr);
+ this->SetPropertyDefault("Fortran_FORMAT", nullptr);
+ this->SetPropertyDefault("Fortran_MODULE_DIRECTORY", nullptr);
+ this->SetPropertyDefault("GNUtoMS", nullptr);
+ this->SetPropertyDefault("OSX_ARCHITECTURES", nullptr);
+ this->SetPropertyDefault("IOS_INSTALL_COMBINED", nullptr);
+ this->SetPropertyDefault("AUTOMOC", nullptr);
+ this->SetPropertyDefault("AUTOUIC", nullptr);
+ this->SetPropertyDefault("AUTORCC", nullptr);
+ this->SetPropertyDefault("AUTOMOC_COMPILER_PREDEFINES", nullptr);
+ this->SetPropertyDefault("AUTOMOC_DEPEND_FILTERS", nullptr);
+ this->SetPropertyDefault("AUTOMOC_MACRO_NAMES", nullptr);
+ this->SetPropertyDefault("AUTOMOC_MOC_OPTIONS", nullptr);
+ this->SetPropertyDefault("AUTOUIC_OPTIONS", nullptr);
+ this->SetPropertyDefault("AUTOUIC_SEARCH_PATHS", nullptr);
+ this->SetPropertyDefault("AUTORCC_OPTIONS", nullptr);
+ this->SetPropertyDefault("LINK_DEPENDS_NO_SHARED", nullptr);
+ this->SetPropertyDefault("LINK_INTERFACE_LIBRARIES", nullptr);
+ this->SetPropertyDefault("WIN32_EXECUTABLE", nullptr);
+ this->SetPropertyDefault("MACOSX_BUNDLE", nullptr);
+ this->SetPropertyDefault("MACOSX_RPATH", nullptr);
+ this->SetPropertyDefault("NO_SYSTEM_FROM_IMPORTED", nullptr);
+ this->SetPropertyDefault("BUILD_WITH_INSTALL_NAME_DIR", nullptr);
+ this->SetPropertyDefault("C_CLANG_TIDY", nullptr);
+ this->SetPropertyDefault("C_COMPILER_LAUNCHER", nullptr);
+ this->SetPropertyDefault("C_CPPLINT", nullptr);
+ this->SetPropertyDefault("C_CPPCHECK", nullptr);
+ this->SetPropertyDefault("C_INCLUDE_WHAT_YOU_USE", nullptr);
+ this->SetPropertyDefault("LINK_WHAT_YOU_USE", nullptr);
+ this->SetPropertyDefault("C_STANDARD", nullptr);
+ this->SetPropertyDefault("C_STANDARD_REQUIRED", nullptr);
+ this->SetPropertyDefault("C_EXTENSIONS", nullptr);
+ this->SetPropertyDefault("CXX_CLANG_TIDY", nullptr);
+ this->SetPropertyDefault("CXX_COMPILER_LAUNCHER", nullptr);
+ this->SetPropertyDefault("CXX_CPPLINT", nullptr);
+ this->SetPropertyDefault("CXX_CPPCHECK", nullptr);
+ this->SetPropertyDefault("CXX_INCLUDE_WHAT_YOU_USE", nullptr);
+ this->SetPropertyDefault("CXX_STANDARD", nullptr);
+ this->SetPropertyDefault("CXX_STANDARD_REQUIRED", nullptr);
+ this->SetPropertyDefault("CXX_EXTENSIONS", nullptr);
+ this->SetPropertyDefault("CUDA_STANDARD", nullptr);
+ this->SetPropertyDefault("CUDA_STANDARD_REQUIRED", nullptr);
+ this->SetPropertyDefault("CUDA_EXTENSIONS", nullptr);
+ this->SetPropertyDefault("CUDA_COMPILER_LAUNCHER", nullptr);
+ this->SetPropertyDefault("LINK_SEARCH_START_STATIC", nullptr);
+ this->SetPropertyDefault("LINK_SEARCH_END_STATIC", nullptr);
}
// Collect the set of configuration types.
@@ -295,11 +294,10 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
"ARCHIVE_OUTPUT_DIRECTORY_", "LIBRARY_OUTPUT_DIRECTORY_",
"RUNTIME_OUTPUT_DIRECTORY_", "PDB_OUTPUT_DIRECTORY_",
"COMPILE_PDB_OUTPUT_DIRECTORY_", "MAP_IMPORTED_CONFIG_",
- "INTERPROCEDURAL_OPTIMIZATION_", CM_NULLPTR
+ "INTERPROCEDURAL_OPTIMIZATION_", nullptr
};
- for (std::vector<std::string>::iterator ci = configNames.begin();
- ci != configNames.end(); ++ci) {
- std::string configUpper = cmSystemTools::UpperCase(*ci);
+ for (std::string const& configName : configNames) {
+ std::string configUpper = cmSystemTools::UpperCase(configName);
for (const char** p = configProps; *p; ++p) {
// Interface libraries have no output locations, so honor only
// the configuration map.
@@ -309,7 +307,7 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
}
std::string property = *p;
property += configUpper;
- this->SetPropertyDefault(property, CM_NULLPTR);
+ this->SetPropertyDefault(property, nullptr);
}
// Initialize per-configuration name postfix property from the
@@ -319,9 +317,9 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
// property directly.
if (this->TargetTypeValue != cmStateEnums::EXECUTABLE &&
this->TargetTypeValue != cmStateEnums::INTERFACE_LIBRARY) {
- std::string property = cmSystemTools::UpperCase(*ci);
+ std::string property = cmSystemTools::UpperCase(configName);
property += "_POSTFIX";
- this->SetPropertyDefault(property, CM_NULLPTR);
+ this->SetPropertyDefault(property, nullptr);
}
}
}
@@ -365,16 +363,16 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
this->GetType() != cmStateEnums::UTILITY) {
- this->SetPropertyDefault("C_VISIBILITY_PRESET", CM_NULLPTR);
- this->SetPropertyDefault("CXX_VISIBILITY_PRESET", CM_NULLPTR);
- this->SetPropertyDefault("CUDA_VISIBILITY_PRESET", CM_NULLPTR);
- this->SetPropertyDefault("VISIBILITY_INLINES_HIDDEN", CM_NULLPTR);
+ this->SetPropertyDefault("C_VISIBILITY_PRESET", nullptr);
+ this->SetPropertyDefault("CXX_VISIBILITY_PRESET", nullptr);
+ this->SetPropertyDefault("CUDA_VISIBILITY_PRESET", nullptr);
+ this->SetPropertyDefault("VISIBILITY_INLINES_HIDDEN", nullptr);
}
if (this->TargetTypeValue == cmStateEnums::EXECUTABLE) {
- this->SetPropertyDefault("ANDROID_GUI", CM_NULLPTR);
- this->SetPropertyDefault("CROSSCOMPILING_EMULATOR", CM_NULLPTR);
- this->SetPropertyDefault("ENABLE_EXPORTS", CM_NULLPTR);
+ this->SetPropertyDefault("ANDROID_GUI", nullptr);
+ this->SetPropertyDefault("CROSSCOMPILING_EMULATOR", nullptr);
+ this->SetPropertyDefault("ENABLE_EXPORTS", nullptr);
}
if (this->TargetTypeValue == cmStateEnums::SHARED_LIBRARY ||
this->TargetTypeValue == cmStateEnums::MODULE_LIBRARY) {
@@ -382,12 +380,12 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
}
if (this->TargetTypeValue == cmStateEnums::SHARED_LIBRARY ||
this->TargetTypeValue == cmStateEnums::EXECUTABLE) {
- this->SetPropertyDefault("WINDOWS_EXPORT_ALL_SYMBOLS", CM_NULLPTR);
+ this->SetPropertyDefault("WINDOWS_EXPORT_ALL_SYMBOLS", nullptr);
}
if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
this->GetType() != cmStateEnums::UTILITY) {
- this->SetPropertyDefault("POSITION_INDEPENDENT_CODE", CM_NULLPTR);
+ this->SetPropertyDefault("POSITION_INDEPENDENT_CODE", nullptr);
}
// Record current policies for later use.
@@ -403,8 +401,8 @@ cmTarget::cmTarget(std::string const& name, cmStateEnums::TargetType type,
if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
this->GetType() != cmStateEnums::UTILITY) {
- this->SetPropertyDefault("JOB_POOL_COMPILE", CM_NULLPTR);
- this->SetPropertyDefault("JOB_POOL_LINK", CM_NULLPTR);
+ this->SetPropertyDefault("JOB_POOL_COMPILE", nullptr);
+ this->SetPropertyDefault("JOB_POOL_LINK", nullptr);
}
}
@@ -427,7 +425,7 @@ cmListFileBacktrace const* cmTarget::GetUtilityBacktrace(
std::map<std::string, cmListFileBacktrace>::const_iterator i =
this->UtilityBacktraces.find(u);
if (i == this->UtilityBacktraces.end()) {
- return CM_NULLPTR;
+ return nullptr;
}
return &i->second;
@@ -479,9 +477,7 @@ void cmTarget::AddSources(std::vector<std::string> const& srcs)
{
std::string srcFiles;
const char* sep = "";
- for (std::vector<std::string>::const_iterator i = srcs.begin();
- i != srcs.end(); ++i) {
- std::string filename = *i;
+ for (auto filename : srcs) {
const char* src = filename.c_str();
if (!(src[0] == '$' && src[1] == '<')) {
@@ -545,7 +541,7 @@ cmSourceFile* cmTarget::AddSourceCMP0049(const std::string& s)
{
std::string src = this->ProcessSourceItemCMP0049(s);
if (!s.empty() && src.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
return this->AddSource(src);
}
@@ -595,8 +591,9 @@ public:
{
std::vector<std::string> files;
cmSystemTools::ExpandListArgument(entry, files);
- std::vector<cmSourceFileLocation> locations(files.size());
- std::transform(files.begin(), files.end(), locations.begin(),
+ std::vector<cmSourceFileLocation> locations;
+ locations.reserve(files.size());
+ std::transform(files.begin(), files.end(), std::back_inserter(locations),
CreateLocation(this->Needle.GetMakefile()));
return std::find_if(locations.begin(), locations.end(),
@@ -616,7 +613,7 @@ cmSourceFile* cmTarget::AddSource(const std::string& src)
this->Internal->SourceBacktraces.push_back(lfbt);
}
if (cmGeneratorExpression::Find(src) != std::string::npos) {
- return CM_NULLPTR;
+ return nullptr;
}
return this->Makefile->GetOrCreateSource(src);
}
@@ -710,12 +707,10 @@ void cmTarget::GetTllSignatureTraces(std::ostream& s, TLLSignature sig) const
const char* sigString =
(sig == cmTarget::KeywordTLLSignature ? "keyword" : "plain");
s << "The uses of the " << sigString << " signature are here:\n";
- typedef std::vector<std::pair<TLLSignature, cmListFileContext> > Container;
cmOutputConverter converter(this->GetMakefile()->GetStateSnapshot());
- for (Container::const_iterator it = this->TLLCommands.begin();
- it != this->TLLCommands.end(); ++it) {
- if (it->first == sig) {
- cmListFileContext lfc = it->second;
+ for (auto const& cmd : this->TLLCommands) {
+ if (cmd.first == sig) {
+ cmListFileContext lfc = cmd.second;
lfc.FilePath = converter.ConvertToRelativePath(
this->Makefile->GetState()->GetSourceDirectory(), lfc.FilePath);
s << " * " << lfc << std::endl;
@@ -1178,7 +1173,7 @@ const char* cmTarget::GetComputedProperty(
const char* cmTarget::GetProperty(const std::string& prop) const
{
- static CM_UNORDERED_SET<std::string> specialProps;
+ static std::unordered_set<std::string> specialProps;
#define MAKE_STATIC_PROP(PROP) static const std::string prop##PROP = #PROP
MAKE_STATIC_PROP(LINK_LIBRARIES);
MAKE_STATIC_PROP(TYPE);
@@ -1210,7 +1205,7 @@ const char* cmTarget::GetProperty(const std::string& prop) const
if (specialProps.count(prop)) {
if (prop == propLINK_LIBRARIES) {
if (this->Internal->LinkImplementationPropertyEntries.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
static std::string output;
@@ -1223,7 +1218,7 @@ const char* cmTarget::GetProperty(const std::string& prop) const
}
if (prop == propINCLUDE_DIRECTORIES) {
if (this->Internal->IncludeDirectoriesEntries.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
static std::string output;
@@ -1232,7 +1227,7 @@ const char* cmTarget::GetProperty(const std::string& prop) const
}
if (prop == propCOMPILE_FEATURES) {
if (this->Internal->CompileFeaturesEntries.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
static std::string output;
@@ -1241,7 +1236,7 @@ const char* cmTarget::GetProperty(const std::string& prop) const
}
if (prop == propCOMPILE_OPTIONS) {
if (this->Internal->CompileOptionsEntries.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
static std::string output;
@@ -1250,7 +1245,7 @@ const char* cmTarget::GetProperty(const std::string& prop) const
}
if (prop == propCOMPILE_DEFINITIONS) {
if (this->Internal->CompileDefinitionsEntries.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
static std::string output;
@@ -1259,7 +1254,7 @@ const char* cmTarget::GetProperty(const std::string& prop) const
}
if (prop == propMANUALLY_ADDED_DEPENDENCIES) {
if (this->Utilities.empty()) {
- return CM_NULLPTR;
+ return nullptr;
}
static std::string output;
@@ -1397,8 +1392,8 @@ std::string cmTarget::ImportedGetFullPath(
std::string result;
- const char* loc = CM_NULLPTR;
- const char* imp = CM_NULLPTR;
+ const char* loc = nullptr;
+ const char* imp = nullptr;
std::string suffix;
if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
@@ -1535,7 +1530,7 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
}
// If it was found, set the suffix.
if (*loc || *imp) {
- suffix = "";
+ suffix.clear();
}
} else {
std::string mcUpper = cmSystemTools::UpperCase(*mci);
@@ -1582,7 +1577,7 @@ bool cmTarget::GetMappedConfig(std::string const& desired_config,
// configurations and no exact match.
if (!*loc && !*imp) {
// The suffix computed above is not useful.
- suffix = "";
+ suffix.clear();
// Look for a configuration-less location. This may be set by
// manually-written code.
diff --git a/Source/cmTarget.h b/Source/cmTarget.h
index 1f00c0155..940e26c69 100644
--- a/Source/cmTarget.h
+++ b/Source/cmTarget.h
@@ -9,6 +9,7 @@
#include <map>
#include <set>
#include <string>
+#include <unordered_map>
#include <utility>
#include <vector>
@@ -19,7 +20,6 @@
#include "cmPropertyMap.h"
#include "cmStateTypes.h"
#include "cmTargetLinkLibraryType.h"
-#include "cm_unordered_map.hxx"
class cmGlobalGenerator;
class cmMakefile;
@@ -184,7 +184,7 @@ public:
* name as would be specified to the ADD_EXECUTABLE or UTILITY_SOURCE
* commands. It is not a full path nor does it have an extension.
*/
- void AddUtility(const std::string& u, cmMakefile* makefile = CM_NULLPTR);
+ void AddUtility(const std::string& u, cmMakefile* makefile = nullptr);
///! Get the utilities used by this target
std::set<std::string> const& GetUtilities() const { return this->Utilities; }
cmListFileBacktrace const* GetUtilityBacktrace(const std::string& u) const;
@@ -297,7 +297,7 @@ private:
std::vector<cmCustomCommand> PreBuildCommands;
std::vector<cmCustomCommand> PreLinkCommands;
std::vector<cmCustomCommand> PostBuildCommands;
- std::vector<std::pair<TLLSignature, cmListFileContext> > TLLCommands;
+ std::vector<std::pair<TLLSignature, cmListFileContext>> TLLCommands;
LinkLibraryVectorType OriginalLinkLibraries;
cmMakefile* Makefile;
cmTargetInternalPointer Internal;
@@ -323,7 +323,7 @@ private:
cmListFileBacktrace Backtrace;
};
-typedef CM_UNORDERED_MAP<std::string, cmTarget> cmTargets;
+typedef std::unordered_map<std::string, cmTarget> cmTargets;
class cmTargetSet : public std::set<std::string>
{
diff --git a/Source/cmTargetCompileDefinitionsCommand.cxx b/Source/cmTargetCompileDefinitionsCommand.cxx
index 008d1a210..d159d4178 100644
--- a/Source/cmTargetCompileDefinitionsCommand.cxx
+++ b/Source/cmTargetCompileDefinitionsCommand.cxx
@@ -41,12 +41,11 @@ std::string cmTargetCompileDefinitionsCommand::Join(
{
std::string defs;
std::string sep;
- for (std::vector<std::string>::const_iterator it = content.begin();
- it != content.end(); ++it) {
- if (cmHasLiteralPrefix(it->c_str(), "-D")) {
- defs += sep + it->substr(2);
+ for (std::string const& it : content) {
+ if (cmHasLiteralPrefix(it.c_str(), "-D")) {
+ defs += sep + it.substr(2);
} else {
- defs += sep + *it;
+ defs += sep + it;
}
sep = ";";
}
diff --git a/Source/cmTargetCompileDefinitionsCommand.h b/Source/cmTargetCompileDefinitionsCommand.h
index 11abf571c..f91045225 100644
--- a/Source/cmTargetCompileDefinitionsCommand.h
+++ b/Source/cmTargetCompileDefinitionsCommand.h
@@ -3,7 +3,7 @@
#ifndef cmTargetCompileDefinitionsCommand_h
#define cmTargetCompileDefinitionsCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -20,26 +20,23 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
- {
- return new cmTargetCompileDefinitionsCommand;
- }
+ cmCommand* Clone() override { return new cmTargetCompileDefinitionsCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
- void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
- void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
+ void HandleImportedTarget(const std::string& tgt) override;
+ void HandleMissingTarget(const std::string& name) override;
bool HandleDirectContent(cmTarget* tgt,
const std::vector<std::string>& content,
- bool prepend, bool system) CM_OVERRIDE;
- std::string Join(const std::vector<std::string>& content) CM_OVERRIDE;
+ bool prepend, bool system) override;
+ std::string Join(const std::vector<std::string>& content) override;
};
#endif
diff --git a/Source/cmTargetCompileFeaturesCommand.cxx b/Source/cmTargetCompileFeaturesCommand.cxx
index 1b6c00887..722bbe56c 100644
--- a/Source/cmTargetCompileFeaturesCommand.cxx
+++ b/Source/cmTargetCompileFeaturesCommand.cxx
@@ -45,10 +45,9 @@ std::string cmTargetCompileFeaturesCommand::Join(
bool cmTargetCompileFeaturesCommand::HandleDirectContent(
cmTarget* tgt, const std::vector<std::string>& content, bool, bool)
{
- for (std::vector<std::string>::const_iterator it = content.begin();
- it != content.end(); ++it) {
+ for (std::string const& it : content) {
std::string error;
- if (!this->Makefile->AddRequiredTargetFeature(tgt, *it, &error)) {
+ if (!this->Makefile->AddRequiredTargetFeature(tgt, it, &error)) {
this->SetError(error);
return false;
}
diff --git a/Source/cmTargetCompileFeaturesCommand.h b/Source/cmTargetCompileFeaturesCommand.h
index 990868004..444d26069 100644
--- a/Source/cmTargetCompileFeaturesCommand.h
+++ b/Source/cmTargetCompileFeaturesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmTargetCompileFeaturesCommand_h
#define cmTargetCompileFeaturesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -16,19 +16,19 @@ class cmTarget;
class cmTargetCompileFeaturesCommand : public cmTargetPropCommandBase
{
- cmCommand* Clone() CM_OVERRIDE { return new cmTargetCompileFeaturesCommand; }
+ cmCommand* Clone() override { return new cmTargetCompileFeaturesCommand; }
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
- void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
- void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
+ void HandleImportedTarget(const std::string& tgt) override;
+ void HandleMissingTarget(const std::string& name) override;
bool HandleDirectContent(cmTarget* tgt,
const std::vector<std::string>& content,
- bool prepend, bool system) CM_OVERRIDE;
- std::string Join(const std::vector<std::string>& content) CM_OVERRIDE;
+ bool prepend, bool system) override;
+ std::string Join(const std::vector<std::string>& content) override;
};
#endif
diff --git a/Source/cmTargetCompileOptionsCommand.h b/Source/cmTargetCompileOptionsCommand.h
index b5408f7cb..3fab238f2 100644
--- a/Source/cmTargetCompileOptionsCommand.h
+++ b/Source/cmTargetCompileOptionsCommand.h
@@ -3,7 +3,7 @@
#ifndef cmTargetCompileOptionsCommand_h
#define cmTargetCompileOptionsCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -20,23 +20,23 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmTargetCompileOptionsCommand; }
+ cmCommand* Clone() override { return new cmTargetCompileOptionsCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
- void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
- void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
+ void HandleImportedTarget(const std::string& tgt) override;
+ void HandleMissingTarget(const std::string& name) override;
bool HandleDirectContent(cmTarget* tgt,
const std::vector<std::string>& content,
- bool prepend, bool system) CM_OVERRIDE;
- std::string Join(const std::vector<std::string>& content) CM_OVERRIDE;
+ bool prepend, bool system) override;
+ std::string Join(const std::vector<std::string>& content) override;
};
#endif
diff --git a/Source/cmTargetIncludeDirectoriesCommand.cxx b/Source/cmTargetIncludeDirectoriesCommand.cxx
index 65a31490f..4646c7ee1 100644
--- a/Source/cmTargetIncludeDirectoriesCommand.cxx
+++ b/Source/cmTargetIncludeDirectoriesCommand.cxx
@@ -47,13 +47,12 @@ std::string cmTargetIncludeDirectoriesCommand::Join(
std::string sep;
std::string prefix =
this->Makefile->GetCurrentSourceDirectory() + std::string("/");
- for (std::vector<std::string>::const_iterator it = content.begin();
- it != content.end(); ++it) {
- if (cmSystemTools::FileIsFullPath(it->c_str()) ||
- cmGeneratorExpression::Find(*it) == 0) {
- dirs += sep + *it;
+ for (std::string const& it : content) {
+ if (cmSystemTools::FileIsFullPath(it.c_str()) ||
+ cmGeneratorExpression::Find(it) == 0) {
+ dirs += sep + it;
} else {
- dirs += sep + prefix + *it;
+ dirs += sep + prefix + it;
}
sep = ";";
}
@@ -70,13 +69,12 @@ bool cmTargetIncludeDirectoriesCommand::HandleDirectContent(
std::string prefix =
this->Makefile->GetCurrentSourceDirectory() + std::string("/");
std::set<std::string> sdirs;
- for (std::vector<std::string>::const_iterator it = content.begin();
- it != content.end(); ++it) {
- if (cmSystemTools::FileIsFullPath(it->c_str()) ||
- cmGeneratorExpression::Find(*it) == 0) {
- sdirs.insert(*it);
+ for (std::string const& it : content) {
+ if (cmSystemTools::FileIsFullPath(it.c_str()) ||
+ cmGeneratorExpression::Find(it) == 0) {
+ sdirs.insert(it);
} else {
- sdirs.insert(prefix + *it);
+ sdirs.insert(prefix + it);
}
}
tgt->AddSystemIncludeDirectories(sdirs);
diff --git a/Source/cmTargetIncludeDirectoriesCommand.h b/Source/cmTargetIncludeDirectoriesCommand.h
index 374a867dc..27a2f437a 100644
--- a/Source/cmTargetIncludeDirectoriesCommand.h
+++ b/Source/cmTargetIncludeDirectoriesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmTargetIncludeDirectoriesCommand_h
#define cmTargetIncludeDirectoriesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -20,30 +20,27 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE
- {
- return new cmTargetIncludeDirectoriesCommand;
- }
+ cmCommand* Clone() override { return new cmTargetIncludeDirectoriesCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
- void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
- void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
+ void HandleImportedTarget(const std::string& tgt) override;
+ void HandleMissingTarget(const std::string& name) override;
bool HandleDirectContent(cmTarget* tgt,
const std::vector<std::string>& content,
- bool prepend, bool system) CM_OVERRIDE;
+ bool prepend, bool system) override;
void HandleInterfaceContent(cmTarget* tgt,
const std::vector<std::string>& content,
- bool prepend, bool system) CM_OVERRIDE;
+ bool prepend, bool system) override;
- std::string Join(const std::vector<std::string>& content) CM_OVERRIDE;
+ std::string Join(const std::vector<std::string>& content) override;
};
#endif
diff --git a/Source/cmTargetLinkLibrariesCommand.cxx b/Source/cmTargetLinkLibrariesCommand.cxx
index e17303645..dda0464de 100644
--- a/Source/cmTargetLinkLibrariesCommand.cxx
+++ b/Source/cmTargetLinkLibrariesCommand.cxx
@@ -95,7 +95,7 @@ bool cmTargetLinkLibrariesCommand::InitialPass(
if (this->Target->GetType() == cmStateEnums::UTILITY) {
std::ostringstream e;
- const char* modal = CM_NULLPTR;
+ const char* modal = nullptr;
cmake::MessageType messageType = cmake::AUTHOR_WARNING;
switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0039)) {
case cmPolicies::WARN:
@@ -311,7 +311,7 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib,
if (!this->Target->PushTLLCommandTrace(
sig, this->Makefile->GetExecutionContext())) {
std::ostringstream e;
- const char* modal = CM_NULLPTR;
+ const char* modal = nullptr;
cmake::MessageType messageType = cmake::AUTHOR_WARNING;
switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0023)) {
case cmPolicies::WARN:
@@ -366,6 +366,7 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib,
if (tgt && (tgt->GetType() != cmStateEnums::STATIC_LIBRARY) &&
(tgt->GetType() != cmStateEnums::SHARED_LIBRARY) &&
+ (tgt->GetType() != cmStateEnums::UNKNOWN_LIBRARY) &&
(tgt->GetType() != cmStateEnums::INTERFACE_LIBRARY) &&
!tgt->IsExecutableWithExports()) {
std::ostringstream e;
@@ -428,10 +429,9 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib,
// Include this library in the link interface for the target.
if (llt == DEBUG_LibraryType || llt == GENERAL_LibraryType) {
// Put in the DEBUG configuration interfaces.
- for (std::vector<std::string>::const_iterator i = debugConfigs.begin();
- i != debugConfigs.end(); ++i) {
+ for (std::string const& dc : debugConfigs) {
prop = "LINK_INTERFACE_LIBRARIES_";
- prop += *i;
+ prop += dc;
this->Target->AppendProperty(prop, lib.c_str());
}
}
@@ -441,10 +441,9 @@ bool cmTargetLinkLibrariesCommand::HandleLibrary(const std::string& lib,
// Make sure the DEBUG configuration interfaces exist so that the
// general one will not be used as a fall-back.
- for (std::vector<std::string>::const_iterator i = debugConfigs.begin();
- i != debugConfigs.end(); ++i) {
+ for (std::string const& dc : debugConfigs) {
prop = "LINK_INTERFACE_LIBRARIES_";
- prop += *i;
+ prop += dc;
if (!this->Target->GetProperty(prop)) {
this->Target->SetProperty(prop, "");
}
diff --git a/Source/cmTargetLinkLibrariesCommand.h b/Source/cmTargetLinkLibrariesCommand.h
index 3fd20accd..f41af49d2 100644
--- a/Source/cmTargetLinkLibrariesCommand.h
+++ b/Source/cmTargetLinkLibrariesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmTargetLinkLibrariesCommand_h
#define cmTargetLinkLibrariesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -27,14 +27,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmTargetLinkLibrariesCommand; }
+ cmCommand* Clone() override { return new cmTargetLinkLibrariesCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
void LinkLibraryTypeSpecifierWarning(int left, int right);
diff --git a/Source/cmTargetPropertyComputer.cxx b/Source/cmTargetPropertyComputer.cxx
index a57bc5aea..1d2520d4b 100644
--- a/Source/cmTargetPropertyComputer.cxx
+++ b/Source/cmTargetPropertyComputer.cxx
@@ -4,11 +4,11 @@
#include "cmTargetPropertyComputer.h"
#include <sstream>
+#include <unordered_set>
#include "cmMessenger.h"
#include "cmPolicies.h"
#include "cmStateSnapshot.h"
-#include "cm_unordered_set.hxx"
#include "cmake.h"
bool cmTargetPropertyComputer::HandleLocationPropertyPolicy(
@@ -16,7 +16,7 @@ bool cmTargetPropertyComputer::HandleLocationPropertyPolicy(
cmListFileBacktrace const& context)
{
std::ostringstream e;
- const char* modal = CM_NULLPTR;
+ const char* modal = nullptr;
cmake::MessageType messageType = cmake::AUTHOR_WARNING;
switch (context.GetBottom().GetPolicy(cmPolicies::CMP0026)) {
case cmPolicies::WARN:
@@ -49,7 +49,7 @@ bool cmTargetPropertyComputer::WhiteListedInterfaceProperty(
if (cmHasLiteralPrefix(prop, "INTERFACE_")) {
return true;
}
- static CM_UNORDERED_SET<std::string> builtIns;
+ static std::unordered_set<std::string> builtIns;
if (builtIns.empty()) {
builtIns.insert("COMPATIBLE_INTERFACE_BOOL");
builtIns.insert("COMPATIBLE_INTERFACE_NUMBER_MAX");
@@ -66,12 +66,19 @@ bool cmTargetPropertyComputer::WhiteListedInterfaceProperty(
}
if (prop == "IMPORTED_CONFIGURATIONS" || prop == "IMPORTED_LIBNAME" ||
- prop == "NO_SYSTEM_FROM_IMPORTED" ||
cmHasLiteralPrefix(prop, "IMPORTED_LIBNAME_") ||
cmHasLiteralPrefix(prop, "MAP_IMPORTED_CONFIG_")) {
return true;
}
+ // This property should not be allowed but was incorrectly added in
+ // CMake 3.8. We can't remove it from the whitelist without breaking
+ // projects that try to set it. One day we could warn about this, but
+ // for now silently accept it.
+ if (prop == "NO_SYSTEM_FROM_IMPORTED") {
+ return true;
+ }
+
return false;
}
diff --git a/Source/cmTargetPropertyComputer.h b/Source/cmTargetPropertyComputer.h
index 94688e313..97e4fba2c 100644
--- a/Source/cmTargetPropertyComputer.h
+++ b/Source/cmTargetPropertyComputer.h
@@ -26,12 +26,12 @@ public:
return loc;
}
if (cmSystemTools::GetFatalErrorOccured()) {
- return CM_NULLPTR;
+ return nullptr;
}
if (prop == "SOURCES") {
return GetSources(tgt, messenger, context);
}
- return CM_NULLPTR;
+ return nullptr;
}
static bool WhiteListedInterfaceProperty(const std::string& prop);
@@ -69,7 +69,7 @@ private:
if (!tgt->IsImported() &&
!HandleLocationPropertyPolicy(tgt->GetName(), messenger,
context)) {
- return CM_NULLPTR;
+ return nullptr;
}
return ComputeLocationForBuild(tgt);
}
@@ -79,7 +79,7 @@ private:
if (!tgt->IsImported() &&
!HandleLocationPropertyPolicy(tgt->GetName(), messenger,
context)) {
- return CM_NULLPTR;
+ return nullptr;
}
const char* configName = prop.c_str() + 9;
return ComputeLocation(tgt, configName);
@@ -93,13 +93,13 @@ private:
if (!tgt->IsImported() &&
!HandleLocationPropertyPolicy(tgt->GetName(), messenger,
context)) {
- return CM_NULLPTR;
+ return nullptr;
}
return ComputeLocation(tgt, configName);
}
}
}
- return CM_NULLPTR;
+ return nullptr;
}
template <typename Target>
diff --git a/Source/cmTargetSourcesCommand.h b/Source/cmTargetSourcesCommand.h
index 09ba72915..0639e980e 100644
--- a/Source/cmTargetSourcesCommand.h
+++ b/Source/cmTargetSourcesCommand.h
@@ -3,7 +3,7 @@
#ifndef cmTargetSourcesCommand_h
#define cmTargetSourcesCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -20,24 +20,24 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmTargetSourcesCommand; }
+ cmCommand* Clone() override { return new cmTargetSourcesCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
- void HandleImportedTarget(const std::string& tgt) CM_OVERRIDE;
- void HandleMissingTarget(const std::string& name) CM_OVERRIDE;
+ void HandleImportedTarget(const std::string& tgt) override;
+ void HandleMissingTarget(const std::string& name) override;
bool HandleDirectContent(cmTarget* tgt,
const std::vector<std::string>& content,
- bool prepend, bool system) CM_OVERRIDE;
+ bool prepend, bool system) override;
- std::string Join(const std::vector<std::string>& content) CM_OVERRIDE;
+ std::string Join(const std::vector<std::string>& content) override;
};
#endif
diff --git a/Source/cmTestGenerator.cxx b/Source/cmTestGenerator.cxx
index be4b37847..78ca6bca3 100644
--- a/Source/cmTestGenerator.cxx
+++ b/Source/cmTestGenerator.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmTestGenerator.h"
-#include <map>
#include <ostream>
#include <utility>
@@ -23,7 +22,7 @@ cmTestGenerator::cmTestGenerator(
{
this->ActionsPerConfig = !test->GetOldStyle();
this->TestGenerated = false;
- this->LG = CM_NULLPTR;
+ this->LG = nullptr;
}
cmTestGenerator::~cmTestGenerator()
@@ -80,7 +79,7 @@ void cmTestGenerator::GenerateScriptForConfig(std::ostream& os,
// Prepend with the emulator when cross compiling if required.
const char* emulator = target->GetProperty("CROSSCOMPILING_EMULATOR");
- if (emulator != CM_NULLPTR) {
+ if (emulator != nullptr) {
std::vector<std::string> emulatorWithArgs;
cmSystemTools::ExpandListArgument(emulator, emulatorWithArgs);
std::string emulatorExe(emulatorWithArgs[0]);
@@ -114,10 +113,10 @@ void cmTestGenerator::GenerateScriptForConfig(std::ostream& os,
if (!pm.empty()) {
os << indent << "set_tests_properties(" << this->Test->GetName()
<< " PROPERTIES ";
- for (cmPropertyMap::const_iterator i = pm.begin(); i != pm.end(); ++i) {
- os << " " << i->first << " "
+ for (auto const& i : pm) {
+ os << " " << i.first << " "
<< cmOutputConverter::EscapeForCMake(
- ge.Parse(i->second.GetValue())->Evaluate(this->LG, config));
+ ge.Parse(i.second.GetValue())->Evaluate(this->LG, config));
}
os << ")" << std::endl;
}
@@ -154,15 +153,14 @@ void cmTestGenerator::GenerateOldStyle(std::ostream& fout, Indent indent)
// Just double-quote all arguments so they are re-parsed
// correctly by the test system.
fout << " \"";
- for (std::string::const_iterator c = argit->begin(); c != argit->end();
- ++c) {
+ for (char c : *argit) {
// Escape quotes within arguments. We should escape
// backslashes too but we cannot because it makes the result
// inconsistent with previous behavior of this command.
- if ((*c == '"')) {
+ if (c == '"') {
fout << '\\';
}
- fout << *c;
+ fout << c;
}
fout << "\"";
}
@@ -173,9 +171,9 @@ void cmTestGenerator::GenerateOldStyle(std::ostream& fout, Indent indent)
if (!pm.empty()) {
fout << indent << "set_tests_properties(" << this->Test->GetName()
<< " PROPERTIES ";
- for (cmPropertyMap::const_iterator i = pm.begin(); i != pm.end(); ++i) {
- fout << " " << i->first << " "
- << cmOutputConverter::EscapeForCMake(i->second.GetValue());
+ for (auto const& i : pm) {
+ fout << " " << i.first << " "
+ << cmOutputConverter::EscapeForCMake(i.second.GetValue());
}
fout << ")" << std::endl;
}
diff --git a/Source/cmTestGenerator.h b/Source/cmTestGenerator.h
index b2273050f..1ca61c210 100644
--- a/Source/cmTestGenerator.h
+++ b/Source/cmTestGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmTestGenerator_h
#define cmTestGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmScriptGenerator.h"
@@ -26,17 +26,17 @@ public:
cmTestGenerator(cmTest* test,
std::vector<std::string> const& configurations =
std::vector<std::string>());
- ~cmTestGenerator() CM_OVERRIDE;
+ ~cmTestGenerator() override;
void Compute(cmLocalGenerator* lg);
protected:
- void GenerateScriptConfigs(std::ostream& os, Indent indent) CM_OVERRIDE;
- void GenerateScriptActions(std::ostream& os, Indent indent) CM_OVERRIDE;
+ void GenerateScriptConfigs(std::ostream& os, Indent indent) override;
+ void GenerateScriptActions(std::ostream& os, Indent indent) override;
void GenerateScriptForConfig(std::ostream& os, const std::string& config,
- Indent indent) CM_OVERRIDE;
- void GenerateScriptNoConfig(std::ostream& os, Indent indent) CM_OVERRIDE;
- bool NeedsScriptNoConfig() const CM_OVERRIDE;
+ Indent indent) override;
+ void GenerateScriptNoConfig(std::ostream& os, Indent indent) override;
+ bool NeedsScriptNoConfig() const override;
void GenerateOldStyle(std::ostream& os, Indent indent);
cmLocalGenerator* LG;
diff --git a/Source/cmTimestamp.cxx b/Source/cmTimestamp.cxx
index 4b9718847..9fb79d945 100644
--- a/Source/cmTimestamp.cxx
+++ b/Source/cmTimestamp.cxx
@@ -2,7 +2,6 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmTimestamp.h"
-#include "cmConfigure.h"
#include <cstring>
#include <sstream>
#include <stdlib.h>
@@ -12,7 +11,7 @@
std::string cmTimestamp::CurrentTime(const std::string& formatString,
bool utcFlag)
{
- time_t currentTimeT = time(CM_NULLPTR);
+ time_t currentTimeT = time(nullptr);
std::string source_date_epoch;
cmSystemTools::GetEnv("SOURCE_DATE_EPOCH", source_date_epoch);
if (!source_date_epoch.empty()) {
@@ -56,14 +55,14 @@ std::string cmTimestamp::CreateTimestampFromTimeT(time_t timeT,
struct tm timeStruct;
memset(&timeStruct, 0, sizeof(timeStruct));
- struct tm* ptr = (struct tm*)CM_NULLPTR;
+ struct tm* ptr = nullptr;
if (utcFlag) {
ptr = gmtime(&timeT);
} else {
ptr = localtime(&timeT);
}
- if (ptr == CM_NULLPTR) {
+ if (ptr == nullptr) {
return std::string();
}
@@ -124,7 +123,9 @@ std::string cmTimestamp::AddTimestampComponent(char flag,
switch (flag) {
case 'a':
+ case 'A':
case 'b':
+ case 'B':
case 'd':
case 'H':
case 'I':
diff --git a/Source/cmTryCompileCommand.h b/Source/cmTryCompileCommand.h
index 483654822..fbe0d78b6 100644
--- a/Source/cmTryCompileCommand.h
+++ b/Source/cmTryCompileCommand.h
@@ -3,7 +3,7 @@
#ifndef cmTryCompileCommand_h
#define cmTryCompileCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmTryCompileCommand; }
+ cmCommand* Clone() override { return new cmTryCompileCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmTryRunCommand.cxx b/Source/cmTryRunCommand.cxx
index 07e20e62f..dcaa4939e 100644
--- a/Source/cmTryRunCommand.cxx
+++ b/Source/cmTryRunCommand.cxx
@@ -33,11 +33,11 @@ bool cmTryRunCommand::InitialPass(std::vector<std::string> const& argv,
// build an arg list for TryCompile and extract the runArgs,
std::vector<std::string> tryCompile;
- this->CompileResultVariable = "";
- this->RunResultVariable = "";
- this->OutputVariable = "";
- this->RunOutputVariable = "";
- this->CompileOutputVariable = "";
+ this->CompileResultVariable.clear();
+ this->RunResultVariable.clear();
+ this->OutputVariable.clear();
+ this->RunOutputVariable.clear();
+ this->CompileOutputVariable.clear();
std::string runArgs;
unsigned int i;
@@ -125,9 +125,8 @@ bool cmTryRunCommand::InitialPass(std::vector<std::string> const& argv,
std::string runOutputContents;
if (this->Makefile->IsOn("CMAKE_CROSSCOMPILING") &&
!this->Makefile->IsDefinitionSet("CMAKE_CROSSCOMPILING_EMULATOR")) {
- this->DoNotRunExecutable(runArgs, argv[3], captureRunOutput
- ? &runOutputContents
- : CM_NULLPTR);
+ this->DoNotRunExecutable(
+ runArgs, argv[3], captureRunOutput ? &runOutputContents : nullptr);
} else {
this->RunExecutable(runArgs, &runOutputContents);
}
@@ -189,7 +188,7 @@ void cmTryRunCommand::RunExecutable(const std::string& runArgs,
}
int timeout = 0;
bool worked = cmSystemTools::RunSingleCommand(
- finalCommand.c_str(), out, out, &retVal, CM_NULLPTR,
+ finalCommand.c_str(), out, out, &retVal, nullptr,
cmSystemTools::OUTPUT_NONE, timeout);
// set the run var
char retChar[1000];
@@ -233,7 +232,7 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
this->RunResultVariable + "__TRYRUN_OUTPUT";
bool error = false;
- if (this->Makefile->GetDefinition(this->RunResultVariable) == CM_NULLPTR) {
+ if (this->Makefile->GetDefinition(this->RunResultVariable) == nullptr) {
// if the variables doesn't exist, create it with a helpful error text
// and mark it as advanced
std::string comment;
@@ -255,8 +254,8 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
}
// is the output from the executable used ?
- if (out != CM_NULLPTR) {
- if (this->Makefile->GetDefinition(internalRunOutputName) == CM_NULLPTR) {
+ if (out != nullptr) {
+ if (this->Makefile->GetDefinition(internalRunOutputName) == nullptr) {
// if the variables doesn't exist, create it with a helpful error text
// and mark it as advanced
std::string comment;
@@ -304,7 +303,7 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
comment += " to\n"
" the exit code (in many cases 0 for success), otherwise "
"enter \"FAILED_TO_RUN\".\n";
- if (out != CM_NULLPTR) {
+ if (out != nullptr) {
comment += internalRunOutputName;
comment +=
"\n contains the text the executable "
@@ -335,7 +334,7 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
<< this->Makefile->GetDefinition(this->RunResultVariable)
<< "\"\n CACHE STRING \"Result from TRY_RUN\" FORCE)\n\n";
- if (out != CM_NULLPTR) {
+ if (out != nullptr) {
file << "set( " << internalRunOutputName << " \n \""
<< this->Makefile->GetDefinition(internalRunOutputName)
<< "\"\n CACHE STRING \"Output from TRY_RUN\" FORCE)\n\n";
@@ -348,7 +347,7 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
"please set the following cache variables "
"appropriately:\n";
errorMessage += " " + this->RunResultVariable + " (advanced)\n";
- if (out != CM_NULLPTR) {
+ if (out != nullptr) {
errorMessage += " " + internalRunOutputName + " (advanced)\n";
}
errorMessage += detailsString;
@@ -356,7 +355,7 @@ void cmTryRunCommand::DoNotRunExecutable(const std::string& runArgs,
return;
}
- if (out != CM_NULLPTR) {
+ if (out != nullptr) {
(*out) = this->Makefile->GetDefinition(internalRunOutputName);
}
}
diff --git a/Source/cmTryRunCommand.h b/Source/cmTryRunCommand.h
index c27b026ad..b632ef580 100644
--- a/Source/cmTryRunCommand.h
+++ b/Source/cmTryRunCommand.h
@@ -3,7 +3,7 @@
#ifndef cmTryRunCommand_h
#define cmTryRunCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -24,14 +24,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmTryRunCommand; }
+ cmCommand* Clone() override { return new cmTryRunCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
void RunExecutable(const std::string& runArgs,
diff --git a/Source/cmUnexpectedCommand.h b/Source/cmUnexpectedCommand.h
index 995d8a5d6..7154881a4 100644
--- a/Source/cmUnexpectedCommand.h
+++ b/Source/cmUnexpectedCommand.h
@@ -3,7 +3,7 @@
#ifndef cmUnexpectedCommand_h
#define cmUnexpectedCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -21,13 +21,13 @@ public:
{
}
- cmCommand* Clone() CM_OVERRIDE
+ cmCommand* Clone() override
{
return new cmUnexpectedCommand(this->Name, this->Error);
}
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
private:
std::string Name;
diff --git a/Source/cmUnsetCommand.cxx b/Source/cmUnsetCommand.cxx
index 31525ba4a..18bbdd748 100644
--- a/Source/cmUnsetCommand.cxx
+++ b/Source/cmUnsetCommand.cxx
@@ -46,7 +46,7 @@ bool cmUnsetCommand::InitialPass(std::vector<std::string> const& args,
}
// unset(VAR PARENT_SCOPE)
if ((args.size() == 2) && (args[1] == "PARENT_SCOPE")) {
- this->Makefile->RaiseScope(variable, CM_NULLPTR);
+ this->Makefile->RaiseScope(variable, nullptr);
return true;
}
// ERROR: second argument isn't CACHE or PARENT_SCOPE
diff --git a/Source/cmUnsetCommand.h b/Source/cmUnsetCommand.h
index 2a1f3f0a6..4e1208a45 100644
--- a/Source/cmUnsetCommand.h
+++ b/Source/cmUnsetCommand.h
@@ -3,7 +3,7 @@
#ifndef cmUnsetCommand_h
#define cmUnsetCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -23,14 +23,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmUnsetCommand; }
+ cmCommand* Clone() override { return new cmUnsetCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmUseMangledMesaCommand.cxx b/Source/cmUseMangledMesaCommand.cxx
index 07095b137..c04a68327 100644
--- a/Source/cmUseMangledMesaCommand.cxx
+++ b/Source/cmUseMangledMesaCommand.cxx
@@ -38,11 +38,10 @@ bool cmUseMangledMesaCommand::InitialPass(std::vector<std::string> const& args,
return false;
}
cmSystemTools::MakeDirectory(destDir);
- for (std::vector<std::string>::iterator i = files.begin(); i != files.end();
- ++i) {
+ for (std::string const& f : files) {
std::string path = inputDir;
path += "/";
- path += *i;
+ path += f;
this->CopyAndFullPathMesaHeader(path.c_str(), destDir);
}
diff --git a/Source/cmUseMangledMesaCommand.h b/Source/cmUseMangledMesaCommand.h
index 511882989..78f86167b 100644
--- a/Source/cmUseMangledMesaCommand.h
+++ b/Source/cmUseMangledMesaCommand.h
@@ -3,7 +3,7 @@
#ifndef cmUseMangledMesaCommand_h
#define cmUseMangledMesaCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,9 +15,9 @@ class cmExecutionStatus;
class cmUseMangledMesaCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmUseMangledMesaCommand; }
+ cmCommand* Clone() override { return new cmUseMangledMesaCommand; }
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
protected:
void CopyAndFullPathMesaHeader(const char* source, const char* outdir);
diff --git a/Source/cmUtilitySourceCommand.cxx b/Source/cmUtilitySourceCommand.cxx
index eabd7ef31..0ce437c1a 100644
--- a/Source/cmUtilitySourceCommand.cxx
+++ b/Source/cmUtilitySourceCommand.cxx
@@ -33,7 +33,7 @@ bool cmUtilitySourceCommand::InitialPass(std::vector<std::string> const& args,
bool haveCacheValue = false;
if (this->Makefile->IsOn("CMAKE_CROSSCOMPILING")) {
- haveCacheValue = (cacheValue != CM_NULLPTR);
+ haveCacheValue = (cacheValue != nullptr);
if (!haveCacheValue) {
std::string msg = "UTILITY_SOURCE is used in cross compiling mode for ";
msg += cacheEntry;
@@ -45,7 +45,7 @@ bool cmUtilitySourceCommand::InitialPass(std::vector<std::string> const& args,
} else {
cmState* state = this->Makefile->GetState();
haveCacheValue =
- (cacheValue && (strstr(cacheValue, "(IntDir)") == CM_NULLPTR ||
+ (cacheValue && (strstr(cacheValue, "(IntDir)") == nullptr ||
(intDir && strcmp(intDir, "$(IntDir)") == 0)) &&
(state->GetCacheMajorVersion() != 0 &&
state->GetCacheMinorVersion() != 0));
diff --git a/Source/cmUtilitySourceCommand.h b/Source/cmUtilitySourceCommand.h
index a95b48d6a..165eceff6 100644
--- a/Source/cmUtilitySourceCommand.h
+++ b/Source/cmUtilitySourceCommand.h
@@ -3,7 +3,7 @@
#ifndef cmUtilitySourceCommand_h
#define cmUtilitySourceCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,9 +15,9 @@ class cmExecutionStatus;
class cmUtilitySourceCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmUtilitySourceCommand; }
+ cmCommand* Clone() override { return new cmUtilitySourceCommand; }
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmVS10CLFlagTable.h b/Source/cmVS10CLFlagTable.h
index dbd760ed1..df4d58c03 100644
--- a/Source/cmVS10CLFlagTable.h
+++ b/Source/cmVS10CLFlagTable.h
@@ -70,7 +70,8 @@ static cmVS7FlagTable cmVS10CLFlagTable[] = {
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
{ "PrecompiledHeader", "Yu", "Use", "Use",
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
- { "PrecompiledHeader", "", "Not Using Precompiled Headers", "NotUsing", 0 },
+ { "PrecompiledHeader", "Y-", "Not Using Precompiled Headers", "NotUsing",
+ 0 },
{ "AssemblerOutput", "", "No Listing", "NoListing", 0 },
{ "AssemblerOutput", "FA", "Assembly-Only Listing", "AssemblyCode", 0 },
diff --git a/Source/cmVS10CSharpFlagTable.h b/Source/cmVS10CSharpFlagTable.h
index 493ec2b12..18d587c50 100644
--- a/Source/cmVS10CSharpFlagTable.h
+++ b/Source/cmVS10CSharpFlagTable.h
@@ -25,7 +25,8 @@ static cmVS7FlagTable cmVS10CSharpFlagTable[] = {
{ "ApplicationIcon", "win32icon", "", "",
cmIDEFlagTable::UserValueRequired },
- { "Win32Manifest", "win32manifest:", "", "true", 0 },
+ { "ApplicationManifest", "win32manifest:", "", "",
+ cmIDEFlagTable::UserValueRequired },
{ "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
diff --git a/Source/cmVS10LinkFlagTable.h b/Source/cmVS10LinkFlagTable.h
index c30ea9a66..6a0313a2f 100644
--- a/Source/cmVS10LinkFlagTable.h
+++ b/Source/cmVS10LinkFlagTable.h
@@ -29,6 +29,8 @@ static cmVS7FlagTable cmVS10LinkFlagTable[] = {
{ "CreateHotPatchableImage", "FUNCTIONPADMIN:16", "Itanium Image Only",
"ItaniumImage", 0 },
+ // correct flags for uac should be /MANIFESTUAC, but some projects already
+ // use this bug to access uac field, so keep these for compatibility
{ "UACExecutionLevel", "level='asInvoker'", "asInvoker", "AsInvoker", 0 },
{ "UACExecutionLevel", "level='highestAvailable'", "highestAvailable",
"HighestAvailable", 0 },
@@ -123,8 +125,12 @@ static cmVS7FlagTable cmVS10LinkFlagTable[] = {
{ "GenerateManifest", "MANIFEST:NO", "", "false", 0 },
{ "GenerateManifest", "MANIFEST", "", "true", 0 },
{ "AllowIsolation", "ALLOWISOLATION:NO", "", "false", 0 },
+
+ // correct flags for uac should be /MANIFESTUAC, but some projects already
+ // use this bug to access uac field, so keep these for compatibility
{ "UACUIAccess", "uiAccess='false'", "", "false", 0 },
{ "UACUIAccess", "uiAccess='true'", "", "true", 0 },
+
{ "GenerateDebugInformation", "DEBUG", "", "true",
cmVS7FlagTable::CaseInsensitive },
{ "MapExports", "MAPINFO:EXPORTS", "", "true", 0 },
@@ -162,11 +168,8 @@ static cmVS7FlagTable cmVS10LinkFlagTable[] = {
{ "LinkDLL", "DLL", "", "true", 0 },
// Bool Properties With Argument
- { "EnableUAC", "MANIFESTUAC:NO", "", "false", 0 },
- { "EnableUAC", "MANIFESTUAC:", "", "true",
- cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
- { "UACUIAccess", "MANIFESTUAC:", "Enable User Account Control (UAC)", "",
- cmVS7FlagTable::UserValueRequired },
+ { "EnableUAC", "MANIFESTUAC:", "", "",
+ cmVS7FlagTable::UserValueRequired | cmVS7FlagTable::SpaceAppendable },
{ "GenerateMapFile", "MAP", "", "true",
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
{ "MapFileName", "MAP:", "Generate Map File", "",
diff --git a/Source/cmVS11CLFlagTable.h b/Source/cmVS11CLFlagTable.h
index 75317093f..d156938e1 100644
--- a/Source/cmVS11CLFlagTable.h
+++ b/Source/cmVS11CLFlagTable.h
@@ -74,7 +74,8 @@ static cmVS7FlagTable cmVS11CLFlagTable[] = {
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
{ "PrecompiledHeader", "Yu", "Use", "Use",
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
- { "PrecompiledHeader", "", "Not Using Precompiled Headers", "NotUsing", 0 },
+ { "PrecompiledHeader", "Y-", "Not Using Precompiled Headers", "NotUsing",
+ 0 },
{ "AssemblerOutput", "", "No Listing", "NoListing", 0 },
{ "AssemblerOutput", "FA", "Assembly-Only Listing", "AssemblyCode", 0 },
diff --git a/Source/cmVS11CSharpFlagTable.h b/Source/cmVS11CSharpFlagTable.h
index 71870b698..e3ba83c2c 100644
--- a/Source/cmVS11CSharpFlagTable.h
+++ b/Source/cmVS11CSharpFlagTable.h
@@ -25,7 +25,8 @@ static cmVS7FlagTable cmVS11CSharpFlagTable[] = {
{ "ApplicationIcon", "win32icon", "", "",
cmIDEFlagTable::UserValueRequired },
- { "Win32Manifest", "win32manifest:", "", "true", 0 },
+ { "ApplicationManifest", "win32manifest:", "", "",
+ cmIDEFlagTable::UserValueRequired },
{ "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
diff --git a/Source/cmVS11LinkFlagTable.h b/Source/cmVS11LinkFlagTable.h
index 1b3a046f6..24ba8fded 100644
--- a/Source/cmVS11LinkFlagTable.h
+++ b/Source/cmVS11LinkFlagTable.h
@@ -29,6 +29,8 @@ static cmVS7FlagTable cmVS11LinkFlagTable[] = {
{ "CreateHotPatchableImage", "FUNCTIONPADMIN:16", "Itanium Image Only",
"ItaniumImage", 0 },
+ // correct flags for uac should be /MANIFESTUAC, but some projects already
+ // use this bug to access uac field, so keep these for compatibility
{ "UACExecutionLevel", "level='asInvoker'", "asInvoker", "AsInvoker", 0 },
{ "UACExecutionLevel", "level='highestAvailable'", "highestAvailable",
"HighestAvailable", 0 },
@@ -135,8 +137,12 @@ static cmVS7FlagTable cmVS11LinkFlagTable[] = {
{ "GenerateManifest", "MANIFEST:NO", "", "false", 0 },
{ "GenerateManifest", "MANIFEST", "", "true", 0 },
{ "AllowIsolation", "ALLOWISOLATION:NO", "", "false", 0 },
+
+ // correct flags for uac should be /MANIFESTUAC, but some projects already
+ // use this bug to access uac field, so keep these for compatibility
{ "UACUIAccess", "uiAccess='false'", "", "false", 0 },
{ "UACUIAccess", "uiAccess='true'", "", "true", 0 },
+
{ "ManifestEmbed", "manifest:embed", "", "true", 0 },
{ "GenerateDebugInformation", "DEBUG", "", "true",
cmVS7FlagTable::CaseInsensitive },
@@ -179,11 +185,8 @@ static cmVS7FlagTable cmVS11LinkFlagTable[] = {
{ "LinkDLL", "DLL", "", "true", 0 },
// Bool Properties With Argument
- { "EnableUAC", "MANIFESTUAC:NO", "", "false", 0 },
- { "EnableUAC", "MANIFESTUAC:", "", "true",
- cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
- { "UACUIAccess", "MANIFESTUAC:", "Enable User Account Control (UAC)", "",
- cmVS7FlagTable::UserValueRequired },
+ { "EnableUAC", "MANIFESTUAC:", "", "",
+ cmVS7FlagTable::UserValueRequired | cmVS7FlagTable::SpaceAppendable },
{ "GenerateMapFile", "MAP", "", "true",
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
{ "MapFileName", "MAP:", "Generate Map File", "",
diff --git a/Source/cmVS12CLFlagTable.h b/Source/cmVS12CLFlagTable.h
index 9515c91b8..a4f251808 100644
--- a/Source/cmVS12CLFlagTable.h
+++ b/Source/cmVS12CLFlagTable.h
@@ -78,7 +78,8 @@ static cmVS7FlagTable cmVS12CLFlagTable[] = {
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
{ "PrecompiledHeader", "Yu", "Use", "Use",
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
- { "PrecompiledHeader", "", "Not Using Precompiled Headers", "NotUsing", 0 },
+ { "PrecompiledHeader", "Y-", "Not Using Precompiled Headers", "NotUsing",
+ 0 },
{ "AssemblerOutput", "", "No Listing", "NoListing", 0 },
{ "AssemblerOutput", "FA", "Assembly-Only Listing", "AssemblyCode", 0 },
diff --git a/Source/cmVS12CSharpFlagTable.h b/Source/cmVS12CSharpFlagTable.h
index f98b1840d..f8db63670 100644
--- a/Source/cmVS12CSharpFlagTable.h
+++ b/Source/cmVS12CSharpFlagTable.h
@@ -25,7 +25,8 @@ static cmVS7FlagTable cmVS12CSharpFlagTable[] = {
{ "ApplicationIcon", "win32icon", "", "",
cmIDEFlagTable::UserValueRequired },
- { "Win32Manifest", "win32manifest:", "", "true", 0 },
+ { "ApplicationManifest", "win32manifest:", "", "",
+ cmIDEFlagTable::UserValueRequired },
{ "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
diff --git a/Source/cmVS12LinkFlagTable.h b/Source/cmVS12LinkFlagTable.h
index 168c34c22..fc667c359 100644
--- a/Source/cmVS12LinkFlagTable.h
+++ b/Source/cmVS12LinkFlagTable.h
@@ -29,6 +29,8 @@ static cmVS7FlagTable cmVS12LinkFlagTable[] = {
{ "CreateHotPatchableImage", "FUNCTIONPADMIN:16", "Itanium Image Only",
"ItaniumImage", 0 },
+ // correct flags for uac should be /MANIFESTUAC, but some projects already
+ // use this bug to access uac field, so keep these for compatibility
{ "UACExecutionLevel", "level='asInvoker'", "asInvoker", "AsInvoker", 0 },
{ "UACExecutionLevel", "level='highestAvailable'", "highestAvailable",
"HighestAvailable", 0 },
@@ -135,8 +137,12 @@ static cmVS7FlagTable cmVS12LinkFlagTable[] = {
{ "GenerateManifest", "MANIFEST:NO", "", "false", 0 },
{ "GenerateManifest", "MANIFEST", "", "true", 0 },
{ "AllowIsolation", "ALLOWISOLATION:NO", "", "false", 0 },
+
+ // correct flags for uac should be /MANIFESTUAC, but some projects already
+ // use this bug to access uac field, so keep these for compatibility
{ "UACUIAccess", "uiAccess='false'", "", "false", 0 },
{ "UACUIAccess", "uiAccess='true'", "", "true", 0 },
+
{ "ManifestEmbed", "manifest:embed", "", "true", 0 },
{ "GenerateDebugInformation", "DEBUG", "", "true",
cmVS7FlagTable::CaseInsensitive },
@@ -179,11 +185,8 @@ static cmVS7FlagTable cmVS12LinkFlagTable[] = {
{ "LinkDLL", "DLL", "", "true", 0 },
// Bool Properties With Argument
- { "EnableUAC", "MANIFESTUAC:NO", "", "false", 0 },
- { "EnableUAC", "MANIFESTUAC:", "", "true",
- cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
- { "UACUIAccess", "MANIFESTUAC:", "Enable User Account Control (UAC)", "",
- cmVS7FlagTable::UserValueRequired },
+ { "EnableUAC", "MANIFESTUAC:", "", "",
+ cmVS7FlagTable::UserValueRequired | cmVS7FlagTable::SpaceAppendable },
{ "GenerateMapFile", "MAP", "", "true",
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
{ "MapFileName", "MAP:", "Generate Map File", "",
diff --git a/Source/cmVS140CLFlagTable.h b/Source/cmVS140CLFlagTable.h
index 60b437974..2b89042c8 100644
--- a/Source/cmVS140CLFlagTable.h
+++ b/Source/cmVS140CLFlagTable.h
@@ -80,7 +80,8 @@ static cmVS7FlagTable cmVS140CLFlagTable[] = {
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
{ "PrecompiledHeader", "Yu", "Use", "Use",
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
- { "PrecompiledHeader", "", "Not Using Precompiled Headers", "NotUsing", 0 },
+ { "PrecompiledHeader", "Y-", "Not Using Precompiled Headers", "NotUsing",
+ 0 },
{ "AssemblerOutput", "", "No Listing", "NoListing", 0 },
{ "AssemblerOutput", "FA", "Assembly-Only Listing", "AssemblyCode", 0 },
diff --git a/Source/cmVS140CSharpFlagTable.h b/Source/cmVS140CSharpFlagTable.h
index 256c35f70..055d5cba0 100644
--- a/Source/cmVS140CSharpFlagTable.h
+++ b/Source/cmVS140CSharpFlagTable.h
@@ -25,7 +25,8 @@ static cmVS7FlagTable cmVS140CSharpFlagTable[] = {
{ "ApplicationIcon", "win32icon", "", "",
cmIDEFlagTable::UserValueRequired },
- { "Win32Manifest", "win32manifest:", "", "true", 0 },
+ { "ApplicationManifest", "win32manifest:", "", "",
+ cmIDEFlagTable::UserValueRequired },
{ "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
diff --git a/Source/cmVS140LinkFlagTable.h b/Source/cmVS140LinkFlagTable.h
index b9a4dc30a..7c9452abf 100644
--- a/Source/cmVS140LinkFlagTable.h
+++ b/Source/cmVS140LinkFlagTable.h
@@ -29,6 +29,8 @@ static cmVS7FlagTable cmVS140LinkFlagTable[] = {
{ "CreateHotPatchableImage", "FUNCTIONPADMIN:16", "Itanium Image Only",
"ItaniumImage", 0 },
+ // correct flags for uac should be /MANIFESTUAC, but some projects already
+ // use this bug to access uac field, so keep these for compatibility
{ "UACExecutionLevel", "level='asInvoker'", "asInvoker", "AsInvoker", 0 },
{ "UACExecutionLevel", "level='highestAvailable'", "highestAvailable",
"HighestAvailable", 0 },
@@ -148,8 +150,12 @@ static cmVS7FlagTable cmVS140LinkFlagTable[] = {
{ "GenerateManifest", "MANIFEST:NO", "", "false", 0 },
{ "GenerateManifest", "MANIFEST", "", "true", 0 },
{ "AllowIsolation", "ALLOWISOLATION:NO", "", "false", 0 },
+
+ // correct flags for uac should be /MANIFESTUAC, but some projects already
+ // use this bug to access uac field, so keep these for compatibility
{ "UACUIAccess", "uiAccess='false'", "", "false", 0 },
{ "UACUIAccess", "uiAccess='true'", "", "true", 0 },
+
{ "ManifestEmbed", "manifest:embed", "", "true", 0 },
{ "MapExports", "MAPINFO:EXPORTS", "", "true", 0 },
{ "AssemblyDebug", "ASSEMBLYDEBUG:DISABLE", "", "false", 0 },
@@ -190,11 +196,8 @@ static cmVS7FlagTable cmVS140LinkFlagTable[] = {
{ "LinkDLL", "DLL", "", "true", 0 },
// Bool Properties With Argument
- { "EnableUAC", "MANIFESTUAC:NO", "", "false", 0 },
- { "EnableUAC", "MANIFESTUAC:", "", "true",
- cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
- { "UACUIAccess", "MANIFESTUAC:", "Enable User Account Control (UAC)", "",
- cmVS7FlagTable::UserValueRequired },
+ { "EnableUAC", "MANIFESTUAC:", "", "",
+ cmVS7FlagTable::UserValueRequired | cmVS7FlagTable::SpaceAppendable },
{ "GenerateMapFile", "MAP", "", "true",
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
{ "MapFileName", "MAP:", "Generate Map File", "",
diff --git a/Source/cmVS141CLFlagTable.h b/Source/cmVS141CLFlagTable.h
index f751fc875..c780d469a 100644
--- a/Source/cmVS141CLFlagTable.h
+++ b/Source/cmVS141CLFlagTable.h
@@ -79,6 +79,7 @@ static cmVS7FlagTable cmVS141CLFlagTable[] = {
{ "FloatingPointModel", "fp:strict", "Strict", "Strict", 0 },
{ "FloatingPointModel", "fp:fast", "Fast", "Fast", 0 },
+ { "LanguageStandard", "std:c++17", "ISO C++17 Standard", "stdcpp17", 0 },
{ "LanguageStandard", "std:c++14", "ISO C++14 Standard", "stdcpp14", 0 },
{ "LanguageStandard", "std:c++latest", "ISO C++ Latest Draft Standard",
"stdcpplatest", 0 },
@@ -87,7 +88,8 @@ static cmVS7FlagTable cmVS141CLFlagTable[] = {
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
{ "PrecompiledHeader", "Yu", "Use", "Use",
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
- { "PrecompiledHeader", "", "Not Using Precompiled Headers", "NotUsing", 0 },
+ { "PrecompiledHeader", "Y-", "Not Using Precompiled Headers", "NotUsing",
+ 0 },
{ "AssemblerOutput", "", "No Listing", "NoListing", 0 },
{ "AssemblerOutput", "FA", "Assembly-Only Listing", "AssemblyCode", 0 },
diff --git a/Source/cmVS141CSharpFlagTable.h b/Source/cmVS141CSharpFlagTable.h
index 85085817c..5de9bf33f 100644
--- a/Source/cmVS141CSharpFlagTable.h
+++ b/Source/cmVS141CSharpFlagTable.h
@@ -25,7 +25,8 @@ static cmVS7FlagTable cmVS141CSharpFlagTable[] = {
{ "ApplicationIcon", "win32icon", "", "",
cmIDEFlagTable::UserValueRequired },
- { "Win32Manifest", "win32manifest:", "", "true", 0 },
+ { "ApplicationManifest", "win32manifest:", "", "",
+ cmIDEFlagTable::UserValueRequired },
{ "NoWin32Manifest", "nowin32manifest", "", "true", 0 },
diff --git a/Source/cmVS141LinkFlagTable.h b/Source/cmVS141LinkFlagTable.h
index 8f0f1f42d..f159f7061 100644
--- a/Source/cmVS141LinkFlagTable.h
+++ b/Source/cmVS141LinkFlagTable.h
@@ -29,6 +29,8 @@ static cmVS7FlagTable cmVS141LinkFlagTable[] = {
{ "CreateHotPatchableImage", "FUNCTIONPADMIN:16", "Itanium Image Only",
"ItaniumImage", 0 },
+ // correct flags for uac should be /MANIFESTUAC, but some projects already
+ // use this bug to access uac field, so keep these for compatibility
{ "UACExecutionLevel", "level='asInvoker'", "asInvoker", "AsInvoker", 0 },
{ "UACExecutionLevel", "level='highestAvailable'", "highestAvailable",
"HighestAvailable", 0 },
@@ -87,6 +89,7 @@ static cmVS7FlagTable cmVS141LinkFlagTable[] = {
{ "TargetMachine", "", "Not Set", "NotSet", 0 },
{ "TargetMachine", "MACHINE:ARM", "MachineARM", "MachineARM", 0 },
+ { "TargetMachine", "MACHINE:ARM64", "MachineARM64", "MachineARM64", 0 },
{ "TargetMachine", "MACHINE:EBC", "MachineEBC", "MachineEBC", 0 },
{ "TargetMachine", "MACHINE:IA64", "MachineIA64", "MachineIA64", 0 },
{ "TargetMachine", "MACHINE:MIPS", "MachineMIPS", "MachineMIPS", 0 },
@@ -149,8 +152,12 @@ static cmVS7FlagTable cmVS141LinkFlagTable[] = {
{ "GenerateManifest", "MANIFEST:NO", "", "false", 0 },
{ "GenerateManifest", "MANIFEST", "", "true", 0 },
{ "AllowIsolation", "ALLOWISOLATION:NO", "", "false", 0 },
+
+ // correct flags for uac should be /MANIFESTUAC, but some projects already
+ // use this bug to access uac field, so keep these for compatibility
{ "UACUIAccess", "uiAccess='false'", "", "false", 0 },
{ "UACUIAccess", "uiAccess='true'", "", "true", 0 },
+
{ "ManifestEmbed", "manifest:embed", "", "true", 0 },
{ "MapExports", "MAPINFO:EXPORTS", "", "true", 0 },
{ "AssemblyDebug", "ASSEMBLYDEBUG:DISABLE", "", "false", 0 },
@@ -191,11 +198,8 @@ static cmVS7FlagTable cmVS141LinkFlagTable[] = {
{ "LinkDLL", "DLL", "", "true", 0 },
// Bool Properties With Argument
- { "EnableUAC", "MANIFESTUAC:NO", "", "false", 0 },
- { "EnableUAC", "MANIFESTUAC:", "", "true",
- cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
- { "UACUIAccess", "MANIFESTUAC:", "Enable User Account Control (UAC)", "",
- cmVS7FlagTable::UserValueRequired },
+ { "EnableUAC", "MANIFESTUAC:", "", "",
+ cmVS7FlagTable::UserValueRequired | cmVS7FlagTable::SpaceAppendable },
{ "GenerateMapFile", "MAP", "", "true",
cmVS7FlagTable::UserValueIgnored | cmVS7FlagTable::Continue },
{ "MapFileName", "MAP:", "Generate Map File", "",
diff --git a/Source/cmVS14LibFlagTable.h b/Source/cmVS14LibFlagTable.h
index 7fa713893..be4652c68 100644
--- a/Source/cmVS14LibFlagTable.h
+++ b/Source/cmVS14LibFlagTable.h
@@ -11,6 +11,7 @@ static cmVS7FlagTable cmVS14LibFlagTable[] = {
0 },
{ "TargetMachine", "MACHINE:ARM", "MachineARM", "MachineARM", 0 },
+ { "TargetMachine", "MACHINE:ARM64", "MachineARM64", "MachineARM64", 0 },
{ "TargetMachine", "MACHINE:EBC", "MachineEBC", "MachineEBC", 0 },
{ "TargetMachine", "MACHINE:IA64", "MachineIA64", "MachineIA64", 0 },
{ "TargetMachine", "MACHINE:MIPS", "MachineMIPS", "MachineMIPS", 0 },
diff --git a/Source/cmVSSetupHelper.cxx b/Source/cmVSSetupHelper.cxx
index 7168f266c..ea13649c2 100644
--- a/Source/cmVSSetupHelper.cxx
+++ b/Source/cmVSSetupHelper.cxx
@@ -1,7 +1,10 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmVSSetupHelper.h"
+
#include "cmSystemTools.h"
+#include "cmsys/Encoding.hxx"
+#include "cmsys/FStream.hxx"
#ifndef VSSetupConstants
#define VSSetupConstants
@@ -41,14 +44,19 @@ const CLSID CLSID_SetupConfiguration = {
/* clang-format on */
#endif
-const WCHAR* VCToolsetComponent =
- L"Microsoft.VisualStudio.Component.VC.Tools.x86.x64";
const WCHAR* Win10SDKComponent =
L"Microsoft.VisualStudio.Component.Windows10SDK";
const WCHAR* Win81SDKComponent =
L"Microsoft.VisualStudio.Component.Windows81SDK";
const WCHAR* ComponentType = L"Component";
+std::string VSInstanceInfo::GetInstallLocation() const
+{
+ std::string loc = cmsys::Encoding::ToNarrow(this->VSInstallLocation);
+ cmSystemTools::ConvertToUnixSlashes(loc);
+ return loc;
+}
+
cmVSSetupAPIHelper::cmVSSetupAPIHelper()
: setupConfig(NULL)
, setupConfig2(NULL)
@@ -90,11 +98,11 @@ bool cmVSSetupAPIHelper::IsWin81SDKInstalled()
}
bool cmVSSetupAPIHelper::CheckInstalledComponent(
- SmartCOMPtr<ISetupPackageReference> package, bool& bVCToolset,
- bool& bWin10SDK, bool& bWin81SDK)
+ SmartCOMPtr<ISetupPackageReference> package, bool& bWin10SDK,
+ bool& bWin81SDK)
{
bool ret = false;
- bVCToolset = bWin10SDK = bWin81SDK = false;
+ bWin10SDK = bWin81SDK = false;
SmartBSTR bstrId;
if (FAILED(package->GetId(&bstrId))) {
return ret;
@@ -107,11 +115,6 @@ bool cmVSSetupAPIHelper::CheckInstalledComponent(
std::wstring id = std::wstring(bstrId);
std::wstring type = std::wstring(bstrType);
- if (id.compare(VCToolsetComponent) == 0 &&
- type.compare(ComponentType) == 0) {
- bVCToolset = true;
- ret = true;
- }
// Checks for any version of Win10 SDK. The version is appended at the end of
// the
@@ -135,7 +138,6 @@ bool cmVSSetupAPIHelper::CheckInstalledComponent(
bool cmVSSetupAPIHelper::GetVSInstanceInfo(
SmartCOMPtr<ISetupInstance2> pInstance, VSInstanceInfo& vsInstanceInfo)
{
- bool isVCToolSetInstalled = false;
if (pInstance == NULL)
return false;
@@ -174,6 +176,23 @@ bool cmVSSetupAPIHelper::GetVSInstanceInfo(
}
}
+ // Check if a compiler is installed with this instance.
+ {
+ std::string const vcRoot = vsInstanceInfo.GetInstallLocation();
+ std::string const vcToolsVersionFile =
+ vcRoot + "/VC/Auxiliary/Build/Microsoft.VCToolsVersion.default.txt";
+ std::string vcToolsVersion;
+ cmsys::ifstream fin(vcToolsVersionFile.c_str());
+ if (!fin || !cmSystemTools::GetLineFromStream(fin, vcToolsVersion)) {
+ return false;
+ }
+ vcToolsVersion = cmSystemTools::TrimWhitespace(vcToolsVersion);
+ std::string const vcToolsDir = vcRoot + "/VC/Tools/MSVC/" + vcToolsVersion;
+ if (!cmSystemTools::FileIsDirectory(vcToolsDir)) {
+ return false;
+ }
+ }
+
// Reboot may have been required before the product package was registered
// (last).
if ((eRegistered & state) == eRegistered) {
@@ -199,12 +218,11 @@ bool cmVSSetupAPIHelper::GetVSInstanceInfo(
package == NULL)
continue;
- bool vcToolsetInstalled = false, win10SDKInstalled = false,
- win81SDkInstalled = false;
- bool ret = CheckInstalledComponent(package, vcToolsetInstalled,
- win10SDKInstalled, win81SDkInstalled);
+ bool win10SDKInstalled = false;
+ bool win81SDkInstalled = false;
+ bool ret =
+ CheckInstalledComponent(package, win10SDKInstalled, win81SDkInstalled);
if (ret) {
- isVCToolSetInstalled |= vcToolsetInstalled;
vsInstanceInfo.IsWin10SDKInstalled |= win10SDKInstalled;
vsInstanceInfo.IsWin81SDKInstalled |= win81SDkInstalled;
}
@@ -213,18 +231,16 @@ bool cmVSSetupAPIHelper::GetVSInstanceInfo(
SafeArrayDestroy(lpsaPackages);
}
- return isVCToolSetInstalled;
+ return true;
}
bool cmVSSetupAPIHelper::GetVSInstanceInfo(std::string& vsInstallLocation)
{
- vsInstallLocation = "";
+ vsInstallLocation.clear();
bool isInstalled = this->EnumerateAndChooseVSInstance();
if (isInstalled) {
- std::string str(chosenInstanceInfo.VSInstallLocation.begin(),
- chosenInstanceInfo.VSInstallLocation.end());
- vsInstallLocation = str;
+ vsInstallLocation = chosenInstanceInfo.GetInstallLocation();
}
return isInstalled;
@@ -281,9 +297,7 @@ bool cmVSSetupAPIHelper::EnumerateAndChooseVSInstance()
if (isInstalled) {
if (!envVSCommonToolsDir.empty()) {
- std::string currentVSLocation(instanceInfo.VSInstallLocation.begin(),
- instanceInfo.VSInstallLocation.end());
- cmSystemTools::ConvertToUnixSlashes(currentVSLocation);
+ std::string currentVSLocation = instanceInfo.GetInstallLocation();
currentVSLocation += "/Common7/Tools";
if (cmSystemTools::ComparePath(currentVSLocation,
envVSCommonToolsDir)) {
diff --git a/Source/cmVSSetupHelper.h b/Source/cmVSSetupHelper.h
index d2f514c63..74a7ec04a 100644
--- a/Source/cmVSSetupHelper.h
+++ b/Source/cmVSSetupHelper.h
@@ -116,6 +116,8 @@ struct VSInstanceInfo
ullVersion = 0;
IsWin10SDKInstalled = IsWin81SDKInstalled = false;
}
+
+ std::string GetInstallLocation() const;
};
class cmVSSetupAPIHelper
@@ -134,8 +136,7 @@ private:
bool GetVSInstanceInfo(SmartCOMPtr<ISetupInstance2> instance2,
VSInstanceInfo& vsInstanceInfo);
bool CheckInstalledComponent(SmartCOMPtr<ISetupPackageReference> package,
- bool& bVCToolset, bool& bWin10SDK,
- bool& bWin81SDK);
+ bool& bWin10SDK, bool& bWin81SDK);
int ChooseVSInstance(const std::vector<VSInstanceInfo>& vecVSInstances);
bool EnumerateAndChooseVSInstance();
diff --git a/Source/cmVariableRequiresCommand.h b/Source/cmVariableRequiresCommand.h
index 9808d5f0c..94970c584 100644
--- a/Source/cmVariableRequiresCommand.h
+++ b/Source/cmVariableRequiresCommand.h
@@ -3,7 +3,7 @@
#ifndef cmVariableRequiresCommand_h
#define cmVariableRequiresCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -15,9 +15,9 @@ class cmExecutionStatus;
class cmVariableRequiresCommand : public cmCommand
{
public:
- cmCommand* Clone() CM_OVERRIDE { return new cmVariableRequiresCommand; }
+ cmCommand* Clone() override { return new cmVariableRequiresCommand; }
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmVariableWatch.cxx b/Source/cmVariableWatch.cxx
index 419e1a411..bd5d19c39 100644
--- a/Source/cmVariableWatch.cxx
+++ b/Source/cmVariableWatch.cxx
@@ -2,11 +2,9 @@
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmVariableWatch.h"
-#include "cmAlgorithms.h"
-
-#include "cm_auto_ptr.hxx"
-#include <algorithm>
+#include <memory>
#include <utility>
+#include <vector>
static const char* const cmVariableWatchAccessStrings[] = {
"READ_ACCESS", "UNKNOWN_READ_ACCESS", "UNKNOWN_DEFINED_ACCESS",
@@ -25,37 +23,27 @@ cmVariableWatch::cmVariableWatch()
{
}
-template <typename C>
-void deleteAllSecond(typename C::value_type it)
-{
- cmDeleteAll(it.second);
-}
-
cmVariableWatch::~cmVariableWatch()
{
- std::for_each(this->WatchMap.begin(), this->WatchMap.end(),
- deleteAllSecond<cmVariableWatch::StringToVectorOfPairs>);
}
bool cmVariableWatch::AddWatch(const std::string& variable, WatchMethod method,
void* client_data /*=0*/,
DeleteData delete_data /*=0*/)
{
- CM_AUTO_PTR<cmVariableWatch::Pair> p(new cmVariableWatch::Pair);
+ auto p = std::make_shared<cmVariableWatch::Pair>();
p->Method = method;
p->ClientData = client_data;
p->DeleteDataCall = delete_data;
- cmVariableWatch::VectorOfPairs* vp = &this->WatchMap[variable];
- cmVariableWatch::VectorOfPairs::size_type cc;
- for (cc = 0; cc < vp->size(); cc++) {
- cmVariableWatch::Pair* pair = (*vp)[cc];
+ cmVariableWatch::VectorOfPairs& vp = this->WatchMap[variable];
+ for (auto& pair : vp) {
if (pair->Method == method && client_data &&
client_data == pair->ClientData) {
// Callback already exists
return false;
}
}
- vp->push_back(p.release());
+ vp.push_back(std::move(p));
return true;
}
@@ -72,7 +60,6 @@ void cmVariableWatch::RemoveWatch(const std::string& variable,
// If client_data is NULL, we want to disconnect all watches against
// the given method; otherwise match ClientData as well.
(!client_data || (client_data == (*it)->ClientData))) {
- delete *it;
vp->erase(it);
return;
}
@@ -86,10 +73,17 @@ bool cmVariableWatch::VariableAccessed(const std::string& variable,
cmVariableWatch::StringToVectorOfPairs::const_iterator mit =
this->WatchMap.find(variable);
if (mit != this->WatchMap.end()) {
- const cmVariableWatch::VectorOfPairs* vp = &mit->second;
- cmVariableWatch::VectorOfPairs::const_iterator it;
- for (it = vp->begin(); it != vp->end(); it++) {
- (*it)->Method(variable, access_type, (*it)->ClientData, newValue, mf);
+ // The strategy here is to copy the list of callbacks, and ignore
+ // new callbacks that existing ones may add.
+ std::vector<std::weak_ptr<Pair>> vp(mit->second.begin(),
+ mit->second.end());
+ for (auto& weak_it : vp) {
+ // In the case where a callback was removed, the weak_ptr will not be
+ // lockable, and so this ensures we don't attempt to call into freed
+ // memory
+ if (auto it = weak_it.lock()) {
+ it->Method(variable, access_type, it->ClientData, newValue, mf);
+ }
}
return true;
}
diff --git a/Source/cmVariableWatch.h b/Source/cmVariableWatch.h
index a575afe9d..27d1b12df 100644
--- a/Source/cmVariableWatch.h
+++ b/Source/cmVariableWatch.h
@@ -6,6 +6,7 @@
#include "cmConfigure.h" // IWYU pragma: keep
#include <map>
+#include <memory> // IWYU pragma: keep
#include <string>
#include <vector>
@@ -31,10 +32,9 @@ public:
* Add watch to the variable
*/
bool AddWatch(const std::string& variable, WatchMethod method,
- void* client_data = CM_NULLPTR,
- DeleteData delete_data = CM_NULLPTR);
+ void* client_data = nullptr, DeleteData delete_data = nullptr);
void RemoveWatch(const std::string& variable, WatchMethod method,
- void* client_data = CM_NULLPTR);
+ void* client_data = nullptr);
/**
* This method is called when variable is accessed
@@ -67,9 +67,9 @@ protected:
void* ClientData;
DeleteData DeleteDataCall;
Pair()
- : Method(CM_NULLPTR)
- , ClientData(CM_NULLPTR)
- , DeleteDataCall(CM_NULLPTR)
+ : Method(nullptr)
+ , ClientData(nullptr)
+ , DeleteDataCall(nullptr)
{
}
~Pair()
@@ -80,7 +80,7 @@ protected:
}
};
- typedef std::vector<Pair*> VectorOfPairs;
+ typedef std::vector<std::shared_ptr<Pair>> VectorOfPairs;
typedef std::map<std::string, VectorOfPairs> StringToVectorOfPairs;
StringToVectorOfPairs WatchMap;
diff --git a/Source/cmVariableWatchCommand.cxx b/Source/cmVariableWatchCommand.cxx
index 281850ecc..9930086f4 100644
--- a/Source/cmVariableWatchCommand.cxx
+++ b/Source/cmVariableWatchCommand.cxx
@@ -91,11 +91,9 @@ cmVariableWatchCommand::cmVariableWatchCommand()
cmVariableWatchCommand::~cmVariableWatchCommand()
{
- std::set<std::string>::const_iterator it;
- for (it = this->WatchedVariables.begin(); it != this->WatchedVariables.end();
- ++it) {
+ for (std::string const& wv : this->WatchedVariables) {
this->Makefile->GetCMakeInstance()->GetVariableWatch()->RemoveWatch(
- *it, cmVariableWatchCommandVariableAccessed);
+ wv, cmVariableWatchCommandVariableAccessed);
}
}
diff --git a/Source/cmVariableWatchCommand.h b/Source/cmVariableWatchCommand.h
index 9f0439175..6a8115d74 100644
--- a/Source/cmVariableWatchCommand.h
+++ b/Source/cmVariableWatchCommand.h
@@ -3,7 +3,7 @@
#ifndef cmVariableWatchCommand_h
#define cmVariableWatchCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <set>
#include <string>
@@ -23,24 +23,24 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmVariableWatchCommand; }
+ cmCommand* Clone() override { return new cmVariableWatchCommand; }
//! Default constructor
cmVariableWatchCommand();
//! Destructor.
- ~cmVariableWatchCommand() CM_OVERRIDE;
+ ~cmVariableWatchCommand() override;
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
/** This command does not really have a final pass but it needs to
stay alive since it owns variable watch callback information. */
- bool HasFinalPass() const CM_OVERRIDE { return true; }
+ bool HasFinalPass() const override { return true; }
protected:
std::set<std::string> WatchedVariables;
diff --git a/Source/cmVisualStudio10TargetGenerator.cxx b/Source/cmVisualStudio10TargetGenerator.cxx
index dee153f6b..c61902ab6 100644
--- a/Source/cmVisualStudio10TargetGenerator.cxx
+++ b/Source/cmVisualStudio10TargetGenerator.cxx
@@ -15,7 +15,7 @@
#include "cmVisualStudioGeneratorOptions.h"
#include "windows.h"
-#include "cm_auto_ptr.hxx"
+#include <memory> // IWYU pragma: keep
static std::string cmVS10EscapeXML(std::string arg)
{
@@ -25,6 +25,12 @@ static std::string cmVS10EscapeXML(std::string arg)
return arg;
}
+static std::string cmVS10EscapeQuotes(std::string arg)
+{
+ cmSystemTools::ReplaceString(arg, "\"", "&quot;");
+ return arg;
+}
+
static std::string cmVS10EscapeComment(std::string comment)
{
// MSBuild takes the CDATA of a <Message></Message> element and just
@@ -79,7 +85,7 @@ cmVisualStudio10TargetGenerator::cmVisualStudio10TargetGenerator(
this->LocalGenerator =
(cmLocalVisualStudio7Generator*)this->GeneratorTarget->GetLocalGenerator();
this->Name = this->GeneratorTarget->GetName();
- this->GUID = this->GlobalGenerator->GetGUID(this->Name.c_str());
+ this->GUID = this->GlobalGenerator->GetGUID(this->Name);
this->Platform = gg->GetPlatformName();
this->NsightTegra = gg->IsNsightTegra();
for (int i = 0; i < 4; ++i) {
@@ -144,7 +150,7 @@ void cmVisualStudio10TargetGenerator::WritePlatformConfigTag(
(*stream) << config << "|" << this->Platform;
(*stream) << "'";
// handle special case for 32 bit C# targets
- if (csproj == this->ProjectType && this->Platform == "Win32") {
+ if (this->ProjectType == csproj && this->Platform == "Win32") {
(*stream) << " Or ";
(*stream) << "'$(Configuration)|$(Platform)'=='";
(*stream) << config << "|x86";
@@ -292,7 +298,7 @@ void cmVisualStudio10TargetGenerator::Generate()
this->WriteString("</PropertyGroup>\n", 1);
}
- if (csproj != this->ProjectType) {
+ if (this->ProjectType != csproj) {
this->WriteProjectConfigurations();
}
this->WriteString("<PropertyGroup Label=\"Globals\">\n", 1);
@@ -309,7 +315,7 @@ void cmVisualStudio10TargetGenerator::Generate()
this->GeneratorTarget->GetProperty("VS_GLOBAL_PROJECT_TYPES");
if (vsProjectTypes) {
std::string tagName = "ProjectTypes";
- if (csproj == this->ProjectType) {
+ if (this->ProjectType == csproj) {
tagName = "ProjectTypeGuids";
}
this->WriteString("", 2);
@@ -401,11 +407,11 @@ void cmVisualStudio10TargetGenerator::Generate()
continue;
std::string globalKey = keyIt->substr(strlen(prefix));
// Skip invalid or separately-handled properties.
- if (globalKey == "" || globalKey == "PROJECT_TYPES" ||
+ if (globalKey.empty() || globalKey == "PROJECT_TYPES" ||
globalKey == "ROOTNAMESPACE" || globalKey == "KEYWORD") {
continue;
}
- const char* value = this->GeneratorTarget->GetProperty(keyIt->c_str());
+ const char* value = this->GeneratorTarget->GetProperty(*keyIt);
if (!value)
continue;
this->WriteString("<", 2);
@@ -463,7 +469,7 @@ void cmVisualStudio10TargetGenerator::Generate()
this->WriteProjectConfigurationValues();
- if (vcxproj == this->ProjectType) {
+ if (this->ProjectType == vcxproj) {
this->WriteString("<Import Project=\"" VS10_CXX_PROPS "\" />\n", 1);
}
this->WriteString("<ImportGroup Label=\"ExtensionSettings\">\n", 1);
@@ -566,7 +572,7 @@ void cmVisualStudio10TargetGenerator::Generate()
this->WriteString(import.c_str(), 2);
}
this->WriteString("</ImportGroup>\n", 1);
- if (csproj == this->ProjectType) {
+ if (this->ProjectType == csproj) {
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
@@ -576,6 +582,18 @@ void cmVisualStudio10TargetGenerator::Generate()
this->WriteEvents(*i);
this->WriteString("</PropertyGroup>\n", 1);
}
+ // make sure custom commands are executed before build (if necessary)
+ this->WriteString("<PropertyGroup>\n", 1);
+ this->WriteString("<BuildDependsOn>\n", 2);
+ for (std::set<std::string>::const_iterator i =
+ this->CSharpCustomCommandNames.begin();
+ i != this->CSharpCustomCommandNames.end(); ++i) {
+ this->WriteString(i->c_str(), 3);
+ (*this->BuildFileStream) << ";\n";
+ }
+ this->WriteString("$(BuildDependsOn)\n", 3);
+ this->WriteString("</BuildDependsOn>\n", 2);
+ this->WriteString("</PropertyGroup>\n", 1);
}
this->WriteString("</Project>", 0);
// The groups are stored in a separate file for VS 10
@@ -596,7 +614,7 @@ void cmVisualStudio10TargetGenerator::WriteDotNetReferences()
++i) {
if (i->first.find("VS_DOTNET_REFERENCE_") == 0) {
std::string name = i->first.substr(20);
- if (name != "") {
+ if (!name.empty()) {
std::string path = i->second.GetValue();
if (!cmsys::SystemTools::FileIsFullPath(path)) {
path = std::string(this->GeneratorTarget->Target->GetMakefile()
@@ -624,7 +642,7 @@ void cmVisualStudio10TargetGenerator::WriteDotNetReferences()
this->WriteDotNetReference(*ri, "");
}
}
- for (std::vector<std::pair<std::string, std::string> >::const_iterator i =
+ for (std::vector<std::pair<std::string, std::string>>::const_iterator i =
hintReferences.begin();
i != hintReferences.end(); ++i) {
this->WriteDotNetReference(i->first, i->second);
@@ -657,9 +675,39 @@ void cmVisualStudio10TargetGenerator::WriteDotNetReference(
this->WriteString("<HintPath>", 3);
(*this->BuildFileStream) << hint << "</HintPath>\n";
}
+ this->WriteDotNetReferenceCustomTags(ref);
this->WriteString("</Reference>\n", 2);
}
+void cmVisualStudio10TargetGenerator::WriteDotNetReferenceCustomTags(
+ std::string const& ref)
+{
+
+ static const std::string refpropPrefix = "VS_DOTNET_REFERENCEPROP_";
+ static const std::string refpropInfix = "_TAG_";
+ const std::string refPropFullPrefix = refpropPrefix + ref + refpropInfix;
+ typedef std::map<std::string, std::string> CustomTags;
+ CustomTags tags;
+ cmPropertyMap const& props = this->GeneratorTarget->Target->GetProperties();
+ for (cmPropertyMap::const_iterator i = props.begin(); i != props.end();
+ ++i) {
+ if (i->first.find(refPropFullPrefix) == 0) {
+ std::string refTag = i->first.substr(refPropFullPrefix.length());
+ std::string refVal = i->second.GetValue();
+ if (!refTag.empty() && !refVal.empty()) {
+ tags[refTag] = refVal;
+ }
+ }
+ }
+ for (CustomTags::const_iterator tag = tags.begin(); tag != tags.end();
+ ++tag) {
+ this->WriteString("<", 3);
+ (*this->BuildFileStream) << tag->first << ">"
+ << cmVS10EscapeXML(tag->second) << "</"
+ << tag->first << ">\n";
+ }
+}
+
void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup()
{
std::vector<cmSourceFile const*> resxObjs;
@@ -675,7 +723,7 @@ void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup()
this->WriteString("<EmbeddedResource Include=\"", 2);
this->ConvertToWindowsSlash(obj);
bool useRelativePath = false;
- if (csproj == this->ProjectType && this->InSourceBuild) {
+ if (this->ProjectType == csproj && this->InSourceBuild) {
// If we do an in-source build and the resource file is in a
// subdirectory
// of the .csproj file, we have to use relative pathnames, otherwise
@@ -688,7 +736,7 @@ void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup()
}
(*this->BuildFileStream) << obj << "\">\n";
- if (csproj != this->ProjectType) {
+ if (this->ProjectType != csproj) {
this->WriteString("<DependentUpon>", 3);
std::string hFileName = obj.substr(0, obj.find_last_of(".")) + ".h";
(*this->BuildFileStream) << hFileName << "</DependentUpon>\n";
@@ -696,7 +744,7 @@ void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup()
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
- this->WritePlatformConfigTag("LogicalName", i->c_str(), 3);
+ this->WritePlatformConfigTag("LogicalName", *i, 3);
if (this->GeneratorTarget->GetProperty("VS_GLOBAL_ROOTNAMESPACE") ||
// Handle variant of VS_GLOBAL_<variable> for RootNamespace.
this->GeneratorTarget->GetProperty("VS_GLOBAL_RootNamespace")) {
@@ -758,7 +806,7 @@ void cmVisualStudio10TargetGenerator::WriteEmbeddedResourceGroup()
for (cmPropertyMap::const_iterator p = props.begin(); p != props.end();
++p) {
static const std::string propNamePrefix = "VS_CSHARP_";
- if (p->first.find(propNamePrefix.c_str()) == 0) {
+ if (p->first.find(propNamePrefix) == 0) {
std::string tagName = p->first.substr(propNamePrefix.length());
if (!tagName.empty()) {
std::string value = props.GetPropertyValue(p->first);
@@ -798,7 +846,7 @@ void cmVisualStudio10TargetGenerator::WriteXamlFilesGroup()
}
this->WriteSource(xamlType, *oi, ">\n");
- if (csproj == this->ProjectType && !this->InSourceBuild) {
+ if (this->ProjectType == csproj && !this->InSourceBuild) {
// add <Link> tag to written XAML source if necessary
const std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
const std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
@@ -914,10 +962,10 @@ void cmVisualStudio10TargetGenerator::WriteProjectConfigurationValues()
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
- this->WritePlatformConfigTag("PropertyGroup", i->c_str(), 1,
+ this->WritePlatformConfigTag("PropertyGroup", *i, 1,
" Label=\"Configuration\"", "\n");
- if (csproj != this->ProjectType) {
+ if (this->ProjectType != csproj) {
std::string configType = "<ConfigurationType>";
if (const char* vsConfigurationType =
this->GeneratorTarget->GetProperty("VS_CONFIGURATION_TYPE")) {
@@ -1038,8 +1086,7 @@ void cmVisualStudio10TargetGenerator::WriteMSToolConfigurationValuesManaged(
this->WriteString("<DefineDebug>true</DefineDebug>\n", 2);
}
- std::string outDir =
- this->GeneratorTarget->GetDirectory(config.c_str()) + "/";
+ std::string outDir = this->GeneratorTarget->GetDirectory(config) + "/";
this->ConvertToWindowsSlash(outDir);
this->WriteString("<OutputPath>", 2);
(*this->BuildFileStream) << cmVS10EscapeXML(outDir) << "</OutputPath>\n";
@@ -1119,6 +1166,7 @@ void cmVisualStudio10TargetGenerator::WriteNsightTegraConfigurationValues(
void cmVisualStudio10TargetGenerator::WriteCustomCommands()
{
this->SourcesVisited.clear();
+ this->CSharpCustomCommandNames.clear();
std::vector<cmSourceFile const*> customCommands;
this->GeneratorTarget->GetCustomCommands(customCommands, "");
for (std::vector<cmSourceFile const*>::const_iterator si =
@@ -1140,9 +1188,14 @@ void cmVisualStudio10TargetGenerator::WriteCustomCommand(
}
}
if (cmCustomCommand const* command = sf->GetCustomCommand()) {
- this->WriteString("<ItemGroup>\n", 1);
+ // C# projects write their <Target> within WriteCustomRule()
+ if (this->ProjectType != csproj) {
+ this->WriteString("<ItemGroup>\n", 1);
+ }
this->WriteCustomRule(sf, *command);
- this->WriteString("</ItemGroup>\n", 1);
+ if (this->ProjectType != csproj) {
+ this->WriteString("</ItemGroup>\n", 1);
+ }
}
}
}
@@ -1177,8 +1230,20 @@ void cmVisualStudio10TargetGenerator::WriteCustomRule(
}
cmLocalVisualStudio7Generator* lg = this->LocalGenerator;
- this->WriteSource("CustomBuild", source, ">\n");
-
+ if (this->ProjectType != csproj) {
+ this->WriteSource("CustomBuild", source, ">\n");
+ } else {
+ this->WriteString("<ItemGroup>\n", 1);
+ std::string link;
+ this->GetCSharpSourceLink(source, link);
+ this->WriteSource("None", source, ">\n");
+ if (!link.empty()) {
+ this->WriteString("<Link>", 3);
+ (*this->BuildFileStream) << link << "</Link>\n";
+ }
+ this->WriteString("</None>\n", 2);
+ this->WriteString("</ItemGroup>\n", 1);
+ }
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
@@ -1186,41 +1251,90 @@ void cmVisualStudio10TargetGenerator::WriteCustomRule(
std::string comment = lg->ConstructComment(ccg);
comment = cmVS10EscapeComment(comment);
std::string script = cmVS10EscapeXML(lg->ConstructScript(ccg));
- this->WritePlatformConfigTag("Message", i->c_str(), 3);
- (*this->BuildFileStream) << cmVS10EscapeXML(comment) << "</Message>\n";
- this->WritePlatformConfigTag("Command", i->c_str(), 3);
- (*this->BuildFileStream) << script << "</Command>\n";
- this->WritePlatformConfigTag("AdditionalInputs", i->c_str(), 3);
-
- (*this->BuildFileStream) << cmVS10EscapeXML(source->GetFullPath());
+ // input files for custom command
+ std::stringstream inputs;
+ inputs << cmVS10EscapeXML(source->GetFullPath());
for (std::vector<std::string>::const_iterator d = ccg.GetDepends().begin();
d != ccg.GetDepends().end(); ++d) {
std::string dep;
- if (this->LocalGenerator->GetRealDependency(d->c_str(), i->c_str(),
- dep)) {
+ if (this->LocalGenerator->GetRealDependency(*d, *i, dep)) {
this->ConvertToWindowsSlash(dep);
- (*this->BuildFileStream) << ";" << cmVS10EscapeXML(dep);
+ inputs << ";" << cmVS10EscapeXML(dep);
}
}
- (*this->BuildFileStream) << ";%(AdditionalInputs)</AdditionalInputs>\n";
- this->WritePlatformConfigTag("Outputs", i->c_str(), 3);
+ // output files for custom command
+ std::stringstream outputs;
const char* sep = "";
for (std::vector<std::string>::const_iterator o = ccg.GetOutputs().begin();
o != ccg.GetOutputs().end(); ++o) {
std::string out = *o;
this->ConvertToWindowsSlash(out);
- (*this->BuildFileStream) << sep << cmVS10EscapeXML(out);
+ outputs << sep << cmVS10EscapeXML(out);
sep = ";";
}
- (*this->BuildFileStream) << "</Outputs>\n";
- if (this->LocalGenerator->GetVersion() >
- cmGlobalVisualStudioGenerator::VS10) {
- // VS >= 11 let us turn off linking of custom command outputs.
- this->WritePlatformConfigTag("LinkObjects", i->c_str(), 3);
- (*this->BuildFileStream) << "false</LinkObjects>\n";
+ if (this->ProjectType == csproj) {
+ std::string name = "CustomCommand_" + *i + "_" +
+ cmSystemTools::ComputeStringMD5(sourcePath);
+ std::string inputs_s = inputs.str();
+ std::string outputs_s = outputs.str();
+ comment = cmVS10EscapeQuotes(comment);
+ script = cmVS10EscapeQuotes(script);
+ inputs_s = cmVS10EscapeQuotes(inputs_s);
+ outputs_s = cmVS10EscapeQuotes(outputs_s);
+ this->WriteCustomRuleCSharp(*i, name, script, inputs_s, outputs_s,
+ comment);
+ } else {
+ this->WriteCustomRuleCpp(*i, script, inputs.str(), outputs.str(),
+ comment);
}
}
- this->WriteString("</CustomBuild>\n", 2);
+ if (this->ProjectType != csproj) {
+ this->WriteString("</CustomBuild>\n", 2);
+ }
+}
+
+void cmVisualStudio10TargetGenerator::WriteCustomRuleCpp(
+ std::string const& config, std::string const& script,
+ std::string const& inputs, std::string const& outputs,
+ std::string const& comment)
+{
+ this->WritePlatformConfigTag("Message", config, 3);
+ (*this->BuildFileStream) << cmVS10EscapeXML(comment) << "</Message>\n";
+ this->WritePlatformConfigTag("Command", config, 3);
+ (*this->BuildFileStream) << script << "</Command>\n";
+ this->WritePlatformConfigTag("AdditionalInputs", config, 3);
+ (*this->BuildFileStream) << inputs;
+ (*this->BuildFileStream) << ";%(AdditionalInputs)</AdditionalInputs>\n";
+ this->WritePlatformConfigTag("Outputs", config, 3);
+ (*this->BuildFileStream) << outputs << "</Outputs>\n";
+ if (this->LocalGenerator->GetVersion() >
+ cmGlobalVisualStudioGenerator::VS10) {
+ // VS >= 11 let us turn off linking of custom command outputs.
+ this->WritePlatformConfigTag("LinkObjects", config, 3);
+ (*this->BuildFileStream) << "false</LinkObjects>\n";
+ }
+}
+
+void cmVisualStudio10TargetGenerator::WriteCustomRuleCSharp(
+ std::string const& config, std::string const& name,
+ std::string const& script, std::string const& inputs,
+ std::string const& outputs, std::string const& comment)
+{
+ this->CSharpCustomCommandNames.insert(name);
+ std::stringstream attributes;
+ attributes << "\n Name=\"" << name << "\"";
+ attributes << "\n Inputs=\"" << inputs << "\"";
+ attributes << "\n Outputs=\"" << outputs << "\"";
+ this->WritePlatformConfigTag("Target", config, 1, attributes.str().c_str(),
+ "\n");
+ if (!comment.empty()) {
+ this->WriteString("<Exec Command=\"", 2);
+ (*this->BuildFileStream) << "echo " << cmVS10EscapeXML(comment)
+ << "\" />\n";
+ }
+ this->WriteString("<Exec Command=\"", 2);
+ (*this->BuildFileStream) << script << "\" />\n";
+ this->WriteString("</Target>\n", 1);
}
std::string cmVisualStudio10TargetGenerator::ConvertPath(
@@ -1243,7 +1357,7 @@ void cmVisualStudio10TargetGenerator::ConvertToWindowsSlash(std::string& s)
}
void cmVisualStudio10TargetGenerator::WriteGroups()
{
- if (csproj == this->ProjectType) {
+ if (this->ProjectType == csproj) {
return;
}
@@ -1355,7 +1469,7 @@ void cmVisualStudio10TargetGenerator::WriteGroups()
std::string guidName = "SG_Filter_";
guidName += name;
this->WriteString("<UniqueIdentifier>", 3);
- std::string guid = this->GlobalGenerator->GetGUID(guidName.c_str());
+ std::string guid = this->GlobalGenerator->GetGUID(guidName);
(*this->BuildFileStream) << "{" << guid << "}"
<< "</UniqueIdentifier>\n";
this->WriteString("</Filter>\n", 2);
@@ -1366,7 +1480,7 @@ void cmVisualStudio10TargetGenerator::WriteGroups()
this->WriteString("<Filter Include=\"Resource Files\">\n", 2);
std::string guidName = "SG_Filter_Resource Files";
this->WriteString("<UniqueIdentifier>", 3);
- std::string guid = this->GlobalGenerator->GetGUID(guidName.c_str());
+ std::string guid = this->GlobalGenerator->GetGUID(guidName);
(*this->BuildFileStream) << "{" << guid << "}"
<< "</UniqueIdentifier>\n";
this->WriteString("<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;", 3);
@@ -1478,6 +1592,8 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
std::string shaderEntryPoint;
std::string shaderModel;
std::string shaderAdditionalFlags;
+ std::string outputHeaderFile;
+ std::string variableName;
std::string settingsGenerator;
std::string settingsLastGenOutput;
std::string sourceLink;
@@ -1485,7 +1601,7 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
std::string copyToOutDir;
std::string includeInVsix;
std::string ext = cmSystemTools::LowerCase(sf->GetExtension());
- if (csproj == this->ProjectType) {
+ if (this->ProjectType == csproj) {
// EVERY extra source file must have a <Link>, otherwise it might not
// be visible in Visual Studio at all. The path relative to current
// source- or binary-dir is used within the link, if the file is
@@ -1498,7 +1614,7 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
std::string srcDir = this->Makefile->GetCurrentSourceDirectory();
std::string binDir = this->Makefile->GetCurrentBinaryDirectory();
if (fullFileName.find(binDir) != std::string::npos) {
- sourceLink = "";
+ sourceLink.clear();
} else if (fullFileName.find(srcDir) != std::string::npos) {
sourceLink = fullFileName.substr(srcDir.length() + 1);
} else {
@@ -1527,6 +1643,16 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
shaderModel = sm;
toolHasSettings = true;
}
+ // Figure out which output header file to use if any
+ if (const char* ohf = sf->GetProperty("VS_SHADER_OUTPUT_HEADER_FILE")) {
+ outputHeaderFile = ohf;
+ toolHasSettings = true;
+ }
+ // Figure out which variable name to use if any
+ if (const char* vn = sf->GetProperty("VS_SHADER_VARIABLE_NAME")) {
+ variableName = vn;
+ toolHasSettings = true;
+ }
// Figure out if there's any additional flags to use
if (const char* saf = sf->GetProperty("VS_SHADER_FLAGS")) {
shaderAdditionalFlags = saf;
@@ -1564,6 +1690,10 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
toolHasSettings = true;
}
+ // Collect VS_CSHARP_* property values (if some are set)
+ std::map<std::string, std::string> sourceFileTags;
+ this->GetCSharpSourceProperties(sf, sourceFileTags);
+
if (this->NsightTegra) {
// Nsight Tegra needs specific file types to check up-to-dateness.
std::string name = cmSystemTools::LowerCase(sf->GetLocation().GetName());
@@ -1604,7 +1734,8 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
if (!deployContent.empty()) {
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(deployContent);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge =
+ ge.Parse(deployContent);
// Deployment location cannot be set on a configuration basis
if (!deployLocation.empty()) {
this->WriteString("<Link>", 3);
@@ -1647,6 +1778,28 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
(*this->BuildFileStream) << cmVS10EscapeXML(shaderModel)
<< "</ShaderModel>\n";
}
+ if (!outputHeaderFile.empty()) {
+ for (size_t i = 0; i != this->Configurations.size(); ++i) {
+ this->WriteString("<HeaderFileOutput Condition=\""
+ "'$(Configuration)|$(Platform)'=='",
+ 3);
+ (*this->BuildFileStream) << this->Configurations[i] << "|"
+ << this->Platform << "'\">"
+ << cmVS10EscapeXML(outputHeaderFile);
+ this->WriteString("</HeaderFileOutput>\n", 0);
+ }
+ }
+ if (!variableName.empty()) {
+ for (size_t i = 0; i != this->Configurations.size(); ++i) {
+ this->WriteString("<VariableName Condition=\""
+ "'$(Configuration)|$(Platform)'=='",
+ 3);
+ (*this->BuildFileStream) << this->Configurations[i] << "|"
+ << this->Platform << "'\">"
+ << cmVS10EscapeXML(variableName);
+ this->WriteString("</VariableName>\n", 0);
+ }
+ }
if (!shaderAdditionalFlags.empty()) {
this->WriteString("<AdditionalOptions>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(shaderAdditionalFlags)
@@ -1680,7 +1833,8 @@ void cmVisualStudio10TargetGenerator::WriteExtraSource(cmSourceFile const* sf)
(*this->BuildFileStream) << cmVS10EscapeXML(includeInVsix)
<< "</IncludeInVSIX>\n";
}
-
+ // write source file specific tags
+ this->WriteCSharpSourceProperties(sourceFileTags);
this->WriteString("</", 2);
(*this->BuildFileStream) << tool << ">\n";
} else {
@@ -1929,7 +2083,7 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
std::string configDefines = defines;
std::string defPropName = "COMPILE_DEFINITIONS_";
defPropName += configUpper;
- if (const char* ccdefs = sf.GetProperty(defPropName.c_str())) {
+ if (const char* ccdefs = sf.GetProperty(defPropName)) {
if (!configDefines.empty()) {
configDefines += ";";
}
@@ -1944,7 +2098,7 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
hasFlags = true;
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
- cmIDEFlagTable const* flagtable = CM_NULLPTR;
+ cmIDEFlagTable const* flagtable = nullptr;
const std::string& srclang = source->GetLanguage();
if (srclang == "C" || srclang == "CXX") {
flagtable = gg->GetClFlagTable();
@@ -1970,9 +2124,9 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
}
if (configDependentFlags) {
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge = ge.Parse(flags);
- std::string evaluatedFlags =
- cge->Evaluate(this->LocalGenerator, *config);
+ std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(flags);
+ std::string evaluatedFlags = cge->Evaluate(
+ this->LocalGenerator, *config, false, this->GeneratorTarget);
clOptions.Parse(evaluatedFlags.c_str());
} else {
clOptions.Parse(flags.c_str());
@@ -2002,48 +2156,23 @@ bool cmVisualStudio10TargetGenerator::OutputSourceSpecificFlags(
std::string xamlFileName = fileName.substr(0, fileName.find_last_of("."));
(*this->BuildFileStream) << xamlFileName << "</DependentUpon>\n";
}
- if (csproj == this->ProjectType) {
+ if (this->ProjectType == csproj) {
std::string f = source->GetFullPath();
typedef std::map<std::string, std::string> CsPropMap;
CsPropMap sourceFileTags;
// set <Link> tag if necessary
- if (!this->InSourceBuild) {
- const std::string stripFromPath =
- this->Makefile->GetCurrentSourceDirectory();
- if (f.find(stripFromPath) != std::string::npos) {
- std::string link = f.substr(stripFromPath.length() + 1);
- this->ConvertToWindowsSlash(link);
- sourceFileTags["Link"] = link;
- }
- }
- const cmPropertyMap& props = sf.GetProperties();
- for (cmPropertyMap::const_iterator p = props.begin(); p != props.end();
- ++p) {
- static const std::string propNamePrefix = "VS_CSHARP_";
- if (p->first.find(propNamePrefix.c_str()) == 0) {
- std::string tagName = p->first.substr(propNamePrefix.length());
- if (!tagName.empty()) {
- const std::string val = props.GetPropertyValue(p->first);
- if (!val.empty()) {
- sourceFileTags[tagName] = val;
- } else {
- sourceFileTags.erase(tagName);
- }
- }
- }
+ std::string link;
+ this->GetCSharpSourceLink(source, link);
+ if (!link.empty()) {
+ sourceFileTags["Link"] = link;
}
+ this->GetCSharpSourceProperties(&sf, sourceFileTags);
// write source file specific tags
if (!sourceFileTags.empty()) {
hasFlags = true;
(*this->BuildFileStream) << firstString;
firstString = "";
- for (CsPropMap::const_iterator i = sourceFileTags.begin();
- i != sourceFileTags.end(); ++i) {
- this->WriteString("<", 3);
- (*this->BuildFileStream)
- << i->first << ">" << cmVS10EscapeXML(i->second) << "</" << i->first
- << ">\n";
- }
+ this->WriteCSharpSourceProperties(sourceFileTags);
}
}
@@ -2069,7 +2198,7 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions()
if (ttype > cmStateEnums::GLOBAL_TARGET) {
return;
}
- if (csproj == this->ProjectType) {
+ if (this->ProjectType == csproj) {
return;
}
@@ -2081,7 +2210,7 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions()
this->Configurations.begin();
config != this->Configurations.end(); ++config) {
if (ttype >= cmStateEnums::UTILITY) {
- this->WritePlatformConfigTag("IntDir", config->c_str(), 2);
+ this->WritePlatformConfigTag("IntDir", *config, 2);
*this->BuildFileStream
<< "$(Platform)\\$(Configuration)\\$(ProjectName)\\"
<< "</IntDir>\n";
@@ -2098,30 +2227,30 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions()
targetNameFull = this->GeneratorTarget->GetName();
targetNameFull += ".lib";
} else {
- outDir = this->GeneratorTarget->GetDirectory(config->c_str()) + "/";
- targetNameFull = this->GeneratorTarget->GetFullName(config->c_str());
+ outDir = this->GeneratorTarget->GetDirectory(*config) + "/";
+ targetNameFull = this->GeneratorTarget->GetFullName(*config);
}
this->ConvertToWindowsSlash(intermediateDir);
this->ConvertToWindowsSlash(outDir);
- this->WritePlatformConfigTag("OutDir", config->c_str(), 2);
+ this->WritePlatformConfigTag("OutDir", *config, 2);
*this->BuildFileStream << cmVS10EscapeXML(outDir) << "</OutDir>\n";
- this->WritePlatformConfigTag("IntDir", config->c_str(), 2);
+ this->WritePlatformConfigTag("IntDir", *config, 2);
*this->BuildFileStream << cmVS10EscapeXML(intermediateDir)
<< "</IntDir>\n";
if (const char* workingDir = this->GeneratorTarget->GetProperty(
"VS_DEBUGGER_WORKING_DIRECTORY")) {
- this->WritePlatformConfigTag("LocalDebuggerWorkingDirectory",
- config->c_str(), 2);
+ this->WritePlatformConfigTag("LocalDebuggerWorkingDirectory", *config,
+ 2);
*this->BuildFileStream << cmVS10EscapeXML(workingDir)
<< "</LocalDebuggerWorkingDirectory>\n";
}
std::string name =
cmSystemTools::GetFilenameWithoutLastExtension(targetNameFull);
- this->WritePlatformConfigTag("TargetName", config->c_str(), 2);
+ this->WritePlatformConfigTag("TargetName", *config, 2);
*this->BuildFileStream << cmVS10EscapeXML(name) << "</TargetName>\n";
std::string ext =
@@ -2131,7 +2260,7 @@ void cmVisualStudio10TargetGenerator::WritePathAndIncrementalLinkOptions()
// A single "." appears to be treated as an empty extension.
ext = ".";
}
- this->WritePlatformConfigTag("TargetExt", config->c_str(), 2);
+ this->WritePlatformConfigTag("TargetExt", *config, 2);
*this->BuildFileStream << cmVS10EscapeXML(ext) << "</TargetExt>\n";
this->OutputLinkIncremental(*config);
@@ -2146,7 +2275,7 @@ void cmVisualStudio10TargetGenerator::OutputLinkIncremental(
if (!this->MSTools) {
return;
}
- if (csproj == this->ProjectType) {
+ if (this->ProjectType == csproj) {
return;
}
// static libraries and things greater than modules do not need
@@ -2158,13 +2287,13 @@ void cmVisualStudio10TargetGenerator::OutputLinkIncremental(
Options& linkOptions = *(this->LinkOptions[configName]);
const char* incremental = linkOptions.GetFlag("LinkIncremental");
- this->WritePlatformConfigTag("LinkIncremental", configName.c_str(), 2);
+ this->WritePlatformConfigTag("LinkIncremental", configName, 2);
*this->BuildFileStream << (incremental ? incremental : "true")
<< "</LinkIncremental>\n";
linkOptions.RemoveFlag("LinkIncremental");
const char* manifest = linkOptions.GetFlag("GenerateManifest");
- this->WritePlatformConfigTag("GenerateManifest", configName.c_str(), 2);
+ this->WritePlatformConfigTag("GenerateManifest", configName, 2);
*this->BuildFileStream << (manifest ? manifest : "true")
<< "</GenerateManifest>\n";
linkOptions.RemoveFlag("GenerateManifest");
@@ -2175,7 +2304,7 @@ void cmVisualStudio10TargetGenerator::OutputLinkIncremental(
for (const char** f = flags; *f; ++f) {
const char* flag = *f;
if (const char* value = linkOptions.GetFlag(flag)) {
- this->WritePlatformConfigTag(flag, configName.c_str(), 2);
+ this->WritePlatformConfigTag(flag, configName, 2);
*this->BuildFileStream << value << "</" << flag << ">\n";
linkOptions.RemoveFlag(flag);
}
@@ -2203,23 +2332,23 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
- CM_AUTO_PTR<Options> pOptions;
+ std::unique_ptr<Options> pOptions;
switch (this->ProjectType) {
case vcxproj:
- pOptions = CM_AUTO_PTR<Options>(new Options(
- this->LocalGenerator, Options::Compiler, gg->GetClFlagTable()));
+ pOptions = cm::make_unique<Options>(
+ this->LocalGenerator, Options::Compiler, gg->GetClFlagTable());
break;
case csproj:
- pOptions = CM_AUTO_PTR<Options>(new Options(this->LocalGenerator,
- Options::CSharpCompiler,
- gg->GetCSharpFlagTable()));
+ pOptions =
+ cm::make_unique<Options>(this->LocalGenerator, Options::CSharpCompiler,
+ gg->GetCSharpFlagTable());
break;
}
Options& clOptions = *pOptions;
std::string flags;
const std::string& linkLanguage =
- this->GeneratorTarget->GetLinkerLanguage(configName.c_str());
+ this->GeneratorTarget->GetLinkerLanguage(configName);
if (linkLanguage.empty()) {
cmSystemTools::Error(
"CMake can not determine linker language for target: ",
@@ -2250,13 +2379,13 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
baseFlagVar += "_FLAGS";
flags =
this->GeneratorTarget->Target->GetMakefile()->GetRequiredDefinition(
- baseFlagVar.c_str());
+ baseFlagVar);
std::string flagVar =
baseFlagVar + std::string("_") + cmSystemTools::UpperCase(configName);
flags += " ";
flags +=
this->GeneratorTarget->Target->GetMakefile()->GetRequiredDefinition(
- flagVar.c_str());
+ flagVar);
this->LocalGenerator->AddCompileOptions(flags, this->GeneratorTarget,
langForClCompile, configName);
}
@@ -2275,7 +2404,7 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
std::string defineFlags =
this->GeneratorTarget->Target->GetMakefile()->GetDefineFlags();
if (this->MSTools) {
- if (vcxproj == this->ProjectType) {
+ if (this->ProjectType == vcxproj) {
clOptions.FixExceptionHandlingDefault();
clOptions.AddFlag("PrecompiledHeader", "NotUsing");
std::string asmLocation = configName + "/";
@@ -2287,12 +2416,12 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
std::vector<std::string> targetDefines;
switch (this->ProjectType) {
case vcxproj:
- this->GeneratorTarget->GetCompileDefinitions(targetDefines,
- configName.c_str(), "CXX");
+ this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
+ "CXX");
break;
case csproj:
- this->GeneratorTarget->GetCompileDefinitions(
- targetDefines, configName.c_str(), "CSharp");
+ this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
+ "CSharp");
break;
}
clOptions.AddDefines(targetDefines);
@@ -2332,7 +2461,7 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
}
}
- if (csproj != this->ProjectType && clOptions.IsManaged()) {
+ if (this->ProjectType != csproj && clOptions.IsManaged()) {
this->Managed = true;
std::string managedType = clOptions.GetFlag("CompileAsManaged");
if (managedType == "Safe") {
@@ -2340,6 +2469,12 @@ bool cmVisualStudio10TargetGenerator::ComputeClOptions(
clOptions.AddFlag("CallingConvention", "");
}
}
+ if (this->ProjectType == csproj) {
+ // /nowin32manifest overrides /win32manifest: parameter
+ if (clOptions.HasFlag("NoWin32Manifest")) {
+ clOptions.RemoveFlag("ApplicationManifest");
+ }
+ }
this->ClOptions[configName] = pOptions.release();
return true;
@@ -2371,8 +2506,7 @@ void cmVisualStudio10TargetGenerator::WriteClOptions(
}
if (this->MSTools) {
- cmsys::RegularExpression clangToolset(
- "(v[0-9]+_clang_.*|LLVM-vs[0-9]+.*)");
+ cmsys::RegularExpression clangToolset("v[0-9]+_clang_.*");
const char* toolset = this->GlobalGenerator->GetPlatformToolset();
if (toolset && clangToolset.find(toolset)) {
this->WriteString("<ObjectFileName>"
@@ -2392,8 +2526,7 @@ void cmVisualStudio10TargetGenerator::WriteClOptions(
}
// Specify the compiler program database file if configured.
- std::string pdb =
- this->GeneratorTarget->GetCompilePDBPath(configName.c_str());
+ std::string pdb = this->GeneratorTarget->GetCompilePDBPath(configName);
if (!pdb.empty()) {
this->ConvertToWindowsSlash(pdb);
this->WriteString("<ProgramDataBaseFileName>", 3);
@@ -2422,8 +2555,8 @@ bool cmVisualStudio10TargetGenerator::ComputeRcOptions(
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
- CM_AUTO_PTR<Options> pOptions(new Options(
- this->LocalGenerator, Options::ResourceCompiler, gg->GetRcFlagTable()));
+ auto pOptions = cm::make_unique<Options>(
+ this->LocalGenerator, Options::ResourceCompiler, gg->GetRcFlagTable());
Options& rcOptions = *pOptions;
std::string CONFIG = cmSystemTools::UpperCase(configName);
@@ -2483,8 +2616,8 @@ bool cmVisualStudio10TargetGenerator::ComputeCudaOptions(
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
- CM_AUTO_PTR<Options> pOptions(new Options(
- this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable()));
+ auto pOptions = cm::make_unique<Options>(
+ this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
Options& cudaOptions = *pOptions;
// Get compile flags for CUDA in this directory.
@@ -2515,6 +2648,13 @@ bool cmVisualStudio10TargetGenerator::ComputeCudaOptions(
cudaOptions.AddFlag("CompileOut", "$(IntDir)%(Filename).ptx");
}
+ // CUDA automatically passes the proper '--machine' flag to nvcc
+ // for the current architecture, but does not reflect this default
+ // in the user-visible IDE settings. Set it explicitly.
+ if (this->Platform == "x64") {
+ cudaOptions.AddFlag("TargetMachinePlatform", "64");
+ }
+
// Convert the host compiler options to the toolset's abstractions
// using a secondary flag table.
cudaOptions.ClearTables();
@@ -2535,8 +2675,8 @@ bool cmVisualStudio10TargetGenerator::ComputeCudaOptions(
cudaOptions.FixCudaCodeGeneration();
std::vector<std::string> targetDefines;
- this->GeneratorTarget->GetCompileDefinitions(targetDefines,
- configName.c_str(), "CUDA");
+ this->GeneratorTarget->GetCompileDefinitions(targetDefines, configName,
+ "CUDA");
cudaOptions.AddDefines(targetDefines);
// Add a definition for the configuration name.
@@ -2591,8 +2731,8 @@ bool cmVisualStudio10TargetGenerator::ComputeCudaLinkOptions(
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
- CM_AUTO_PTR<Options> pOptions(new Options(
- this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable()));
+ auto pOptions = cm::make_unique<Options>(
+ this->LocalGenerator, Options::CudaCompiler, gg->GetCudaFlagTable());
Options& cudaLinkOptions = *pOptions;
// Determine if we need to do a device link
@@ -2662,8 +2802,8 @@ bool cmVisualStudio10TargetGenerator::ComputeMasmOptions(
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
- CM_AUTO_PTR<Options> pOptions(new Options(
- this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable()));
+ auto pOptions = cm::make_unique<Options>(
+ this->LocalGenerator, Options::MasmCompiler, gg->GetMasmFlagTable());
Options& masmOptions = *pOptions;
std::string CONFIG = cmSystemTools::UpperCase(configName);
@@ -2720,8 +2860,8 @@ bool cmVisualStudio10TargetGenerator::ComputeNasmOptions(
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
- CM_AUTO_PTR<Options> pOptions(new Options(
- this->LocalGenerator, Options::NasmCompiler, gg->GetNasmFlagTable()));
+ auto pOptions = cm::make_unique<Options>(
+ this->LocalGenerator, Options::NasmCompiler, gg->GetNasmFlagTable());
Options& nasmOptions = *pOptions;
std::string CONFIG = cmSystemTools::UpperCase(configName);
@@ -2882,7 +3022,7 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
if (const char* nativeLibDirectoriesExpression =
this->GeneratorTarget->GetProperty("ANDROID_NATIVE_LIB_DIRECTORIES")) {
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
+ std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(nativeLibDirectoriesExpression);
std::string nativeLibDirs =
cge->Evaluate(this->LocalGenerator, configName);
@@ -2895,7 +3035,7 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
this->GeneratorTarget->GetProperty(
"ANDROID_NATIVE_LIB_DEPENDENCIES")) {
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
+ std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(nativeLibDependenciesExpression);
std::string nativeLibDeps =
cge->Evaluate(this->LocalGenerator, configName);
@@ -2914,7 +3054,7 @@ void cmVisualStudio10TargetGenerator::WriteAntBuildOptions(
if (const char* jarDirectoriesExpression =
this->GeneratorTarget->GetProperty("ANDROID_JAR_DIRECTORIES")) {
cmGeneratorExpression ge;
- CM_AUTO_PTR<cmCompiledGeneratorExpression> cge =
+ std::unique_ptr<cmCompiledGeneratorExpression> cge =
ge.Parse(jarDirectoriesExpression);
std::string jarDirectories =
cge->Evaluate(this->LocalGenerator, configName);
@@ -2976,8 +3116,9 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
{
cmGlobalVisualStudio10Generator* gg =
static_cast<cmGlobalVisualStudio10Generator*>(this->GlobalGenerator);
- CM_AUTO_PTR<Options> pOptions(new Options(
- this->LocalGenerator, Options::Linker, gg->GetLinkFlagTable(), 0, this));
+ auto pOptions =
+ cm::make_unique<Options>(this->LocalGenerator, Options::Linker,
+ gg->GetLinkFlagTable(), nullptr, this);
Options& linkOptions = *pOptions;
cmGeneratorTarget::LinkClosure const* linkClosure =
@@ -3006,11 +3147,11 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
linkFlagVarBase += "_LINKER_FLAGS";
flags += " ";
flags += this->GeneratorTarget->Target->GetMakefile()->GetRequiredDefinition(
- linkFlagVarBase.c_str());
+ linkFlagVarBase);
std::string linkFlagVar = linkFlagVarBase + "_" + CONFIG;
flags += " ";
flags += this->GeneratorTarget->Target->GetMakefile()->GetRequiredDefinition(
- linkFlagVar.c_str());
+ linkFlagVar);
const char* targetLinkFlags =
this->GeneratorTarget->GetProperty("LINK_FLAGS");
if (targetLinkFlags) {
@@ -3020,13 +3161,13 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
std::string flagsProp = "LINK_FLAGS_";
flagsProp += CONFIG;
if (const char* flagsConfig =
- this->GeneratorTarget->GetProperty(flagsProp.c_str())) {
+ this->GeneratorTarget->GetProperty(flagsProp)) {
flags += " ";
flags += flagsConfig;
}
cmComputeLinkInformation* pcli =
- this->GeneratorTarget->GetLinkInformation(config.c_str());
+ this->GeneratorTarget->GetLinkInformation(config);
if (!pcli) {
cmSystemTools::Error(
"CMake can not compute cmComputeLinkInformation for target: ",
@@ -3054,8 +3195,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
std::string standardLibsVar = "CMAKE_";
standardLibsVar += linkLanguage;
standardLibsVar += "_STANDARD_LIBRARIES";
- std::string const libs =
- this->Makefile->GetSafeDefinition(standardLibsVar.c_str());
+ std::string const libs = this->Makefile->GetSafeDefinition(standardLibsVar);
cmSystemTools::ParseWindowsCommandLine(libs.c_str(), libVec);
linkOptions.AddFlag("AdditionalDependencies", libVec);
@@ -3083,18 +3223,15 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
std::string targetNameImport;
std::string targetNamePDB;
if (this->GeneratorTarget->GetType() == cmStateEnums::EXECUTABLE) {
- this->GeneratorTarget->GetExecutableNames(targetName, targetNameFull,
- targetNameImport, targetNamePDB,
- config.c_str());
+ this->GeneratorTarget->GetExecutableNames(
+ targetName, targetNameFull, targetNameImport, targetNamePDB, config);
} else {
this->GeneratorTarget->GetLibraryNames(targetName, targetNameSO,
targetNameFull, targetNameImport,
- targetNamePDB, config.c_str());
+ targetNamePDB, config);
}
if (this->MSTools) {
- linkOptions.AddFlag("Version", "");
-
if (this->GeneratorTarget->GetPropertyAsBool("WIN32_EXECUTABLE")) {
if (this->GlobalGenerator->TargetsWindowsCE()) {
linkOptions.AddFlag("SubSystem", "WindowsCE");
@@ -3130,11 +3267,11 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
linkOptions.AddFlag("GenerateDebugInformation", "false");
- std::string pdb = this->GeneratorTarget->GetPDBDirectory(config.c_str());
+ std::string pdb = this->GeneratorTarget->GetPDBDirectory(config);
pdb += "/";
pdb += targetNamePDB;
std::string imLib = this->GeneratorTarget->GetDirectory(
- config.c_str(), cmStateEnums::ImportLibraryArtifact);
+ config, cmStateEnums::ImportLibraryArtifact);
imLib += "/";
imLib += targetNameImport;
@@ -3164,6 +3301,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLinkOptions(
}
linkOptions.Parse(flags.c_str());
+ linkOptions.FixManifestUACFlags();
if (this->MSTools) {
cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
@@ -3209,7 +3347,7 @@ bool cmVisualStudio10TargetGenerator::ComputeLibOptions(
std::string const& config)
{
cmComputeLinkInformation* pcli =
- this->GeneratorTarget->GetLinkInformation(config.c_str());
+ this->GeneratorTarget->GetLinkInformation(config);
if (!pcli) {
cmSystemTools::Error(
"CMake can not compute cmComputeLinkInformation for target: ",
@@ -3224,8 +3362,8 @@ bool cmVisualStudio10TargetGenerator::ComputeLibOptions(
this->LocalGenerator->GetCurrentBinaryDirectory();
for (ItemVector::const_iterator l = libs.begin(); l != libs.end(); ++l) {
if (l->IsPath && cmVS10IsTargetsFile(l->Value)) {
- std::string path = this->LocalGenerator->ConvertToRelativePath(
- currentBinDir, l->Value.c_str());
+ std::string path =
+ this->LocalGenerator->ConvertToRelativePath(currentBinDir, l->Value);
this->ConvertToWindowsSlash(path);
this->AddTargetsFileAndConfigPair(path, config);
}
@@ -3241,7 +3379,7 @@ void cmVisualStudio10TargetGenerator::WriteLinkOptions(
this->GeneratorTarget->GetType() > cmStateEnums::MODULE_LIBRARY) {
return;
}
- if (csproj == this->ProjectType) {
+ if (this->ProjectType == csproj) {
return;
}
Options& linkOptions = *(this->LinkOptions[config]);
@@ -3270,8 +3408,8 @@ void cmVisualStudio10TargetGenerator::AddLibraries(
this->LocalGenerator->GetCurrentBinaryDirectory();
for (ItemVector::const_iterator l = libs.begin(); l != libs.end(); ++l) {
if (l->IsPath) {
- std::string path = this->LocalGenerator->ConvertToRelativePath(
- currentBinDir, l->Value.c_str());
+ std::string path =
+ this->LocalGenerator->ConvertToRelativePath(currentBinDir, l->Value);
this->ConvertToWindowsSlash(path);
if (cmVS10IsTargetsFile(l->Value)) {
vsTargetVec.push_back(path);
@@ -3311,7 +3449,7 @@ void cmVisualStudio10TargetGenerator::WriteMidlOptions(
if (!this->MSTools) {
return;
}
- if (csproj == this->ProjectType) {
+ if (this->ProjectType == csproj) {
return;
}
@@ -3353,17 +3491,20 @@ void cmVisualStudio10TargetGenerator::WriteMidlOptions(
void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups()
{
+ if (this->ProjectType == csproj) {
+ return;
+ }
for (std::vector<std::string>::const_iterator i =
this->Configurations.begin();
i != this->Configurations.end(); ++i) {
std::vector<std::string> includes;
this->LocalGenerator->GetIncludeDirectories(
- includes, this->GeneratorTarget, "C", i->c_str());
+ includes, this->GeneratorTarget, "C", *i);
for (std::vector<std::string>::iterator ii = includes.begin();
ii != includes.end(); ++ii) {
this->ConvertToWindowsSlash(*ii);
}
- this->WritePlatformConfigTag("ItemDefinitionGroup", i->c_str(), 1);
+ this->WritePlatformConfigTag("ItemDefinitionGroup", *i, 1);
*this->BuildFileStream << "\n";
// output cl compile flags <ClCompile></ClCompile>
if (this->GeneratorTarget->GetType() <= cmStateEnums::OBJECT_LIBRARY) {
@@ -3377,7 +3518,7 @@ void cmVisualStudio10TargetGenerator::WriteItemDefinitionGroups()
// output midl flags <Midl></Midl>
this->WriteMidlOptions(*i, includes);
// write events
- if (csproj != this->ProjectType) {
+ if (this->ProjectType != csproj) {
this->WriteEvents(*i);
}
// output link flags <Link></Link>
@@ -3436,24 +3577,30 @@ void cmVisualStudio10TargetGenerator::WriteEvent(
for (std::vector<cmCustomCommand>::const_iterator i = commands.begin();
i != commands.end(); ++i) {
cmCustomCommandGenerator ccg(*i, configName, this->LocalGenerator);
- comment += pre;
- comment += lg->ConstructComment(ccg);
- script += pre;
- pre = "\n";
- script += cmVS10EscapeXML(lg->ConstructScript(ccg));
+ if (!ccg.HasOnlyEmptyCommandLines()) {
+ comment += pre;
+ comment += lg->ConstructComment(ccg);
+ script += pre;
+ pre = "\n";
+ script += cmVS10EscapeXML(lg->ConstructScript(ccg));
+ }
}
comment = cmVS10EscapeComment(comment);
- if (csproj != this->ProjectType) {
+ if (this->ProjectType != csproj) {
this->WriteString("<Message>", 3);
(*this->BuildFileStream) << cmVS10EscapeXML(comment) << "</Message>\n";
this->WriteString("<Command>", 3);
} else {
- if (!comment.empty()) {
+ std::string strippedComment = comment;
+ strippedComment.erase(
+ std::remove(strippedComment.begin(), strippedComment.end(), '\t'),
+ strippedComment.end());
+ if (!comment.empty() && !strippedComment.empty()) {
(*this->BuildFileStream) << "echo " << cmVS10EscapeXML(comment) << "\n";
}
}
(*this->BuildFileStream) << script;
- if (csproj != this->ProjectType) {
+ if (this->ProjectType != csproj) {
(*this->BuildFileStream) << "</Command>";
}
(*this->BuildFileStream) << "\n";
@@ -3497,11 +3644,12 @@ void cmVisualStudio10TargetGenerator::WriteProjectReferences()
this->ConvertToWindowsSlash(path);
(*this->BuildFileStream) << cmVS10EscapeXML(path) << "\">\n";
this->WriteString("<Project>", 3);
- (*this->BuildFileStream)
- << "{" << this->GlobalGenerator->GetGUID(name.c_str()) << "}";
+ (*this->BuildFileStream) << "{" << this->GlobalGenerator->GetGUID(name)
+ << "}";
(*this->BuildFileStream) << "</Project>\n";
this->WriteString("<Name>", 3);
(*this->BuildFileStream) << name << "</Name>\n";
+ this->WriteDotNetReferenceCustomTags(name);
if (csproj == this->ProjectType) {
if (!static_cast<cmGlobalVisualStudioGenerator*>(this->GlobalGenerator)
->TargetCanBeReferenced(dt)) {
@@ -3600,10 +3748,10 @@ void cmVisualStudio10TargetGenerator::WriteSDKReferences()
this->WriteSingleSDKReference("WindowsIoT", iotExtensionsVersion);
}
}
+ }
- if (hasWrittenItemGroup) {
- this->WriteString("</ItemGroup>\n", 1);
- }
+ if (hasWrittenItemGroup) {
+ this->WriteString("</ItemGroup>\n", 1);
}
}
@@ -3777,7 +3925,7 @@ void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings()
this->WriteString("<XapOutputs>true</XapOutputs>\n", 2);
this->WriteString("<XapFilename>", 2);
(*this->BuildFileStream)
- << cmVS10EscapeXML(this->Name.c_str())
+ << cmVS10EscapeXML(this->Name)
<< "_$(Configuration)_$(Platform).xap</XapFilename>\n";
}
}
@@ -3786,6 +3934,10 @@ void cmVisualStudio10TargetGenerator::WriteApplicationTypeSettings()
this->WriteString("<AppContainerApplication>true"
"</AppContainerApplication>\n",
2);
+ } else if (this->Platform == "ARM64") {
+ this->WriteString("<WindowsSDKDesktopARM64Support>true"
+ "</WindowsSDKDesktopARM64Support>\n",
+ 2);
} else if (this->Platform == "ARM") {
this->WriteString("<WindowsSDKDesktopARMSupport>true"
"</WindowsSDKDesktopARMSupport>\n",
@@ -4296,6 +4448,59 @@ bool cmVisualStudio10TargetGenerator::ForceOld(const std::string& source) const
return true;
}
+void cmVisualStudio10TargetGenerator::GetCSharpSourceProperties(
+ cmSourceFile const* sf, std::map<std::string, std::string>& tags)
+{
+ if (this->ProjectType == csproj) {
+ const cmPropertyMap& props = sf->GetProperties();
+ for (cmPropertyMap::const_iterator p = props.begin(); p != props.end();
+ ++p) {
+ static const std::string propNamePrefix = "VS_CSHARP_";
+ if (p->first.find(propNamePrefix) == 0) {
+ std::string tagName = p->first.substr(propNamePrefix.length());
+ if (!tagName.empty()) {
+ const std::string val = props.GetPropertyValue(p->first);
+ if (!val.empty()) {
+ tags[tagName] = val;
+ } else {
+ tags.erase(tagName);
+ }
+ }
+ }
+ }
+ }
+}
+
+void cmVisualStudio10TargetGenerator::WriteCSharpSourceProperties(
+ const std::map<std::string, std::string>& tags)
+{
+ if (!tags.empty()) {
+ for (std::map<std::string, std::string>::const_iterator i = tags.begin();
+ i != tags.end(); ++i) {
+ this->WriteString("<", 3);
+ (*this->BuildFileStream) << i->first << ">" << cmVS10EscapeXML(i->second)
+ << "</" << i->first << ">\n";
+ }
+ }
+}
+
+void cmVisualStudio10TargetGenerator::GetCSharpSourceLink(
+ cmSourceFile const* sf, std::string& link)
+{
+ std::string f = sf->GetFullPath();
+ if (!this->InSourceBuild) {
+ const std::string stripFromPath =
+ this->Makefile->GetCurrentSourceDirectory();
+ if (f.find(stripFromPath) != std::string::npos) {
+ link = f.substr(stripFromPath.length() + 1);
+ if (const char* l = sf->GetProperty("VS_CSHARP_Link")) {
+ link = l;
+ }
+ this->ConvertToWindowsSlash(link);
+ }
+ }
+}
+
std::string cmVisualStudio10TargetGenerator::GetCMakeFilePath(
const char* relativeFilePath) const
{
diff --git a/Source/cmVisualStudio10TargetGenerator.h b/Source/cmVisualStudio10TargetGenerator.h
index 61066158c..fb24f1ac5 100644
--- a/Source/cmVisualStudio10TargetGenerator.h
+++ b/Source/cmVisualStudio10TargetGenerator.h
@@ -3,7 +3,7 @@
#ifndef cmVisualStudioTargetGenerator_h
#define cmVisualStudioTargetGenerator_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <map>
@@ -66,6 +66,7 @@ private:
void WriteAllSources();
void WriteDotNetReferences();
void WriteDotNetReference(std::string const& ref, std::string const& hint);
+ void WriteDotNetReferenceCustomTags(std::string const& ref);
void WriteEmbeddedResourceGroup();
void WriteWinRTReferences();
void WriteWinRTPackageCertificateKeyFile();
@@ -126,6 +127,16 @@ private:
void OutputLinkIncremental(std::string const& configName);
void WriteCustomRule(cmSourceFile const* source,
cmCustomCommand const& command);
+ void WriteCustomRuleCpp(std::string const& config, std::string const& script,
+ std::string const& inputs,
+ std::string const& outputs,
+ std::string const& comment);
+ void WriteCustomRuleCSharp(std::string const& config,
+ std::string const& commandName,
+ std::string const& script,
+ std::string const& inputs,
+ std::string const& outputs,
+ std::string const& comment);
void WriteCustomCommands();
void WriteCustomCommand(cmSourceFile const* sf);
void WriteGroups();
@@ -153,6 +164,12 @@ private:
bool ForceOld(const std::string& source) const;
+ void GetCSharpSourceProperties(cmSourceFile const* sf,
+ std::map<std::string, std::string>& tags);
+ void WriteCSharpSourceProperties(
+ const std::map<std::string, std::string>& tags);
+ void GetCSharpSourceLink(cmSourceFile const* sf, std::string& link);
+
private:
typedef cmVisualStudioGeneratorOptions Options;
typedef std::map<std::string, Options*> OptionsMap;
@@ -187,6 +204,7 @@ private:
cmGeneratedFileStream* BuildFileStream;
cmLocalVisualStudio7Generator* LocalGenerator;
std::set<cmSourceFile const*> SourcesVisited;
+ std::set<std::string> CSharpCustomCommandNames;
bool IsMissingFiles;
std::vector<std::string> AddedFiles;
std::string DefaultArtifactDir;
diff --git a/Source/cmVisualStudio10ToolsetOptions.h b/Source/cmVisualStudio10ToolsetOptions.h
index 4233337ba..c736a49f5 100644
--- a/Source/cmVisualStudio10ToolsetOptions.h
+++ b/Source/cmVisualStudio10ToolsetOptions.h
@@ -3,7 +3,7 @@
#ifndef cmVisualStudio10ToolsetOptions_h
#define cmVisualStudio10ToolsetOptions_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
diff --git a/Source/cmVisualStudioGeneratorOptions.cxx b/Source/cmVisualStudioGeneratorOptions.cxx
index 1f808c8b2..b1686bec1 100644
--- a/Source/cmVisualStudioGeneratorOptions.cxx
+++ b/Source/cmVisualStudioGeneratorOptions.cxx
@@ -89,7 +89,7 @@ void cmVisualStudioGeneratorOptions::AddTable(cmVS7FlagTable const* table)
void cmVisualStudioGeneratorOptions::ClearTables()
{
for (int i = 0; i < FlagTableCount; ++i) {
- this->FlagTable[i] = CM_NULLPTR;
+ this->FlagTable[i] = nullptr;
}
}
@@ -256,6 +256,74 @@ void cmVisualStudioGeneratorOptions::FixCudaCodeGeneration()
}
}
+void cmVisualStudioGeneratorOptions::FixManifestUACFlags()
+{
+ static const char* ENABLE_UAC = "EnableUAC";
+ if (!HasFlag(ENABLE_UAC)) {
+ return;
+ }
+
+ const std::string uacFlag = GetFlag(ENABLE_UAC);
+ std::vector<std::string> subOptions;
+ cmsys::SystemTools::Split(uacFlag, subOptions, ' ');
+ if (subOptions.empty()) {
+ AddFlag(ENABLE_UAC, "true");
+ return;
+ }
+
+ if (subOptions.size() == 1 && subOptions[0] == "NO") {
+ AddFlag(ENABLE_UAC, "false");
+ return;
+ }
+
+ std::map<std::string, std::string> uacMap;
+ uacMap["level"] = "UACExecutionLevel";
+ uacMap["uiAccess"] = "UACUIAccess";
+
+ std::map<std::string, std::string> uacExecuteLevelMap;
+ uacExecuteLevelMap["asInvoker"] = "AsInvoker";
+ uacExecuteLevelMap["highestAvailable"] = "HighestAvailable";
+ uacExecuteLevelMap["requireAdministrator"] = "RequireAdministrator";
+
+ for (auto const& subopt : subOptions) {
+ std::vector<std::string> keyValue;
+ cmsys::SystemTools::Split(subopt, keyValue, '=');
+ if (keyValue.size() != 2 || (uacMap.find(keyValue[0]) == uacMap.end())) {
+ // ignore none key=value option or unknown flags
+ continue;
+ }
+
+ if (keyValue[1].front() == '\'' && keyValue[1].back() == '\'') {
+ keyValue[1] =
+ keyValue[1].substr(1, std::max<int>(0, keyValue[1].size() - 2));
+ }
+
+ if (keyValue[0] == "level") {
+ if (uacExecuteLevelMap.find(keyValue[1]) == uacExecuteLevelMap.end()) {
+ // unknown level value
+ continue;
+ }
+
+ AddFlag(uacMap[keyValue[0]].c_str(),
+ uacExecuteLevelMap[keyValue[1]].c_str());
+ continue;
+ }
+
+ if (keyValue[0] == "uiAccess") {
+ if (keyValue[1] != "true" && keyValue[1] != "false") {
+ // unknown uiAccess value
+ continue;
+ }
+ AddFlag(uacMap[keyValue[0]].c_str(), keyValue[1].c_str());
+ continue;
+ }
+
+ // unknwon sub option
+ }
+
+ AddFlag(ENABLE_UAC, "true");
+}
+
void cmVisualStudioGeneratorOptions::Parse(const char* flags)
{
// Parse the input string as a windows command line since the string
diff --git a/Source/cmVisualStudioGeneratorOptions.h b/Source/cmVisualStudioGeneratorOptions.h
index 44d271908..7c08a2c30 100644
--- a/Source/cmVisualStudioGeneratorOptions.h
+++ b/Source/cmVisualStudioGeneratorOptions.h
@@ -3,7 +3,7 @@
#ifndef cmVisualStudioGeneratorOptions_h
#define cmVisualStudioGeneratorOptions_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <iosfwd>
#include <string>
@@ -77,6 +77,8 @@ public:
void FixCudaCodeGeneration();
+ void FixManifestUACFlags();
+
bool IsDebug() const;
bool IsWinRt() const;
bool IsManaged() const;
diff --git a/Source/cmVisualStudioSlnData.h b/Source/cmVisualStudioSlnData.h
index e12047fb5..9c1dffc05 100644
--- a/Source/cmVisualStudioSlnData.h
+++ b/Source/cmVisualStudioSlnData.h
@@ -3,7 +3,7 @@
#ifndef cmVisualStudioSlnData_h
#define cmVisualStudioSlnData_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <map>
#include <string>
diff --git a/Source/cmVisualStudioSlnParser.cxx b/Source/cmVisualStudioSlnParser.cxx
index 1a32abacf..a9acb3fce 100644
--- a/Source/cmVisualStudioSlnParser.cxx
+++ b/Source/cmVisualStudioSlnParser.cxx
@@ -329,7 +329,7 @@ bool cmVisualStudioSlnParser::State::Process(
case FileStateIgnore:
if (line.GetTag() == this->EndIgnoreTag) {
this->Stack.pop();
- this->EndIgnoreTag = "";
+ this->EndIgnoreTag.clear();
}
break;
default:
diff --git a/Source/cmVisualStudioSlnParser.h b/Source/cmVisualStudioSlnParser.h
index d51732407..d6345a84d 100644
--- a/Source/cmVisualStudioSlnParser.h
+++ b/Source/cmVisualStudioSlnParser.h
@@ -3,7 +3,7 @@
#ifndef cmVisualStudioSlnParser_h
#define cmVisualStudioSlnParser_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <bitset>
#include <iosfwd>
diff --git a/Source/cmVisualStudioWCEPlatformParser.cxx b/Source/cmVisualStudioWCEPlatformParser.cxx
index fc64d0fb0..3b113aadb 100644
--- a/Source/cmVisualStudioWCEPlatformParser.cxx
+++ b/Source/cmVisualStudioWCEPlatformParser.cxx
@@ -56,12 +56,12 @@ void cmVisualStudioWCEPlatformParser::StartElement(const std::string& name,
return;
}
- this->CharacterData = "";
+ this->CharacterData.clear();
if (name == "PlatformData") {
- this->PlatformName = "";
- this->OSMajorVersion = "";
- this->OSMinorVersion = "";
+ this->PlatformName.clear();
+ this->OSMajorVersion.clear();
+ this->OSMinorVersion.clear();
this->Macros.clear();
}
diff --git a/Source/cmVisualStudioWCEPlatformParser.h b/Source/cmVisualStudioWCEPlatformParser.h
index 75c3d1a39..c19691aa2 100644
--- a/Source/cmVisualStudioWCEPlatformParser.h
+++ b/Source/cmVisualStudioWCEPlatformParser.h
@@ -3,7 +3,7 @@
#ifndef cmVisualStudioWCEPlatformParser_h
#define cmVisualStudioWCEPlatformParser_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <map>
#include <stddef.h>
diff --git a/Source/cmWhileCommand.cxx b/Source/cmWhileCommand.cxx
index 24d7bf1bf..a08003450 100644
--- a/Source/cmWhileCommand.cxx
+++ b/Source/cmWhileCommand.cxx
@@ -7,9 +7,10 @@
#include "cmExpandedCommandArgument.h"
#include "cmMakefile.h"
#include "cmSystemTools.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
+#include <memory> // IWYU pragma: keep
+
cmWhileFunctionBlocker::cmWhileFunctionBlocker(cmMakefile* mf)
: Makefile(mf)
, Depth(0)
@@ -34,7 +35,8 @@ bool cmWhileFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
// if this is the endwhile for this while loop then execute
if (!this->Depth) {
// Remove the function blocker for this scope or bail.
- CM_AUTO_PTR<cmFunctionBlocker> fb(mf.RemoveFunctionBlocker(this, lff));
+ std::unique_ptr<cmFunctionBlocker> fb(
+ mf.RemoveFunctionBlocker(this, lff));
if (!fb.get()) {
return false;
}
@@ -60,11 +62,10 @@ bool cmWhileFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
while (isTrue) {
if (!errorString.empty()) {
std::string err = "had incorrect arguments: ";
- unsigned int i;
- for (i = 0; i < this->Args.size(); ++i) {
- err += (this->Args[i].Delim ? "\"" : "");
- err += this->Args[i].Value;
- err += (this->Args[i].Delim ? "\"" : "");
+ for (cmListFileArgument const& arg : this->Args) {
+ err += (arg.Delim ? "\"" : "");
+ err += arg.Value;
+ err += (arg.Delim ? "\"" : "");
err += " ";
}
err += "(";
@@ -78,9 +79,9 @@ bool cmWhileFunctionBlocker::IsFunctionBlocked(const cmListFileFunction& lff,
}
// Invoke all the functions that were collected in the block.
- for (unsigned int c = 0; c < this->Functions.size(); ++c) {
+ for (cmListFileFunction const& fn : this->Functions) {
cmExecutionStatus status;
- mf.ExecuteCommand(this->Functions[c], status);
+ mf.ExecuteCommand(fn, status);
if (status.GetReturnInvoked()) {
inStatus.SetReturnInvoked();
return true;
diff --git a/Source/cmWhileCommand.h b/Source/cmWhileCommand.h
index a95e4c30c..6f6d40549 100644
--- a/Source/cmWhileCommand.h
+++ b/Source/cmWhileCommand.h
@@ -3,7 +3,7 @@
#ifndef cmWhileCommand_h
#define cmWhileCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -19,10 +19,10 @@ class cmWhileFunctionBlocker : public cmFunctionBlocker
{
public:
cmWhileFunctionBlocker(cmMakefile* mf);
- ~cmWhileFunctionBlocker() CM_OVERRIDE;
+ ~cmWhileFunctionBlocker() override;
bool IsFunctionBlocked(const cmListFileFunction& lff, cmMakefile& mf,
- cmExecutionStatus&) CM_OVERRIDE;
- bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) CM_OVERRIDE;
+ cmExecutionStatus&) override;
+ bool ShouldRemove(const cmListFileFunction& lff, cmMakefile& mf) override;
std::vector<cmListFileArgument> Args;
std::vector<cmListFileFunction> Functions;
@@ -39,21 +39,21 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmWhileCommand; }
+ cmCommand* Clone() override { return new cmWhileCommand; }
/**
* This overrides the default InvokeInitialPass implementation.
* It records the arguments before expansion.
*/
bool InvokeInitialPass(const std::vector<cmListFileArgument>& args,
- cmExecutionStatus&) CM_OVERRIDE;
+ cmExecutionStatus&) override;
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const&,
- cmExecutionStatus&) CM_OVERRIDE
+ cmExecutionStatus&) override
{
return false;
}
diff --git a/Source/cmWriteFileCommand.h b/Source/cmWriteFileCommand.h
index 19922cdf3..9028f84aa 100644
--- a/Source/cmWriteFileCommand.h
+++ b/Source/cmWriteFileCommand.h
@@ -3,7 +3,7 @@
#ifndef cmWriteFileCommand_h
#define cmWriteFileCommand_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <string>
#include <vector>
@@ -22,14 +22,14 @@ public:
/**
* This is a virtual constructor for the command.
*/
- cmCommand* Clone() CM_OVERRIDE { return new cmWriteFileCommand; }
+ cmCommand* Clone() override { return new cmWriteFileCommand; }
/**
* This is called when the command is first encountered in
* the CMakeLists.txt file.
*/
bool InitialPass(std::vector<std::string> const& args,
- cmExecutionStatus& status) CM_OVERRIDE;
+ cmExecutionStatus& status) override;
};
#endif
diff --git a/Source/cmXCode21Object.cxx b/Source/cmXCode21Object.cxx
index 719e62765..a9bb2ef54 100644
--- a/Source/cmXCode21Object.cxx
+++ b/Source/cmXCode21Object.cxx
@@ -34,9 +34,7 @@ void cmXCode21Object::PrintList(std::vector<cmXCodeObject*> const& v,
std::ostream& out, PBXType t)
{
bool hasOne = false;
- for (std::vector<cmXCodeObject*>::const_iterator i = v.begin(); i != v.end();
- ++i) {
- cmXCodeObject* obj = *i;
+ for (auto obj : v) {
if (obj->GetType() == OBJECT && obj->GetIsA() == t) {
hasOne = true;
break;
@@ -46,9 +44,7 @@ void cmXCode21Object::PrintList(std::vector<cmXCodeObject*> const& v,
return;
}
out << "\n/* Begin " << PBXTypeNames[t] << " section */\n";
- for (std::vector<cmXCodeObject*>::const_iterator i = v.begin(); i != v.end();
- ++i) {
- cmXCodeObject* obj = *i;
+ for (auto obj : v) {
if (obj->GetType() == OBJECT && obj->GetIsA() == t) {
obj->Print(out);
}
diff --git a/Source/cmXCode21Object.h b/Source/cmXCode21Object.h
index bcd8d93e1..8e4b80fc1 100644
--- a/Source/cmXCode21Object.h
+++ b/Source/cmXCode21Object.h
@@ -14,7 +14,7 @@ class cmXCode21Object : public cmXCodeObject
{
public:
cmXCode21Object(PBXType ptype, Type type);
- virtual void PrintComment(std::ostream&);
+ void PrintComment(std::ostream&) override;
static void PrintList(std::vector<cmXCodeObject*> const&, std::ostream& out,
PBXType t);
static void PrintList(std::vector<cmXCodeObject*> const&, std::ostream& out);
diff --git a/Source/cmXCodeObject.cxx b/Source/cmXCodeObject.cxx
index 0def8c321..e54f1f356 100644
--- a/Source/cmXCodeObject.cxx
+++ b/Source/cmXCodeObject.cxx
@@ -42,8 +42,8 @@ cmXCodeObject::~cmXCodeObject()
cmXCodeObject::cmXCodeObject(PBXType ptype, Type type)
{
this->Version = 15;
- this->Target = 0;
- this->Object = 0;
+ this->Target = nullptr;
+ this->Object = nullptr;
this->IsA = ptype;
@@ -71,7 +71,7 @@ cmXCodeObject::cmXCodeObject(PBXType ptype, Type type)
this->TypeValue = type;
if (this->TypeValue == OBJECT) {
- this->AddAttribute("isa", 0);
+ this->AddAttribute("isa", nullptr);
}
}
@@ -86,7 +86,7 @@ bool cmXCodeObject::IsEmpty() const
return this->ObjectAttributes.empty();
case OBJECT_REF:
case OBJECT:
- return this->Object == 0;
+ return this->Object == nullptr;
}
return true; // unreachable, but quiets warnings
}
@@ -120,8 +120,9 @@ void cmXCodeObject::Print(std::ostream& out)
out << "isa = " << PBXTypeNames[this->IsA] << ";" << separator;
for (i = this->ObjectAttributes.begin(); i != this->ObjectAttributes.end();
++i) {
- if (i->first == "isa")
+ if (i->first == "isa") {
continue;
+ }
PrintAttribute(out, 3, separator, indentFactor, i->first, i->second, this);
}
@@ -129,9 +130,9 @@ void cmXCodeObject::Print(std::ostream& out)
out << "};\n";
}
-void cmXCodeObject::PrintAttribute(std::ostream& out, const int level,
- const std::string separator,
- const int factor, const std::string& name,
+void cmXCodeObject::PrintAttribute(std::ostream& out, int level,
+ const std::string& separator, int factor,
+ const std::string& name,
const cmXCodeObject* object,
const cmXCodeObject* parent)
{
@@ -203,9 +204,9 @@ void cmXCodeObject::PrintList(std::vector<cmXCodeObject*> const& objs,
{
cmXCodeObject::Indent(1, out);
out << "objects = {\n";
- for (unsigned int i = 0; i < objs.size(); ++i) {
- if (objs[i]->TypeValue == OBJECT) {
- objs[i]->Print(out);
+ for (auto obj : objs) {
+ if (obj->TypeValue == OBJECT) {
+ obj->Print(out);
}
}
cmXCodeObject::Indent(1, out);
diff --git a/Source/cmXCodeObject.h b/Source/cmXCodeObject.h
index b92e6e33e..b0f1d31af 100644
--- a/Source/cmXCodeObject.h
+++ b/Source/cmXCodeObject.h
@@ -94,8 +94,8 @@ public:
}
static void Indent(int level, std::ostream& out);
void Print(std::ostream& out);
- void PrintAttribute(std::ostream& out, const int level,
- const std::string separator, const int factor,
+ void PrintAttribute(std::ostream& out, int level,
+ const std::string& separator, int factor,
const std::string& name, const cmXCodeObject* object,
const cmXCodeObject* parent);
virtual void PrintComment(std::ostream&) {}
@@ -114,19 +114,17 @@ public:
if (i != this->ObjectAttributes.end()) {
return i->second;
}
- return 0;
+ return nullptr;
}
// search the attribute list for an object of the specified type
cmXCodeObject* GetObject(cmXCodeObject::PBXType t) const
{
- for (std::vector<cmXCodeObject*>::const_iterator i = this->List.begin();
- i != this->List.end(); ++i) {
- cmXCodeObject* o = *i;
+ for (auto o : this->List) {
if (o->IsA == t) {
return o;
}
}
- return 0;
+ return nullptr;
}
void CopyAttributes(cmXCodeObject*);
diff --git a/Source/cmXCodeScheme.cxx b/Source/cmXCodeScheme.cxx
index 5c22531d4..f1dce6420 100644
--- a/Source/cmXCodeScheme.cxx
+++ b/Source/cmXCodeScheme.cxx
@@ -10,13 +10,12 @@
#include "cmGeneratorTarget.h"
#include "cmXMLSafe.h"
-cmXCodeScheme::cmXCodeScheme(cmXCodeObject* xcObj,
+cmXCodeScheme::cmXCodeScheme(cmXCodeObject* xcObj, const TestObjects& tests,
const std::vector<std::string>& configList,
unsigned int xcVersion)
: Target(xcObj)
+ , Tests(tests)
, TargetName(xcObj->GetTarget()->GetName())
- , BuildableName(xcObj->GetTarget()->GetFullName())
- , TargetId(xcObj->GetId())
, ConfigList(configList)
, XcodeVersion(xcVersion)
{
@@ -58,7 +57,7 @@ void cmXCodeScheme::WriteXCodeXCScheme(std::ostream& fout,
xout.Attribute("version", "1.3");
WriteBuildAction(xout, container);
- WriteTestAction(xout, FindConfiguration("Debug"));
+ WriteTestAction(xout, FindConfiguration("Debug"), container);
WriteLaunchAction(xout, FindConfiguration("Debug"), container);
WriteProfileAction(xout, FindConfiguration("Release"));
WriteAnalyzeAction(xout, FindConfiguration("Debug"));
@@ -84,14 +83,7 @@ void cmXCodeScheme::WriteBuildAction(cmXMLWriter& xout,
xout.Attribute("buildForArchiving", "YES");
xout.Attribute("buildForAnalyzing", "YES");
- xout.StartElement("BuildableReference");
- xout.BreakAttributes();
- xout.Attribute("BuildableIdentifier", "primary");
- xout.Attribute("BlueprintIdentifier", this->TargetId);
- xout.Attribute("BuildableName", this->BuildableName);
- xout.Attribute("BlueprintName", this->TargetName);
- xout.Attribute("ReferencedContainer", "container:" + container);
- xout.EndElement();
+ WriteBuildableReference(xout, this->Target, container);
xout.EndElement(); // BuildActionEntry
xout.EndElement(); // BuildActionEntries
@@ -99,7 +91,8 @@ void cmXCodeScheme::WriteBuildAction(cmXMLWriter& xout,
}
void cmXCodeScheme::WriteTestAction(cmXMLWriter& xout,
- std::string configuration)
+ const std::string& configuration,
+ const std::string& container)
{
xout.StartElement("TestAction");
xout.BreakAttributes();
@@ -111,8 +104,21 @@ void cmXCodeScheme::WriteTestAction(cmXMLWriter& xout,
xout.Attribute("shouldUseLaunchSchemeArgsEnv", "YES");
xout.StartElement("Testables");
+ for (auto test : this->Tests) {
+ xout.StartElement("TestableReference");
+ xout.BreakAttributes();
+ xout.Attribute("skipped", "NO");
+ WriteBuildableReference(xout, test, container);
+ xout.EndElement(); // TestableReference
+ }
xout.EndElement();
+ if (IsTestable()) {
+ xout.StartElement("MacroExpansion");
+ WriteBuildableReference(xout, this->Target, container);
+ xout.EndElement(); // MacroExpansion
+ }
+
xout.StartElement("AdditionalOptions");
xout.EndElement();
@@ -120,7 +126,7 @@ void cmXCodeScheme::WriteTestAction(cmXMLWriter& xout,
}
void cmXCodeScheme::WriteLaunchAction(cmXMLWriter& xout,
- std::string configuration,
+ const std::string& configuration,
const std::string& container)
{
xout.StartElement("LaunchAction");
@@ -146,14 +152,7 @@ void cmXCodeScheme::WriteLaunchAction(cmXMLWriter& xout,
xout.StartElement("MacroExpansion");
}
- xout.StartElement("BuildableReference");
- xout.BreakAttributes();
- xout.Attribute("BuildableIdentifier", "primary");
- xout.Attribute("BlueprintIdentifier", this->TargetId);
- xout.Attribute("BuildableName", this->BuildableName);
- xout.Attribute("BlueprintName", this->TargetName);
- xout.Attribute("ReferencedContainer", "container:" + container);
- xout.EndElement();
+ WriteBuildableReference(xout, this->Target, container);
xout.EndElement(); // MacroExpansion
@@ -164,7 +163,7 @@ void cmXCodeScheme::WriteLaunchAction(cmXMLWriter& xout,
}
void cmXCodeScheme::WriteProfileAction(cmXMLWriter& xout,
- std::string configuration)
+ const std::string& configuration)
{
xout.StartElement("ProfileAction");
xout.BreakAttributes();
@@ -177,7 +176,7 @@ void cmXCodeScheme::WriteProfileAction(cmXMLWriter& xout,
}
void cmXCodeScheme::WriteAnalyzeAction(cmXMLWriter& xout,
- std::string configuration)
+ const std::string& configuration)
{
xout.StartElement("AnalyzeAction");
xout.BreakAttributes();
@@ -186,7 +185,7 @@ void cmXCodeScheme::WriteAnalyzeAction(cmXMLWriter& xout,
}
void cmXCodeScheme::WriteArchiveAction(cmXMLWriter& xout,
- std::string configuration)
+ const std::string& configuration)
{
xout.StartElement("ArchiveAction");
xout.BreakAttributes();
@@ -195,6 +194,20 @@ void cmXCodeScheme::WriteArchiveAction(cmXMLWriter& xout,
xout.EndElement();
}
+void cmXCodeScheme::WriteBuildableReference(cmXMLWriter& xout,
+ const cmXCodeObject* xcObj,
+ const std::string& container)
+{
+ xout.StartElement("BuildableReference");
+ xout.BreakAttributes();
+ xout.Attribute("BuildableIdentifier", "primary");
+ xout.Attribute("BlueprintIdentifier", xcObj->GetId());
+ xout.Attribute("BuildableName", xcObj->GetTarget()->GetFullName());
+ xout.Attribute("BlueprintName", xcObj->GetTarget()->GetName());
+ xout.Attribute("ReferencedContainer", "container:" + container);
+ xout.EndElement();
+}
+
std::string cmXCodeScheme::WriteVersionString()
{
std::ostringstream v;
@@ -209,12 +222,18 @@ std::string cmXCodeScheme::FindConfiguration(const std::string& name)
//
if (std::find(this->ConfigList.begin(), this->ConfigList.end(), name) ==
this->ConfigList.end() &&
- this->ConfigList.size() > 0)
+ !this->ConfigList.empty()) {
return this->ConfigList[0];
+ }
return name;
}
+bool cmXCodeScheme::IsTestable() const
+{
+ return !this->Tests.empty() || IsExecutable(this->Target);
+}
+
bool cmXCodeScheme::IsExecutable(const cmXCodeObject* target)
{
cmGeneratorTarget* gt = target->GetTarget();
diff --git a/Source/cmXCodeScheme.h b/Source/cmXCodeScheme.h
index 379afed42..e5e501a6f 100644
--- a/Source/cmXCodeScheme.h
+++ b/Source/cmXCodeScheme.h
@@ -5,6 +5,8 @@
#include "cmConfigure.h" // IWYU pragma: keep
+#include <vector>
+
#include "cmGlobalXCodeGenerator.h"
#include "cmSystemTools.h"
#include "cmXCodeObject.h"
@@ -16,7 +18,9 @@
class cmXCodeScheme
{
public:
- cmXCodeScheme(cmXCodeObject* xcObj,
+ typedef std::vector<const cmXCodeObject*> TestObjects;
+
+ cmXCodeScheme(cmXCodeObject* xcObj, const TestObjects& tests,
const std::vector<std::string>& configList,
unsigned int xcVersion);
@@ -25,25 +29,30 @@ public:
private:
const cmXCodeObject* const Target;
+ const TestObjects Tests;
const std::string& TargetName;
- const std::string BuildableName;
- const std::string& TargetId;
const std::vector<std::string>& ConfigList;
const unsigned int XcodeVersion;
void WriteXCodeXCScheme(std::ostream& fout, const std::string& container);
void WriteBuildAction(cmXMLWriter& xout, const std::string& container);
- void WriteTestAction(cmXMLWriter& xout, std::string configuration);
- void WriteLaunchAction(cmXMLWriter& xout, std::string configuration,
+ void WriteTestAction(cmXMLWriter& xout, const std::string& configuration,
+ const std::string& container);
+ void WriteLaunchAction(cmXMLWriter& xout, const std::string& configuration,
const std::string& container);
- void WriteProfileAction(cmXMLWriter& xout, std::string configuration);
- void WriteAnalyzeAction(cmXMLWriter& xout, std::string configuration);
- void WriteArchiveAction(cmXMLWriter& xout, std::string configuration);
+ void WriteProfileAction(cmXMLWriter& xout, const std::string& configuration);
+ void WriteAnalyzeAction(cmXMLWriter& xout, const std::string& configuration);
+ void WriteArchiveAction(cmXMLWriter& xout, const std::string& configuration);
+
+ void WriteBuildableReference(cmXMLWriter& xout, const cmXCodeObject* xcObj,
+ const std::string& container);
std::string WriteVersionString();
std::string FindConfiguration(const std::string& name);
+ bool IsTestable() const;
+
static bool IsExecutable(const cmXCodeObject* target);
};
diff --git a/Source/cmXMLParser.cxx b/Source/cmXMLParser.cxx
index 18afbf370..920e3a5e9 100644
--- a/Source/cmXMLParser.cxx
+++ b/Source/cmXMLParser.cxx
@@ -11,10 +11,10 @@
cmXMLParser::cmXMLParser()
{
- this->Parser = CM_NULLPTR;
+ this->Parser = nullptr;
this->ParseError = 0;
- this->ReportCallback = CM_NULLPTR;
- this->ReportCallbackData = CM_NULLPTR;
+ this->ReportCallback = nullptr;
+ this->ReportCallbackData = nullptr;
}
cmXMLParser::~cmXMLParser()
@@ -26,7 +26,7 @@ cmXMLParser::~cmXMLParser()
int cmXMLParser::Parse(const char* string)
{
- return (int)this->InitializeParser() &&
+ return this->InitializeParser() &&
this->ParseChunk(string, strlen(string)) && this->CleanupParser();
}
@@ -55,7 +55,7 @@ int cmXMLParser::InitializeParser()
}
// Create the expat XML parser.
- this->Parser = XML_ParserCreate(CM_NULLPTR);
+ this->Parser = XML_ParserCreate(nullptr);
XML_SetElementHandler(static_cast<XML_Parser>(this->Parser),
&cmXMLParserStartElement, &cmXMLParserEndElement);
XML_SetCharacterDataHandler(static_cast<XML_Parser>(this->Parser),
@@ -99,7 +99,7 @@ int cmXMLParser::CleanupParser()
// Clean up the parser.
XML_ParserFree(static_cast<XML_Parser>(this->Parser));
- this->Parser = CM_NULLPTR;
+ this->Parser = nullptr;
return result;
}
@@ -156,7 +156,7 @@ const char* cmXMLParser::FindAttribute(const char** atts,
}
}
}
- return CM_NULLPTR;
+ return nullptr;
}
void cmXMLParserStartElement(void* parser, const char* name, const char** atts)
diff --git a/Source/cmXMLWriter.h b/Source/cmXMLWriter.h
index ed76a88c7..981255d41 100644
--- a/Source/cmXMLWriter.h
+++ b/Source/cmXMLWriter.h
@@ -3,7 +3,7 @@
#ifndef cmXMLWiter_h
#define cmXMLWiter_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmXMLSafe.h"
@@ -107,7 +107,7 @@ private:
private:
std::ostream& Output;
- std::stack<std::string, std::vector<std::string> > Elements;
+ std::stack<std::string, std::vector<std::string>> Elements;
std::string IndentationElement;
std::size_t Level;
bool ElementOpen;
diff --git a/Source/cm_auto_ptr.hxx b/Source/cm_auto_ptr.hxx
deleted file mode 100644
index 773602af9..000000000
--- a/Source/cm_auto_ptr.hxx
+++ /dev/null
@@ -1,220 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing for details. */
-#ifndef CM_AUTO_PTR_HXX
-#define CM_AUTO_PTR_HXX
-
-#include "cmConfigure.h"
-
-#ifdef CMake_HAVE_CXX_AUTO_PTR
-
-#include <memory>
-#define CM_AUTO_PTR std::auto_ptr
-
-#else
-
-#define CM_AUTO_PTR cm::auto_ptr
-
-// The HP compiler cannot handle the conversions necessary to use
-// auto_ptr_ref to pass an auto_ptr returned from one function
-// directly to another function as in use_auto_ptr(get_auto_ptr()).
-// We instead use const_cast to achieve the syntax on those platforms.
-// We do not use const_cast on other platforms to maintain the C++
-// standard design and guarantee that if an auto_ptr is bound
-// to a reference-to-const then ownership will be maintained.
-#if defined(__HP_aCC)
-#define cm_AUTO_PTR_REF 0
-#define cm_AUTO_PTR_CONST const
-#define cm_AUTO_PTR_CAST(a) cast(a)
-#else
-#define cm_AUTO_PTR_REF 1
-#define cm_AUTO_PTR_CONST
-#define cm_AUTO_PTR_CAST(a) a
-#endif
-
-// In C++11, clang will warn about using dynamic exception specifications
-// as they are deprecated. But as this class is trying to faithfully
-// mimic std::auto_ptr, we want to keep the 'throw()' decorations below.
-// So we suppress the warning.
-#if defined(__clang__) && defined(__has_warning)
-#if __has_warning("-Wdeprecated")
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wdeprecated"
-#endif
-#endif
-
-namespace cm {
-
-template <class X>
-class auto_ptr;
-
-#if cm_AUTO_PTR_REF
-namespace detail {
-// The auto_ptr_ref template is supposed to be a private member of
-// auto_ptr but Borland 5.8 cannot handle it. Instead put it in
-// a private namespace.
-template <class Y>
-struct auto_ptr_ref
-{
- Y* p_;
-
- // The extra constructor argument prevents implicit conversion to
- // auto_ptr_ref from auto_ptr through the constructor. Normally
- // this should be done with the explicit keyword but Borland 5.x
- // generates code in the conversion operator to call itself
- // infinately.
- auto_ptr_ref(Y* p, int)
- : p_(p)
- {
- }
-};
-}
-#endif
-
-/** C++98 Standard Section 20.4.5 - Template class auto_ptr. */
-template <class X>
-class auto_ptr
-{
-#if !cm_AUTO_PTR_REF
- template <typename Y>
- static inline auto_ptr<Y>& cast(auto_ptr<Y> const& a)
- {
- return const_cast<auto_ptr<Y>&>(a);
- }
-#endif
-
- /** The pointer to the object held. */
- X* x_;
-
-public:
- /** The type of object held by the auto_ptr. */
- typedef X element_type;
-
- /** Construct from an auto_ptr holding a compatible object. This
- transfers ownership to the newly constructed auto_ptr. */
- template <class Y>
- auto_ptr(auto_ptr<Y> cm_AUTO_PTR_CONST& a) throw()
- : x_(cm_AUTO_PTR_CAST(a).release())
- {
- }
-
- /** Assign from an auto_ptr holding a compatible object. This
- transfers ownership to the left-hand-side of the assignment. */
- template <class Y>
- auto_ptr& operator=(auto_ptr<Y> cm_AUTO_PTR_CONST& a) throw() // NOLINT
- {
- this->reset(cm_AUTO_PTR_CAST(a).release());
- return *this; // NOLINT
- }
-
- /**
- * Explicitly construct from a raw pointer. This is typically
- * called with the result of operator new. For example:
- *
- * auto_ptr<X> ptr(new X());
- */
- explicit auto_ptr(X* p = CM_NULLPTR) throw()
- : x_(p)
- {
- }
-
- /** Construct from another auto_ptr holding an object of the same
- type. This transfers ownership to the newly constructed
- auto_ptr. */
- auto_ptr(auto_ptr cm_AUTO_PTR_CONST& a) throw()
- : x_(cm_AUTO_PTR_CAST(a).release())
- {
- }
-
- /** Assign from another auto_ptr holding an object of the same type.
- This transfers ownership to the newly constructed auto_ptr. */
- auto_ptr& operator=(auto_ptr cm_AUTO_PTR_CONST& a) throw() // NOLINT
- {
- this->reset(cm_AUTO_PTR_CAST(a).release());
- return *this; // NOLINT
- }
-
- /** Destruct and delete the object held. */
- ~auto_ptr() throw()
- {
- // Assume object destructor is nothrow.
- delete this->x_;
- }
-
- /** Dereference and return a reference to the object held. */
- X& operator*() const throw() { return *this->x_; }
-
- /** Return a pointer to the object held. */
- X* operator->() const throw() { return this->x_; }
-
- /** Return a pointer to the object held. */
- X* get() const throw() { return this->x_; }
-
- /** Return a pointer to the object held and reset to hold no object.
- This transfers ownership to the caller. */
- X* release() throw()
- {
- X* x = this->x_;
- this->x_ = CM_NULLPTR;
- return x;
- }
-
- /** Assume ownership of the given object. The object previously
- held is deleted. */
- void reset(X* p = 0) throw()
- {
- if (this->x_ != p) {
- // Assume object destructor is nothrow.
- delete this->x_;
- this->x_ = p;
- }
- }
-
- /** Convert to an auto_ptr holding an object of a compatible type.
- This transfers ownership to the returned auto_ptr. */
- template <class Y>
- operator auto_ptr<Y>() throw()
- {
- return auto_ptr<Y>(this->release());
- }
-
-#if cm_AUTO_PTR_REF
- /** Construct from an auto_ptr_ref. This is used when the
- constructor argument is a call to a function returning an
- auto_ptr. */
- auto_ptr(detail::auto_ptr_ref<X> r) throw()
- : x_(r.p_)
- {
- }
-
- /** Assign from an auto_ptr_ref. This is used when a function
- returning an auto_ptr is passed on the right-hand-side of an
- assignment. */
- auto_ptr& operator=(detail::auto_ptr_ref<X> r) throw()
- {
- this->reset(r.p_);
- return *this; // NOLINT
- }
-
- /** Convert to an auto_ptr_ref. This is used when a function
- returning an auto_ptr is the argument to the constructor of
- another auto_ptr. */
- template <class Y>
- operator detail::auto_ptr_ref<Y>() throw()
- {
- return detail::auto_ptr_ref<Y>(this->release(), 1);
- }
-#endif
-};
-
-} // namespace cm
-
-// Undo warning suppression.
-#if defined(__clang__) && defined(__has_warning)
-#if __has_warning("-Wdeprecated")
-#pragma clang diagnostic pop
-#endif
-#endif
-
-#endif
-
-#endif
diff --git a/Source/cm_codecvt.hxx b/Source/cm_codecvt.hxx
index 30c6d5407..3a5606b3d 100644
--- a/Source/cm_codecvt.hxx
+++ b/Source/cm_codecvt.hxx
@@ -3,7 +3,7 @@
#ifndef cm_codecvt_hxx
#define cm_codecvt_hxx
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <locale>
#include <wchar.h>
@@ -23,15 +23,15 @@ public:
codecvt(Encoding e);
protected:
- ~codecvt() CM_OVERRIDE;
- bool do_always_noconv() const throw() CM_OVERRIDE;
+ ~codecvt() override;
+ bool do_always_noconv() const throw() override;
result do_out(mbstate_t& state, const char* from, const char* from_end,
const char*& from_next, char* to, char* to_end,
- char*& to_next) const CM_OVERRIDE;
+ char*& to_next) const override;
result do_unshift(mbstate_t& state, char* to, char*,
- char*& to_next) const CM_OVERRIDE;
- int do_max_length() const throw() CM_OVERRIDE;
- int do_encoding() const throw() CM_OVERRIDE;
+ char*& to_next) const override;
+ int do_max_length() const throw() override;
+ int do_encoding() const throw() override;
private:
// The mbstate_t argument to do_out and do_unshift is responsible
diff --git a/Source/cm_sys_stat.h b/Source/cm_sys_stat.h
index 26e4baa03..796f027c1 100644
--- a/Source/cm_sys_stat.h
+++ b/Source/cm_sys_stat.h
@@ -7,6 +7,11 @@
typedef unsigned short mode_t;
#endif
+#if defined(WIN32)
+typedef unsigned short uid_t;
+typedef unsigned short gid_t;
+#endif
+
#include <sys/types.h>
// include sys/stat.h after sys/types.h
#include <sys/stat.h>
diff --git a/Source/cm_unordered_map.hxx b/Source/cm_unordered_map.hxx
deleted file mode 100644
index bf3890314..000000000
--- a/Source/cm_unordered_map.hxx
+++ /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. */
-#ifndef CM_UNORDERED_MAP_HXX
-#define CM_UNORDERED_MAP_HXX
-
-#include "cmConfigure.h"
-
-#if defined(CMake_HAVE_CXX_UNORDERED_MAP)
-
-#include <unordered_map>
-#define CM_UNORDERED_MAP std::unordered_map
-
-#elif defined(CMAKE_BUILD_WITH_CMAKE)
-
-#include "cmsys/hash_map.hxx"
-#define CM_UNORDERED_MAP cmsys::hash_map
-
-#else
-
-#include <map>
-#define CM_UNORDERED_MAP std::map
-
-#endif
-
-#endif
diff --git a/Source/cm_unordered_set.hxx b/Source/cm_unordered_set.hxx
deleted file mode 100644
index dd1a9a115..000000000
--- a/Source/cm_unordered_set.hxx
+++ /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. */
-#ifndef CM_UNORDERED_SET_HXX
-#define CM_UNORDERED_SET_HXX
-
-#include "cmConfigure.h"
-
-#if defined(CMake_HAVE_CXX_UNORDERED_SET)
-
-#include <unordered_set>
-#define CM_UNORDERED_SET std::unordered_set
-
-#elif defined(CMAKE_BUILD_WITH_CMAKE)
-
-#include "cmsys/hash_set.hxx"
-#define CM_UNORDERED_SET cmsys::hash_set
-
-#else
-
-#include <set>
-#define CM_UNORDERED_SET std::set
-
-#endif
-
-#endif
diff --git a/Source/cmake.cxx b/Source/cmake.cxx
index 689439378..fd7151f08 100644
--- a/Source/cmake.cxx
+++ b/Source/cmake.cxx
@@ -24,7 +24,6 @@
#include "cmUtils.hxx"
#include "cmVersionConfig.h"
#include "cmWorkingDirectory.h"
-#include "cm_auto_ptr.hxx"
#include "cm_sys_stat.h"
#if defined(CMAKE_BUILD_WITH_CMAKE)
@@ -32,7 +31,7 @@
#include "cmGraphVizWriter.h"
#include "cmVariableWatch.h"
-#include "cm_unordered_map.hxx"
+#include <unordered_map>
#endif
// only build kdevelop generator on non-windows platforms
@@ -111,6 +110,7 @@
#include "cmsys/RegularExpression.hxx"
#include <algorithm>
#include <iostream>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
@@ -120,7 +120,7 @@
namespace {
#if defined(CMAKE_BUILD_WITH_CMAKE)
-typedef CM_UNORDERED_MAP<std::string, Json::Value> JsonValueMapType;
+typedef std::unordered_map<std::string, Json::Value> JsonValueMapType;
#endif
} // namespace
@@ -163,9 +163,9 @@ cmake::cmake(Role role)
}
#endif
- this->GlobalGenerator = CM_NULLPTR;
- this->ProgressCallback = CM_NULLPTR;
- this->ProgressCallbackClientData = CM_NULLPTR;
+ this->GlobalGenerator = nullptr;
+ this->ProgressCallback = nullptr;
+ this->ProgressCallbackClientData = nullptr;
this->CurrentWorkingMode = NORMAL_MODE;
#ifdef CMAKE_BUILD_WITH_CMAKE
@@ -215,7 +215,7 @@ cmake::~cmake()
delete this->Messenger;
if (this->GlobalGenerator) {
delete this->GlobalGenerator;
- this->GlobalGenerator = CM_NULLPTR;
+ this->GlobalGenerator = nullptr;
}
cmDeleteAll(this->Generators);
#ifdef CMAKE_BUILD_WITH_CMAKE
@@ -244,31 +244,28 @@ Json::Value cmake::ReportCapabilitiesJson(bool haveServerMode) const
this->GetRegisteredGenerators(generatorInfoList);
JsonValueMapType generatorMap;
- for (std::vector<cmake::GeneratorInfo>::const_iterator i =
- generatorInfoList.begin();
- i != generatorInfoList.end(); ++i) {
- if (i->isAlias) { // skip aliases, they are there for compatibility reasons
+ for (cmake::GeneratorInfo const& gi : generatorInfoList) {
+ if (gi.isAlias) { // skip aliases, they are there for compatibility reasons
// only
continue;
}
- if (i->extraName.empty()) {
+ if (gi.extraName.empty()) {
Json::Value gen = Json::objectValue;
- gen["name"] = i->name;
- gen["toolsetSupport"] = i->supportsToolset;
- gen["platformSupport"] = i->supportsPlatform;
+ gen["name"] = gi.name;
+ gen["toolsetSupport"] = gi.supportsToolset;
+ gen["platformSupport"] = gi.supportsPlatform;
gen["extraGenerators"] = Json::arrayValue;
- generatorMap[i->name] = gen;
+ generatorMap[gi.name] = gen;
} else {
- Json::Value& gen = generatorMap[i->baseName];
- gen["extraGenerators"].append(i->extraName);
+ Json::Value& gen = generatorMap[gi.baseName];
+ gen["extraGenerators"].append(gi.extraName);
}
}
Json::Value generators = Json::arrayValue;
- for (JsonValueMapType::const_iterator i = generatorMap.begin();
- i != generatorMap.end(); ++i) {
- generators.append(i->second);
+ for (auto const& i : generatorMap) {
+ generators.append(i.second);
}
obj["generators"] = generators;
obj["serverMode"] = haveServerMode;
@@ -407,21 +404,18 @@ bool cmake::SetCacheArgs(const std::vector<std::string>& args)
// removed
std::vector<std::string> entriesToDelete;
std::vector<std::string> cacheKeys = this->State->GetCacheEntryKeys();
- for (std::vector<std::string>::const_iterator it = cacheKeys.begin();
- it != cacheKeys.end(); ++it) {
- cmStateEnums::CacheEntryType t = this->State->GetCacheEntryType(*it);
+ for (std::string const& ck : cacheKeys) {
+ cmStateEnums::CacheEntryType t = this->State->GetCacheEntryType(ck);
if (t != cmStateEnums::STATIC) {
- if (regex.find(it->c_str())) {
- entriesToDelete.push_back(*it);
+ if (regex.find(ck.c_str())) {
+ entriesToDelete.push_back(ck);
}
}
}
// now remove them from the cache
- for (std::vector<std::string>::const_iterator currentEntry =
- entriesToDelete.begin();
- currentEntry != entriesToDelete.end(); ++currentEntry) {
- this->State->RemoveCacheEntry(*currentEntry);
+ for (std::string const& currentEntry : entriesToDelete) {
+ this->State->RemoveCacheEntry(currentEntry);
}
} else if (arg.find("-C", 0) == 0) {
std::string path = arg.substr(2);
@@ -488,15 +482,15 @@ void cmake::ReadListFile(const std::vector<std::string>& args,
snapshot.GetDirectory().SetCurrentSource(
cmSystemTools::GetCurrentWorkingDirectory());
snapshot.SetDefaultDefinitions();
- CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(gg, snapshot));
+ cmMakefile mf(gg, snapshot);
if (this->GetWorkingMode() != NORMAL_MODE) {
std::string file(cmSystemTools::CollapseFullPath(path));
cmSystemTools::ConvertToUnixSlashes(file);
- mf->SetScriptModeFile(file.c_str());
+ mf.SetScriptModeFile(file.c_str());
- mf->SetArgcArgv(args);
+ mf.SetArgcArgv(args);
}
- if (!mf->ReadListFile(path)) {
+ if (!mf.ReadListFile(path)) {
cmSystemTools::Error("Error processing file: ", path);
}
this->SetHomeDirectory(homeDir);
@@ -555,7 +549,7 @@ bool cmake::FindPackage(const std::vector<std::string>& args)
gg->CreateGenerationObjects();
cmLocalGenerator* lg = gg->LocalGenerators[0];
std::string includeFlags =
- lg->GetIncludeFlags(includeDirs, CM_NULLPTR, language);
+ lg->GetIncludeFlags(includeDirs, nullptr, language);
std::string definitions = mf->GetSafeDefinition("PACKAGE_DEFINITIONS");
printf("%s %s\n", includeFlags.c_str(), definitions.c_str());
@@ -568,9 +562,8 @@ bool cmake::FindPackage(const std::vector<std::string>& args)
std::string libs = mf->GetSafeDefinition("PACKAGE_LIBRARIES");
std::vector<std::string> libList;
cmSystemTools::ExpandListArgument(libs, libList);
- for (std::vector<std::string>::const_iterator libIt = libList.begin();
- libIt != libList.end(); ++libIt) {
- tgt->AddLinkLibrary(*mf, *libIt, GENERAL_LibraryType);
+ for (std::string const& lib : libList) {
+ tgt->AddLinkLibrary(*mf, lib, GENERAL_LibraryType);
}
std::string buildType = mf->GetSafeDefinition("CMAKE_BUILD_TYPE");
@@ -906,49 +899,42 @@ void cmake::AddDefaultExtraGenerators()
void cmake::GetRegisteredGenerators(
std::vector<GeneratorInfo>& generators) const
{
- for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin(),
- e = this->Generators.end();
- i != e; ++i) {
+ for (cmGlobalGeneratorFactory* gen : this->Generators) {
std::vector<std::string> names;
- (*i)->GetGenerators(names);
+ gen->GetGenerators(names);
- for (size_t j = 0; j < names.size(); ++j) {
+ for (std::string const& name : names) {
GeneratorInfo info;
- info.supportsToolset = (*i)->SupportsToolset();
- info.supportsPlatform = (*i)->SupportsPlatform();
- info.name = names[j];
- info.baseName = names[j];
+ info.supportsToolset = gen->SupportsToolset();
+ info.supportsPlatform = gen->SupportsPlatform();
+ info.name = name;
+ info.baseName = name;
info.isAlias = false;
generators.push_back(info);
}
}
- for (RegisteredExtraGeneratorsVector::const_iterator
- i = this->ExtraGenerators.begin(),
- e = this->ExtraGenerators.end();
- i != e; ++i) {
+ for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
const std::vector<std::string> genList =
- (*i)->GetSupportedGlobalGenerators();
- for (std::vector<std::string>::const_iterator gen = genList.begin();
- gen != genList.end(); ++gen) {
+ eg->GetSupportedGlobalGenerators();
+ for (std::string const& gen : genList) {
GeneratorInfo info;
info.name = cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
- *gen, (*i)->GetName());
- info.baseName = *gen;
- info.extraName = (*i)->GetName();
+ gen, eg->GetName());
+ info.baseName = gen;
+ info.extraName = eg->GetName();
info.supportsPlatform = false;
info.supportsToolset = false;
info.isAlias = false;
generators.push_back(info);
}
- for (std::vector<std::string>::const_iterator a = (*i)->Aliases.begin();
- a != (*i)->Aliases.end(); ++a) {
+ for (std::string const& a : eg->Aliases) {
GeneratorInfo info;
- info.name = *a;
+ info.name = a;
if (!genList.empty()) {
info.baseName = genList.at(0);
}
- info.extraName = (*i)->GetName();
+ info.extraName = eg->GetName();
info.supportsPlatform = false;
info.supportsToolset = false;
info.isAlias = true;
@@ -962,28 +948,24 @@ createExtraGenerator(
const std::vector<cmExternalMakefileProjectGeneratorFactory*>& in,
const std::string& name)
{
- for (std::vector<cmExternalMakefileProjectGeneratorFactory*>::const_iterator
- i = in.begin();
- i != in.end(); ++i) {
+ for (cmExternalMakefileProjectGeneratorFactory* i : in) {
const std::vector<std::string> generators =
- (*i)->GetSupportedGlobalGenerators();
- if ((*i)->GetName() == name) { // Match aliases
- return std::make_pair((*i)->CreateExternalMakefileProjectGenerator(),
+ i->GetSupportedGlobalGenerators();
+ if (i->GetName() == name) { // Match aliases
+ return std::make_pair(i->CreateExternalMakefileProjectGenerator(),
generators.at(0));
}
- for (std::vector<std::string>::const_iterator g = generators.begin();
- g != generators.end(); ++g) {
+ for (std::string const& g : generators) {
const std::string fullName =
cmExternalMakefileProjectGenerator::CreateFullGeneratorName(
- *g, (*i)->GetName());
+ g, i->GetName());
if (fullName == name) {
- return std::make_pair((*i)->CreateExternalMakefileProjectGenerator(),
- *g);
+ return std::make_pair(i->CreateExternalMakefileProjectGenerator(), g);
}
}
}
return std::make_pair(
- static_cast<cmExternalMakefileProjectGenerator*>(CM_NULLPTR), name);
+ static_cast<cmExternalMakefileProjectGenerator*>(nullptr), name);
}
cmGlobalGenerator* cmake::CreateGlobalGenerator(const std::string& gname)
@@ -993,10 +975,9 @@ cmGlobalGenerator* cmake::CreateGlobalGenerator(const std::string& gname)
cmExternalMakefileProjectGenerator* extraGenerator = extra.first;
const std::string name = extra.second;
- cmGlobalGenerator* generator = CM_NULLPTR;
- for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin();
- i != this->Generators.end(); ++i) {
- generator = (*i)->CreateGlobalGenerator(name, this);
+ cmGlobalGenerator* generator = nullptr;
+ for (cmGlobalGeneratorFactory* g : this->Generators) {
+ generator = g->CreateGlobalGenerator(name, this);
if (generator) {
break;
}
@@ -1091,10 +1072,10 @@ void cmake::SetGlobalGenerator(cmGlobalGenerator* gg)
// Save the environment variables CXX and CC
if (!cmSystemTools::GetEnv("CXX", this->CXXEnvironment)) {
- this->CXXEnvironment = "";
+ this->CXXEnvironment.clear();
}
if (!cmSystemTools::GetEnv("CC", this->CCEnvironment)) {
- this->CCEnvironment = "";
+ this->CCEnvironment.clear();
}
}
@@ -1192,9 +1173,8 @@ int cmake::HandleDeleteCacheVariables(const std::string& var)
// load the empty cache
this->LoadCache();
// restore the changed compilers
- for (std::vector<SaveCacheEntry>::iterator i = saved.begin();
- i != saved.end(); ++i) {
- this->AddCacheEntry(i->key, i->value.c_str(), i->help.c_str(), i->type);
+ for (SaveCacheEntry const& i : saved) {
+ this->AddCacheEntry(i.key, i.value.c_str(), i.help.c_str(), i.type);
}
cmSystemTools::Message(warning.str().c_str());
// avoid reconfigure if there were errors
@@ -1348,9 +1328,8 @@ int cmake::ActualConfigure()
if (const char* platformName =
this->State->GetInitializedCacheValue("CMAKE_GENERATOR_PLATFORM")) {
- if (this->GeneratorPlatform.empty()) {
- this->GeneratorPlatform = platformName;
- } else if (this->GeneratorPlatform != platformName) {
+ if (!this->GeneratorPlatform.empty() &&
+ this->GeneratorPlatform != platformName) {
std::string message = "Error: generator platform: ";
message += this->GeneratorPlatform;
message += "\nDoes not match the platform used previously: ";
@@ -1368,9 +1347,7 @@ int cmake::ActualConfigure()
if (const char* tsName =
this->State->GetInitializedCacheValue("CMAKE_GENERATOR_TOOLSET")) {
- if (this->GeneratorToolset.empty()) {
- this->GeneratorToolset = tsName;
- } else if (this->GeneratorToolset != tsName) {
+ if (!this->GeneratorToolset.empty() && this->GeneratorToolset != tsName) {
std::string message = "Error: generator toolset: ";
message += this->GeneratorToolset;
message += "\nDoes not match the toolset used previously: ";
@@ -1791,35 +1768,30 @@ void cmake::SetIsInTryCompile(bool b)
void cmake::GetGeneratorDocumentation(std::vector<cmDocumentationEntry>& v)
{
- for (RegisteredGeneratorsVector::const_iterator i = this->Generators.begin();
- i != this->Generators.end(); ++i) {
+ for (cmGlobalGeneratorFactory* g : this->Generators) {
cmDocumentationEntry e;
- (*i)->GetDocumentation(e);
+ g->GetDocumentation(e);
v.push_back(e);
}
- for (RegisteredExtraGeneratorsVector::const_iterator i =
- this->ExtraGenerators.begin();
- i != this->ExtraGenerators.end(); ++i) {
- const std::string doc = (*i)->GetDocumentation();
- const std::string name = (*i)->GetName();
+ for (cmExternalMakefileProjectGeneratorFactory* eg : this->ExtraGenerators) {
+ const std::string doc = eg->GetDocumentation();
+ const std::string name = eg->GetName();
// Aliases:
- for (std::vector<std::string>::const_iterator a = (*i)->Aliases.begin();
- a != (*i)->Aliases.end(); ++a) {
+ for (std::string const& a : eg->Aliases) {
cmDocumentationEntry e;
- e.Name = *a;
+ e.Name = a;
e.Brief = doc;
v.push_back(e);
}
// Full names:
const std::vector<std::string> generators =
- (*i)->GetSupportedGlobalGenerators();
- for (std::vector<std::string>::const_iterator g = generators.begin();
- g != generators.end(); ++g) {
+ eg->GetSupportedGlobalGenerators();
+ for (std::string const& g : generators) {
cmDocumentationEntry e;
e.Name =
- cmExternalMakefileProjectGenerator::CreateFullGeneratorName(*g, name);
+ cmExternalMakefileProjectGenerator::CreateFullGeneratorName(g, name);
e.Brief = doc;
v.push_back(e);
}
@@ -1899,8 +1871,8 @@ int cmake::CheckBuildSystem()
cm.SetHomeOutputDirectory("");
cm.GetCurrentSnapshot().SetDefaultDefinitions();
cmGlobalGenerator gg(&cm);
- CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(&gg, cm.GetCurrentSnapshot()));
- if (!mf->ReadListFile(this->CheckBuildSystemArgument.c_str()) ||
+ cmMakefile mf(&gg, cm.GetCurrentSnapshot());
+ if (!mf.ReadListFile(this->CheckBuildSystemArgument.c_str()) ||
cmSystemTools::GetErrorOccuredFlag()) {
if (verbose) {
std::ostringstream msg;
@@ -1914,34 +1886,33 @@ int cmake::CheckBuildSystem()
if (this->ClearBuildSystem) {
// Get the generator used for this build system.
- const char* genName = mf->GetDefinition("CMAKE_DEPENDS_GENERATOR");
+ const char* genName = mf.GetDefinition("CMAKE_DEPENDS_GENERATOR");
if (!genName || genName[0] == '\0') {
genName = "Unix Makefiles";
}
// Create the generator and use it to clear the dependencies.
- CM_AUTO_PTR<cmGlobalGenerator> ggd(this->CreateGlobalGenerator(genName));
- if (ggd.get()) {
+ std::unique_ptr<cmGlobalGenerator> ggd(
+ this->CreateGlobalGenerator(genName));
+ if (ggd) {
cm.GetCurrentSnapshot().SetDefaultDefinitions();
- CM_AUTO_PTR<cmMakefile> mfd(
- new cmMakefile(ggd.get(), cm.GetCurrentSnapshot()));
- CM_AUTO_PTR<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(mfd.get()));
- lgd->ClearDependencies(mfd.get(), verbose);
+ cmMakefile mfd(ggd.get(), cm.GetCurrentSnapshot());
+ std::unique_ptr<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(&mfd));
+ lgd->ClearDependencies(&mfd, verbose);
}
}
// If any byproduct of makefile generation is missing we must re-run.
std::vector<std::string> products;
- if (const char* productStr = mf->GetDefinition("CMAKE_MAKEFILE_PRODUCTS")) {
+ if (const char* productStr = mf.GetDefinition("CMAKE_MAKEFILE_PRODUCTS")) {
cmSystemTools::ExpandListArgument(productStr, products);
}
- for (std::vector<std::string>::const_iterator pi = products.begin();
- pi != products.end(); ++pi) {
- if (!(cmSystemTools::FileExists(pi->c_str()) ||
- cmSystemTools::FileIsSymlink(*pi))) {
+ for (std::string const& p : products) {
+ if (!(cmSystemTools::FileExists(p.c_str()) ||
+ cmSystemTools::FileIsSymlink(p))) {
if (verbose) {
std::ostringstream msg;
- msg << "Re-run cmake, missing byproduct: " << *pi << "\n";
+ msg << "Re-run cmake, missing byproduct: " << p << "\n";
cmSystemTools::Stdout(msg.str().c_str());
}
return 1;
@@ -1951,8 +1922,8 @@ int cmake::CheckBuildSystem()
// Get the set of dependencies and outputs.
std::vector<std::string> depends;
std::vector<std::string> outputs;
- const char* dependsStr = mf->GetDefinition("CMAKE_MAKEFILE_DEPENDS");
- const char* outputsStr = mf->GetDefinition("CMAKE_MAKEFILE_OUTPUTS");
+ const char* dependsStr = mf.GetDefinition("CMAKE_MAKEFILE_DEPENDS");
+ const char* outputsStr = mf.GetDefinition("CMAKE_MAKEFILE_OUTPUTS");
if (dependsStr && outputsStr) {
cmSystemTools::ExpandListArgument(dependsStr, depends);
cmSystemTools::ExpandListArgument(outputsStr, outputs);
@@ -2065,19 +2036,18 @@ void cmake::MarkCliAsUsed(const std::string& variable)
void cmake::GenerateGraphViz(const char* fileName) const
{
#ifdef CMAKE_BUILD_WITH_CMAKE
- CM_AUTO_PTR<cmGraphVizWriter> gvWriter(
- new cmGraphVizWriter(this->GetGlobalGenerator()->GetLocalGenerators()));
+ cmGraphVizWriter gvWriter(this->GetGlobalGenerator()->GetLocalGenerators());
std::string settingsFile = this->GetHomeOutputDirectory();
settingsFile += "/CMakeGraphVizOptions.cmake";
std::string fallbackSettingsFile = this->GetHomeDirectory();
fallbackSettingsFile += "/CMakeGraphVizOptions.cmake";
- gvWriter->ReadSettings(settingsFile.c_str(), fallbackSettingsFile.c_str());
+ gvWriter.ReadSettings(settingsFile.c_str(), fallbackSettingsFile.c_str());
- gvWriter->WritePerTargetFiles(fileName);
- gvWriter->WriteTargetDependersFiles(fileName);
- gvWriter->WriteGlobalFile(fileName);
+ gvWriter.WritePerTargetFiles(fileName);
+ gvWriter.WriteTargetDependersFiles(fileName);
+ gvWriter.WriteGlobalFile(fileName);
#endif
}
@@ -2127,7 +2097,7 @@ cmInstalledFile const* cmake::GetInstalledFile(const std::string& name) const
cmInstalledFile const& file = i->second;
return &file;
}
- return CM_NULLPTR;
+ return nullptr;
}
int cmake::GetSystemInformation(std::vector<std::string>& args)
@@ -2383,7 +2353,7 @@ int cmake::Build(const std::string& dir, const std::string& target,
std::cerr << "Error: could not find CMAKE_GENERATOR in Cache\n";
return 1;
}
- CM_AUTO_PTR<cmGlobalGenerator> gen(
+ std::unique_ptr<cmGlobalGenerator> gen(
this->CreateGlobalGenerator(cachedGenerator));
if (!gen.get()) {
std::cerr << "Error: could create CMAKE_GENERATOR \"" << cachedGenerator
@@ -2479,12 +2449,10 @@ void cmake::RunCheckForUnusedVariables()
bool haveUnused = false;
std::ostringstream msg;
msg << "Manually-specified variables were not used by the project:";
- for (std::map<std::string, bool>::const_iterator it =
- this->UsedCliVariables.begin();
- it != this->UsedCliVariables.end(); ++it) {
- if (!it->second) {
+ for (auto const& it : this->UsedCliVariables) {
+ if (!it.second) {
haveUnused = true;
- msg << "\n " << it->first;
+ msg << "\n " << it.first;
}
}
if (haveUnused) {
diff --git a/Source/cmake.h b/Source/cmake.h
index 4ddacf701..b31b6f5ce 100644
--- a/Source/cmake.h
+++ b/Source/cmake.h
@@ -3,7 +3,7 @@
#ifndef cmake_h
#define cmake_h
-#include "cmConfigure.h"
+#include "cmConfigure.h" // IWYU pragma: keep
#include <map>
#include <set>
@@ -209,24 +209,12 @@ public:
this->GeneratorPlatform = ts;
}
- ///! Get the name of the selected generator-specific platform.
- std::string const& GetGeneratorPlatform() const
- {
- return this->GeneratorPlatform;
- }
-
///! Set the name of the selected generator-specific toolset.
void SetGeneratorToolset(std::string const& ts)
{
this->GeneratorToolset = ts;
}
- ///! Get the name of the selected generator-specific toolset.
- std::string const& GetGeneratorToolset() const
- {
- return this->GeneratorToolset;
- }
-
const std::vector<std::string>& GetSourceExtensions() const
{
return this->SourceFileExtensions;
@@ -268,8 +256,7 @@ public:
* number provided may be negative in cases where a message is
* to be displayed without any progress percentage.
*/
- void SetProgressCallback(ProgressCallbackType f,
- void* clientData = CM_NULLPTR);
+ void SetProgressCallback(ProgressCallbackType f, void* clientData = nullptr);
///! this is called by generators to update the progress
void UpdateProgress(const char* msg, float prog);
diff --git a/Source/cmakemain.cxx b/Source/cmakemain.cxx
index da1fe6d64..a1dfc3e89 100644
--- a/Source/cmakemain.cxx
+++ b/Source/cmakemain.cxx
@@ -1,7 +1,7 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmConfigure.h"
+#include "cmake.h"
#include "cmAlgorithms.h"
#include "cmDocumentationEntry.h"
#include "cmGlobalGenerator.h"
@@ -9,7 +9,6 @@
#include "cmState.h"
#include "cmStateTypes.h"
#include "cmSystemTools.h"
-#include "cmake.h"
#include "cmcmd.h"
#ifdef CMAKE_BUILD_WITH_CMAKE
@@ -17,6 +16,12 @@
#include "cmDynamicLoader.h"
#endif
+#ifdef _WIN32
+#include <fcntl.h> /* _O_TEXT */
+#include <stdlib.h> /* _set_fmode, _fmode */
+#endif
+#include "cm_uv.h"
+
#include "cmsys/Encoding.hxx"
#if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
#include "cmsys/ConsoleBuf.hxx"
@@ -26,33 +31,24 @@
#include <string>
#include <vector>
-#ifdef CMAKE_USE_LIBUV
-#ifdef _WIN32
-#include <fcntl.h> /* _O_TEXT */
-#include <stdlib.h> /* _set_fmode, _fmode */
-#endif
-#include "cm_uv.h"
-#endif
-
#ifdef CMAKE_BUILD_WITH_CMAKE
static const char* cmDocumentationName[][2] = {
- { CM_NULLPTR, " cmake - Cross-Platform Makefile Generator." },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, " cmake - Cross-Platform Makefile Generator." },
+ { nullptr, nullptr }
};
static const char* cmDocumentationUsage[][2] = {
- { CM_NULLPTR, " cmake [options] <path-to-source>\n"
- " cmake [options] <path-to-existing-build>" },
- { CM_NULLPTR,
- "Specify a source directory to (re-)generate a build system for "
- "it in the current working directory. Specify an existing build "
- "directory to re-generate its build system." },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, " cmake [options] <path-to-source>\n"
+ " cmake [options] <path-to-existing-build>" },
+ { nullptr, "Specify a source directory to (re-)generate a build system for "
+ "it in the current working directory. Specify an existing build "
+ "directory to re-generate its build system." },
+ { nullptr, nullptr }
};
static const char* cmDocumentationUsageNote[][2] = {
- { CM_NULLPTR, "Run 'cmake --help' for more information." },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, "Run 'cmake --help' for more information." },
+ { nullptr, nullptr }
};
#define CMAKE_BUILD_OPTIONS \
@@ -88,7 +84,7 @@ static const char* cmDocumentationOptions[][2] = {
{ "--no-warn-unused-cli", "Don't warn about command line options." },
{ "--check-system-vars", "Find problems with variable usage in system "
"files." },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, nullptr }
};
#endif
@@ -107,14 +103,14 @@ static int do_build(int ac, char const* const* av);
static cmMakefile* cmakemainGetMakefile(void* clientdata)
{
- cmake* cm = (cmake*)clientdata;
+ cmake* cm = static_cast<cmake*>(clientdata);
if (cm && cm->GetDebugOutput()) {
cmGlobalGenerator* gg = cm->GetGlobalGenerator();
if (gg) {
return gg->GetCurrentMakefile();
}
}
- return CM_NULLPTR;
+ return nullptr;
}
static std::string cmakemainGetStack(void* clientdata)
@@ -172,7 +168,7 @@ int main(int ac, char const* const* av)
ac = args.argc();
av = args.argv();
-#if defined(CMAKE_USE_LIBUV) && defined(_WIN32)
+#if defined(_WIN32)
// Perform libuv one-time initialization now, and then un-do its
// global _fmode setting so that using libuv does not change the
// default file text/binary mode. See libuv issue 840.
@@ -198,9 +194,7 @@ int main(int ac, char const* const* av)
#ifdef CMAKE_BUILD_WITH_CMAKE
cmDynamicLoader::FlushCache();
#endif
-#ifdef CMAKE_USE_LIBUV
uv_loop_close(uv_default_loop());
-#endif
return ret;
}
@@ -310,30 +304,28 @@ int do_cmake(int ac, char const* const* av)
cmake cm(role);
cm.SetHomeDirectory("");
cm.SetHomeOutputDirectory("");
- cmSystemTools::SetMessageCallback(cmakemainMessageCallback, (void*)&cm);
- cm.SetProgressCallback(cmakemainProgressCallback, (void*)&cm);
+ cmSystemTools::SetMessageCallback(cmakemainMessageCallback, &cm);
+ cm.SetProgressCallback(cmakemainProgressCallback, &cm);
cm.SetWorkingMode(workingMode);
int res = cm.Run(args, view_only);
if (list_cached || list_all_cached) {
std::cout << "-- Cache values" << std::endl;
std::vector<std::string> keys = cm.GetState()->GetCacheEntryKeys();
- for (std::vector<std::string>::const_iterator it = keys.begin();
- it != keys.end(); ++it) {
- cmStateEnums::CacheEntryType t = cm.GetState()->GetCacheEntryType(*it);
+ for (std::string const& k : keys) {
+ cmStateEnums::CacheEntryType t = cm.GetState()->GetCacheEntryType(k);
if (t != cmStateEnums::INTERNAL && t != cmStateEnums::STATIC &&
t != cmStateEnums::UNINITIALIZED) {
const char* advancedProp =
- cm.GetState()->GetCacheEntryProperty(*it, "ADVANCED");
+ cm.GetState()->GetCacheEntryProperty(k, "ADVANCED");
if (list_all_cached || !advancedProp) {
if (list_help) {
std::cout << "// "
- << cm.GetState()->GetCacheEntryProperty(*it,
- "HELPSTRING")
+ << cm.GetState()->GetCacheEntryProperty(k, "HELPSTRING")
<< std::endl;
}
- std::cout << *it << ":" << cmState::CacheEntryTypeToString(t) << "="
- << cm.GetState()->GetCacheEntryValue(*it) << std::endl;
+ std::cout << k << ":" << cmState::CacheEntryTypeToString(t) << "="
+ << cm.GetState()->GetCacheEntryValue(k) << std::endl;
if (list_help) {
std::cout << std::endl;
}
@@ -381,7 +373,7 @@ static int do_build(int ac, char const* const* av)
hasTarget = true;
} else {
std::cerr << "'--target' may not be specified more than once.\n\n";
- dir = "";
+ dir.clear();
break;
}
} else if (strcmp(av[i], "--config") == 0) {
@@ -409,7 +401,7 @@ static int do_build(int ac, char const* const* av)
break;
default:
std::cerr << "Unknown argument " << av[i] << std::endl;
- dir = "";
+ dir.clear();
break;
}
}
@@ -426,8 +418,8 @@ static int do_build(int ac, char const* const* av)
}
cmake cm(cmake::RoleInternal);
- cmSystemTools::SetMessageCallback(cmakemainMessageCallback, (void*)&cm);
- cm.SetProgressCallback(cmakemainProgressCallback, (void*)&cm);
+ cmSystemTools::SetMessageCallback(cmakemainMessageCallback, &cm);
+ cm.SetProgressCallback(cmakemainProgressCallback, &cm);
return cm.Build(dir, target, config, nativeOptions, clean);
#endif
}
diff --git a/Source/cmakexbuild.cxx b/Source/cmakexbuild.cxx
index 72da456d4..20ead4785 100644
--- a/Source/cmakexbuild.cxx
+++ b/Source/cmakexbuild.cxx
@@ -47,7 +47,7 @@ int RunXCode(std::vector<const char*>& argv, bool& hitbug)
}
pipe = cmSystemTools::WaitForLine(cp, line, 100, out, err);
}
- cmsysProcess_WaitForExit(cp, 0);
+ cmsysProcess_WaitForExit(cp, nullptr);
if (cmsysProcess_GetState(cp) == cmsysProcess_State_Exited) {
return cmsysProcess_GetExitValue(cp);
}
@@ -64,7 +64,7 @@ int main(int ac, char* av[])
for (int i = 1; i < ac; i++) {
argv.push_back(av[i]);
}
- argv.push_back(0);
+ argv.push_back(nullptr);
bool hitbug = true;
int ret = 0;
while (hitbug) {
diff --git a/Source/cmcmd.cxx b/Source/cmcmd.cxx
index d5b086174..69339b448 100644
--- a/Source/cmcmd.cxx
+++ b/Source/cmcmd.cxx
@@ -12,16 +12,12 @@
#include "cmSystemTools.h"
#include "cmUtils.hxx"
#include "cmVersion.h"
-#include "cm_auto_ptr.hxx"
#include "cmake.h"
-#if defined(HAVE_SERVER_MODE) && HAVE_SERVER_MODE
-#include "cmServer.h"
-#include "cmServerConnection.h"
-#endif
-
#if defined(CMAKE_BUILD_WITH_CMAKE)
#include "cmDependsFortran.h" // For -E cmake_copy_f90_mod callback.
+#include "cmServer.h"
+#include "cmServerConnection.h"
#endif
#if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32)
@@ -32,18 +28,21 @@
#include "cmVisualStudioWCEPlatformParser.h"
#endif
-#include "cmConfigure.h"
#include "cmsys/Directory.hxx"
#include "cmsys/FStream.hxx"
#include "cmsys/Process.h"
#include "cmsys/Terminal.h"
#include <algorithm>
#include <iostream>
+#include <memory> // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
+#include <string.h>
#include <time.h>
+class cmConnection;
+
int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
std::vector<std::string>::const_iterator argEnd);
int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
@@ -88,6 +87,11 @@ void CMakeCommandUsage(const char* program)
<< " environment - display the current environment\n"
<< " make_directory <dir>... - create parent and <dir> directories\n"
<< " md5sum <file>... - create MD5 checksum of files\n"
+ << " sha1sum <file>... - create SHA1 checksum of files\n"
+ << " sha224sum <file>... - create SHA224 checksum of files\n"
+ << " sha256sum <file>... - create SHA256 checksum of files\n"
+ << " sha384sum <file>... - create SHA384 checksum of files\n"
+ << " sha512sum <file>... - create SHA512 checksum of files\n"
<< " remove [-f] <file>... - remove the file(s), use -f to force "
"it\n"
<< " remove_directory dir - remove a directory and its contents\n"
@@ -154,6 +158,291 @@ static bool cmTarFilesFrom(std::string const& file,
return true;
}
+static int HandleIWYU(const std::string& runCmd,
+ const std::string& /* sourceFile */,
+ const std::vector<std::string>& orig_cmd)
+{
+ // Construct the iwyu command line by taking what was given
+ // and adding all the arguments we give to the compiler.
+ std::vector<std::string> iwyu_cmd;
+ cmSystemTools::ExpandListArgument(runCmd, iwyu_cmd, true);
+ iwyu_cmd.insert(iwyu_cmd.end(), orig_cmd.begin() + 1, orig_cmd.end());
+ // Run the iwyu command line. Capture its stderr and hide its stdout.
+ // Ignore its return code because the tool always returns non-zero.
+ std::string stdErr;
+ int ret;
+ if (!cmSystemTools::RunSingleCommand(iwyu_cmd, nullptr, &stdErr, &ret,
+ nullptr, cmSystemTools::OUTPUT_NONE)) {
+ std::cerr << "Error running '" << iwyu_cmd[0] << "': " << stdErr << "\n";
+ return 1;
+ }
+ // Warn if iwyu reported anything.
+ if (stdErr.find("should remove these lines:") != std::string::npos ||
+ stdErr.find("should add these lines:") != std::string::npos) {
+ std::cerr << "Warning: include-what-you-use reported diagnostics:\n"
+ << stdErr << "\n";
+ }
+ // always return 0 we don't want to break the compile
+ return 0;
+}
+
+static int HandleTidy(const std::string& runCmd, const std::string& sourceFile,
+ const std::vector<std::string>& orig_cmd)
+{
+ // Construct the clang-tidy command line by taking what was given
+ // and adding our compiler command line. The clang-tidy tool will
+ // automatically skip over the compiler itself and extract the
+ // options.
+ int ret;
+ std::vector<std::string> tidy_cmd;
+ cmSystemTools::ExpandListArgument(runCmd, tidy_cmd, true);
+ tidy_cmd.push_back(sourceFile);
+ tidy_cmd.push_back("--");
+ tidy_cmd.insert(tidy_cmd.end(), orig_cmd.begin(), orig_cmd.end());
+
+ // Run the tidy command line. Capture its stdout and hide its stderr.
+ std::string stdOut;
+ std::string stdErr;
+ if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret,
+ nullptr, cmSystemTools::OUTPUT_NONE)) {
+ std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr << "\n";
+ return 1;
+ }
+ // Output the stdout from clang-tidy to stderr
+ std::cerr << stdOut;
+ // If clang-tidy exited with an error do the same.
+ if (ret != 0) {
+ std::cerr << stdErr;
+ }
+ return ret;
+}
+
+static int HandleLWYU(const std::string& runCmd,
+ const std::string& /* sourceFile */,
+ const std::vector<std::string>&)
+{
+ // Construct the ldd -r -u (link what you use lwyu) command line
+ // ldd -u -r lwuy target
+ std::vector<std::string> lwyu_cmd;
+ lwyu_cmd.push_back("ldd");
+ lwyu_cmd.push_back("-u");
+ lwyu_cmd.push_back("-r");
+ lwyu_cmd.push_back(runCmd);
+
+ // Run the ldd -u -r command line.
+ // Capture its stdout and hide its stderr.
+ // Ignore its return code because the tool always returns non-zero
+ // if there are any warnings, but we just want to warn.
+ std::string stdOut;
+ std::string stdErr;
+ int ret;
+ if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret,
+ nullptr, cmSystemTools::OUTPUT_NONE)) {
+ std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr << "\n";
+ return 1;
+ }
+
+ // Output the stdout from ldd -r -u to stderr
+ // Warn if lwyu reported anything.
+ if (stdOut.find("Unused direct dependencies:") != std::string::npos) {
+ std::cerr << "Warning: " << stdOut;
+ }
+ return 0;
+}
+
+static int HandleCppLint(const std::string& runCmd,
+ const std::string& sourceFile,
+ const std::vector<std::string>&)
+{
+ // Construct the cpplint command line.
+ std::vector<std::string> cpplint_cmd;
+ cmSystemTools::ExpandListArgument(runCmd, cpplint_cmd, true);
+ cpplint_cmd.push_back(sourceFile);
+
+ // Run the cpplint command line. Capture its output.
+ std::string stdOut;
+ int ret;
+ if (!cmSystemTools::RunSingleCommand(cpplint_cmd, &stdOut, &stdOut, &ret,
+ nullptr, cmSystemTools::OUTPUT_NONE)) {
+ std::cerr << "Error running '" << cpplint_cmd[0] << "': " << stdOut
+ << "\n";
+ return 1;
+ }
+
+ // Output the output from cpplint to stderr
+ std::cerr << stdOut;
+ return ret;
+}
+
+static int HandleCppCheck(const std::string& runCmd,
+ const std::string& sourceFile,
+ const std::vector<std::string>& orig_cmd)
+{
+ // Construct the cpplint command line.
+ std::vector<std::string> cppcheck_cmd;
+ cmSystemTools::ExpandListArgument(runCmd, cppcheck_cmd, true);
+ // extract all the -D, -U, and -I options from the compile line
+ for (auto const& opt : orig_cmd) {
+ if (opt.size() > 2) {
+ if ((opt[0] == '-') &&
+ ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
+ cppcheck_cmd.push_back(opt);
+// convert cl / options to - options if needed
+#if defined(_WIN32)
+ } else if ((opt[0] == '/') &&
+ ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
+ std::string optcopy = opt;
+ optcopy[0] = '-';
+ cppcheck_cmd.push_back(optcopy);
+#endif
+ }
+ }
+ }
+ // add the source file
+ cppcheck_cmd.push_back(sourceFile);
+
+ // Run the cpplint command line. Capture its output.
+ std::string stdOut;
+ std::string stdErr;
+ int ret;
+ if (!cmSystemTools::RunSingleCommand(cppcheck_cmd, &stdOut, &stdErr, &ret,
+ nullptr, cmSystemTools::OUTPUT_NONE)) {
+ std::cerr << "Error running '" << cppcheck_cmd[0] << "': " << stdOut
+ << "\n";
+ return 1;
+ }
+ std::cerr << stdOut;
+ // Output the output from cpplint to stderr
+ if (stdErr.find("(error)") != std::string::npos ||
+ stdErr.find("(warning)") != std::string::npos ||
+ stdErr.find("(style)") != std::string::npos ||
+ stdErr.find("(performance)") != std::string::npos ||
+ stdErr.find("(portability)") != std::string::npos ||
+ stdErr.find("(information)") != std::string::npos) {
+ std::cerr << "Warning: cppcheck reported diagnostics:\n";
+ }
+ std::cerr << stdErr;
+ // ignore errors so build continues
+ return 0;
+}
+
+typedef int (*CoCompileHandler)(const std::string&, const std::string&,
+ const std::vector<std::string>&);
+
+struct CoCompiler
+{
+ const char* Option;
+ CoCompileHandler Handler;
+ bool NoOriginalCommand;
+};
+
+static CoCompiler CoCompilers[] = { // Table of options and handlers.
+ { "--cppcheck=", HandleCppCheck, false },
+ { "--cpplint=", HandleCppLint, false },
+ { "--iwyu=", HandleIWYU, false },
+ { "--lwyu=", HandleLWYU, true },
+ { "--tidy=", HandleTidy, false }
+};
+
+struct CoCompileJob
+{
+ std::string Command;
+ CoCompileHandler Handler;
+};
+
+// called when args[0] == "__run_co_compile"
+int cmcmd::HandleCoCompileCommands(std::vector<std::string>& args)
+{
+ std::vector<CoCompileJob> jobs;
+ std::string sourceFile; // store --source=
+
+ // Default is to run the original command found after -- if the option
+ // does not need to do that, it should be specified here, currently only
+ // lwyu does that.
+ bool runOriginalCmd = true;
+
+ std::vector<std::string> orig_cmd;
+ bool doing_options = true;
+ for (std::string::size_type i = 2; i < args.size(); ++i) {
+ std::string const& arg = args[i];
+ // if the arg is -- then the rest of the args after
+ // go into orig_cmd
+ if (arg == "--") {
+ doing_options = false;
+ } else if (doing_options) {
+ bool optionFound = false;
+ for (CoCompiler const* cc = cmArrayBegin(CoCompilers);
+ cc != cmArrayEnd(CoCompilers); ++cc) {
+ size_t optionLen = strlen(cc->Option);
+ if (arg.compare(0, optionLen, cc->Option) == 0) {
+ optionFound = true;
+ CoCompileJob job;
+ job.Command = arg.substr(optionLen);
+ job.Handler = cc->Handler;
+ jobs.push_back(std::move(job));
+ if (cc->NoOriginalCommand) {
+ runOriginalCmd = false;
+ }
+ }
+ }
+ if (cmHasLiteralPrefix(arg, "--source=")) {
+ sourceFile = arg.substr(9);
+ optionFound = true;
+ }
+ // if it was not a co-compiler or --source then error
+ if (!optionFound) {
+ std::cerr << "__run_co_compile given unknown argument: " << arg
+ << "\n";
+ return 1;
+ }
+ } else { // if not doing_options then push to orig_cmd
+ orig_cmd.push_back(arg);
+ }
+ }
+ if (jobs.empty()) {
+ std::cerr << "__run_co_compile missing command to run. "
+ "Looking for one or more of the following:\n";
+ for (CoCompiler const* cc = cmArrayBegin(CoCompilers);
+ cc != cmArrayEnd(CoCompilers); ++cc) {
+ std::cerr << cc->Option << "\n";
+ }
+ return 1;
+ }
+
+ if (runOriginalCmd && orig_cmd.empty()) {
+ std::cerr << "__run_co_compile missing compile command after --\n";
+ return 1;
+ }
+
+ for (CoCompileJob const& job : jobs) {
+ // call the command handler here
+ int ret = job.Handler(job.Command, sourceFile, orig_cmd);
+
+ // if the command returns non-zero then return and fail.
+ // for commands that do not want to break the build, they should return
+ // 0 no matter what.
+ if (ret != 0) {
+ return ret;
+ }
+ }
+
+ // if there is no original command to run return now
+ if (!runOriginalCmd) {
+ return 0;
+ }
+
+ // Now run the real compiler command and return its result value
+ int ret;
+ if (!cmSystemTools::RunSingleCommand(orig_cmd, nullptr, nullptr, &ret,
+ nullptr,
+ cmSystemTools::OUTPUT_PASSTHROUGH)) {
+ std::cerr << "Error running '" << orig_cmd[0] << "'\n";
+ return 1;
+ }
+ // return the return value from the original compiler command
+ return ret;
+}
+
int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
{
// IF YOU ADD A NEW COMMAND, DOCUMENT IT ABOVE and in cmakemain.cxx
@@ -277,181 +566,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
return 0;
}
#endif
- // run include what you use command and then run the compile
- // command. This is an internal undocumented option and should
- // only be used by CMake itself when running iwyu.
- if (args[1] == "__run_iwyu") {
- if (args.size() < 3) {
- std::cerr << "__run_iwyu Usage: -E __run_iwyu [--iwyu=/path/iwyu]"
- " [--cpplint=/path/cpplint] [--tidy=/path/tidy]"
- " -- compile command\n";
- return 1;
- }
- bool doing_options = true;
- std::vector<std::string> orig_cmd;
- std::string iwyu;
- std::string tidy;
- std::string sourceFile;
- std::string lwyu;
- std::string cpplint;
- for (std::string::size_type cc = 2; cc < args.size(); cc++) {
- std::string const& arg = args[cc];
- if (arg == "--") {
- doing_options = false;
- } else if (doing_options && cmHasLiteralPrefix(arg, "--iwyu=")) {
- iwyu = arg.substr(7);
- } else if (doing_options && cmHasLiteralPrefix(arg, "--tidy=")) {
- tidy = arg.substr(7);
- } else if (doing_options && cmHasLiteralPrefix(arg, "--source=")) {
- sourceFile = arg.substr(9);
- } else if (doing_options && cmHasLiteralPrefix(arg, "--lwyu=")) {
- lwyu = arg.substr(7);
- } else if (doing_options && cmHasLiteralPrefix(arg, "--cpplint=")) {
- cpplint = arg.substr(10);
- } else if (doing_options) {
- std::cerr << "__run_iwyu given unknown argument: " << arg << "\n";
- return 1;
- } else {
- orig_cmd.push_back(arg);
- }
- }
- if (tidy.empty() && iwyu.empty() && lwyu.empty() && cpplint.empty()) {
- std::cerr << "__run_iwyu missing --cpplint=, --iwyu=, --lwyu=, and/or"
- " --tidy=\n";
- return 1;
- }
- if ((!cpplint.empty() || !tidy.empty()) && sourceFile.empty()) {
- std::cerr << "__run_iwyu --cpplint= and/or __run_iwyu --tidy="
- " require --source=\n";
- return 1;
- }
- if (orig_cmd.empty() && lwyu.empty()) {
- std::cerr << "__run_iwyu missing compile command after --\n";
- return 1;
- }
-
- int ret = 0;
-
- if (!iwyu.empty()) {
- // Construct the iwyu command line by taking what was given
- // and adding all the arguments we give to the compiler.
- std::vector<std::string> iwyu_cmd;
- cmSystemTools::ExpandListArgument(iwyu, iwyu_cmd, true);
- iwyu_cmd.insert(iwyu_cmd.end(), orig_cmd.begin() + 1, orig_cmd.end());
-
- // Run the iwyu command line. Capture its stderr and hide its stdout.
- // Ignore its return code because the tool always returns non-zero.
- std::string stdErr;
- if (!cmSystemTools::RunSingleCommand(iwyu_cmd, CM_NULLPTR, &stdErr,
- &ret, CM_NULLPTR,
- cmSystemTools::OUTPUT_NONE)) {
- std::cerr << "Error running '" << iwyu_cmd[0] << "': " << stdErr
- << "\n";
- return 1;
- }
-
- // Warn if iwyu reported anything.
- if (stdErr.find("should remove these lines:") != std::string::npos ||
- stdErr.find("should add these lines:") != std::string::npos) {
- std::cerr << "Warning: include-what-you-use reported diagnostics:\n"
- << stdErr << "\n";
- }
- }
-
- if (!tidy.empty()) {
- // Construct the clang-tidy command line by taking what was given
- // and adding our compiler command line. The clang-tidy tool will
- // automatically skip over the compiler itself and extract the
- // options.
- std::vector<std::string> tidy_cmd;
- cmSystemTools::ExpandListArgument(tidy, tidy_cmd, true);
- tidy_cmd.push_back(sourceFile);
- tidy_cmd.push_back("--");
- tidy_cmd.insert(tidy_cmd.end(), orig_cmd.begin(), orig_cmd.end());
-
- // Run the tidy command line. Capture its stdout and hide its stderr.
- std::string stdOut;
- std::string stdErr;
- if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret,
- CM_NULLPTR,
- cmSystemTools::OUTPUT_NONE)) {
- std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr
- << "\n";
- return 1;
- }
- // Output the stdout from clang-tidy to stderr
- std::cerr << stdOut;
- // If clang-tidy exited with an error do the same.
- if (ret != 0) {
- std::cerr << stdErr;
- return ret;
- }
- }
- if (!lwyu.empty()) {
- // Construct the ldd -r -u (link what you use lwyu) command line
- // ldd -u -r lwuy target
- std::vector<std::string> lwyu_cmd;
- lwyu_cmd.push_back("ldd");
- lwyu_cmd.push_back("-u");
- lwyu_cmd.push_back("-r");
- lwyu_cmd.push_back(lwyu);
-
- // Run the ldd -u -r command line.
- // Capture its stdout and hide its stderr.
- // Ignore its return code because the tool always returns non-zero
- // if there are any warnings, but we just want to warn.
- std::string stdOut;
- std::string stdErr;
- if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret,
- CM_NULLPTR,
- cmSystemTools::OUTPUT_NONE)) {
- std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr
- << "\n";
- return 1;
- }
-
- // Output the stdout from ldd -r -u to stderr
- // Warn if lwyu reported anything.
- if (stdOut.find("Unused direct dependencies:") != std::string::npos) {
- std::cerr << "Warning: " << stdOut;
- }
- }
-
- if (!cpplint.empty()) {
- // Construct the cpplint command line.
- std::vector<std::string> cpplint_cmd;
- cmSystemTools::ExpandListArgument(cpplint, cpplint_cmd, true);
- cpplint_cmd.push_back(sourceFile);
-
- // Run the cpplint command line. Capture its output.
- std::string stdOut;
- if (!cmSystemTools::RunSingleCommand(cpplint_cmd, &stdOut, &stdOut,
- &ret, CM_NULLPTR,
- cmSystemTools::OUTPUT_NONE)) {
- std::cerr << "Error running '" << cpplint_cmd[0] << "': " << stdOut
- << "\n";
- return 1;
- }
-
- // Output the output from cpplint to stderr
- std::cerr << stdOut;
-
- // If cpplint exited with an error do the same.
- if (ret != 0) {
- return ret;
- }
- }
-
- ret = 0;
- // Now run the real compiler command and return its result value.
- if (lwyu.empty() &&
- !cmSystemTools::RunSingleCommand(
- orig_cmd, CM_NULLPTR, CM_NULLPTR, &ret, CM_NULLPTR,
- cmSystemTools::OUTPUT_PASSTHROUGH)) {
- std::cerr << "Error running '" << orig_cmd[0] << "'\n";
- return 1;
- }
- return ret;
+ if (args[1] == "__run_co_compile") {
+ return cmcmd::HandleCoCompileCommands(args);
}
// Echo string
@@ -497,8 +613,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
// Execute command from remaining arguments.
std::vector<std::string> cmd(ai, ae);
int retval;
- if (cmSystemTools::RunSingleCommand(cmd, CM_NULLPTR, CM_NULLPTR, &retval,
- CM_NULLPTR,
+ if (cmSystemTools::RunSingleCommand(cmd, nullptr, nullptr, &retval,
+ nullptr,
cmSystemTools::OUTPUT_PASSTHROUGH)) {
return retval;
}
@@ -584,7 +700,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
return 1;
}
cmake cm(cmake::RoleInternal);
-#if defined(HAVE_SERVER_MODE) && HAVE_SERVER_MODE
+#if defined(CMAKE_BUILD_WITH_CMAKE)
std::cout << cm.ReportCapabilities(true);
#else
std::cout << cm.ReportCapabilities(false);
@@ -623,7 +739,7 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
time(&time_start);
clock_start = clock();
int ret = 0;
- cmSystemTools::RunSingleCommand(command, CM_NULLPTR, CM_NULLPTR, &ret);
+ cmSystemTools::RunSingleCommand(command, nullptr, nullptr, &ret);
clock_finish = clock();
time(&time_finish);
@@ -641,24 +757,28 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
// Command to calculate the md5sum of a file
if (args[1] == "md5sum" && args.size() >= 3) {
- char md5out[32];
- int retval = 0;
- for (std::string::size_type cc = 2; cc < args.size(); cc++) {
- const char* filename = args[cc].c_str();
- // Cannot compute md5sum of a directory
- if (cmSystemTools::FileIsDirectory(filename)) {
- std::cerr << "Error: " << filename << " is a directory" << std::endl;
- retval++;
- } else if (!cmSystemTools::ComputeFileMD5(filename, md5out)) {
- // To mimic md5sum behavior in a shell:
- std::cerr << filename << ": No such file or directory" << std::endl;
- retval++;
- } else {
- std::cout << std::string(md5out, 32) << " " << filename
- << std::endl;
- }
- }
- return retval;
+ return HashSumFile(args, cmCryptoHash::AlgoMD5);
+ }
+
+ // Command to calculate the sha1sum of a file
+ if (args[1] == "sha1sum" && args.size() >= 3) {
+ return HashSumFile(args, cmCryptoHash::AlgoSHA1);
+ }
+
+ if (args[1] == "sha224sum" && args.size() >= 3) {
+ return HashSumFile(args, cmCryptoHash::AlgoSHA224);
+ }
+
+ if (args[1] == "sha256sum" && args.size() >= 3) {
+ return HashSumFile(args, cmCryptoHash::AlgoSHA256);
+ }
+
+ if (args[1] == "sha384sum" && args.size() >= 3) {
+ return HashSumFile(args, cmCryptoHash::AlgoSHA384);
+ }
+
+ if (args[1] == "sha512sum" && args.size() >= 3) {
+ return HashSumFile(args, cmCryptoHash::AlgoSHA512);
}
// Command to change directory and run a program.
@@ -675,8 +795,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
int retval = 0;
int timeout = 0;
if (cmSystemTools::RunSingleCommand(
- command.c_str(), CM_NULLPTR, CM_NULLPTR, &retval,
- directory.c_str(), cmSystemTools::OUTPUT_PASSTHROUGH, timeout)) {
+ command.c_str(), nullptr, nullptr, &retval, directory.c_str(),
+ cmSystemTools::OUTPUT_PASSTHROUGH, timeout)) {
return retval;
}
@@ -820,8 +940,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
snapshot.GetDirectory().SetCurrentBinary(startOutDir);
snapshot.GetDirectory().SetCurrentSource(startDir);
- CM_AUTO_PTR<cmMakefile> mf(new cmMakefile(ggd, snapshot));
- CM_AUTO_PTR<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(mf.get()));
+ cmMakefile mf(ggd, snapshot);
+ std::unique_ptr<cmLocalGenerator> lgd(ggd->CreateLocalGenerator(&mf));
// Actually scan dependencies.
return lgd->UpdateDependencies(depInfo.c_str(), verbose, color) ? 0
@@ -1012,8 +1132,8 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
return 1;
}
}
-#if defined(HAVE_SERVER_MODE) && HAVE_SERVER_MODE
- cmServerConnection* conn;
+#if defined(CMAKE_BUILD_WITH_CMAKE)
+ cmConnection* conn;
if (isDebug) {
conn = new cmServerStdIoConnection;
} else {
@@ -1074,6 +1194,33 @@ int cmcmd::ExecuteCMakeCommand(std::vector<std::string>& args)
return 1;
}
+int cmcmd::HashSumFile(std::vector<std::string>& args, cmCryptoHash::Algo algo)
+{
+ if (args.size() < 3) {
+ return -1;
+ }
+ int retval = 0;
+
+ for (std::string::size_type cc = 2; cc < args.size(); cc++) {
+ const char* filename = args[cc].c_str();
+ // Cannot compute sum of a directory
+ if (cmSystemTools::FileIsDirectory(filename)) {
+ std::cerr << "Error: " << filename << " is a directory" << std::endl;
+ retval++;
+ } else {
+ std::string value = cmSystemTools::ComputeFileHash(filename, algo);
+ if (value.empty()) {
+ // To mimic "md5sum/shasum" behavior in a shell:
+ std::cerr << filename << ": No such file or directory" << std::endl;
+ retval++;
+ } else {
+ std::cout << value << " " << filename << std::endl;
+ }
+ }
+ }
+ return retval;
+}
+
int cmcmd::SymlinkLibrary(std::vector<std::string>& args)
{
int result = 0;
@@ -1277,7 +1424,7 @@ int cmcmd::ExecuteLinkScript(std::vector<std::string>& args)
}
// Setup this command line.
- const char* cmd[2] = { command.c_str(), CM_NULLPTR };
+ const char* cmd[2] = { command.c_str(), nullptr };
cmsysProcess_SetCommand(cp, cmd);
// Report the command if verbose output is enabled.
@@ -1287,7 +1434,7 @@ int cmcmd::ExecuteLinkScript(std::vector<std::string>& args)
// Run the command and wait for it to exit.
cmsysProcess_Execute(cp);
- cmsysProcess_WaitForExit(cp, CM_NULLPTR);
+ cmsysProcess_WaitForExit(cp, nullptr);
// Report failure if any.
switch (cmsysProcess_GetState(cp)) {
@@ -1375,24 +1522,23 @@ private:
// For visual studio 2005 and newer manifest files need to be embedded into
// exe and dll's. This code does that in such a way that incremental linking
// still works.
-int cmcmd::VisualStudioLink(std::vector<std::string>& args, int type)
+int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type)
{
if (args.size() < 2) {
return -1;
}
const bool verbose = cmSystemTools::HasEnv("VERBOSE");
std::vector<std::string> expandedArgs;
- for (std::vector<std::string>::iterator i = args.begin(); i != args.end();
- ++i) {
+ for (std::string const& i : args) {
// check for nmake temporary files
- if ((*i)[0] == '@' && i->find("@CMakeFiles") != 0) {
- cmsys::ifstream fin(i->substr(1).c_str());
+ if (i[0] == '@' && i.find("@CMakeFiles") != 0) {
+ cmsys::ifstream fin(i.substr(1).c_str());
std::string line;
while (cmSystemTools::GetLineFromStream(fin, line)) {
cmSystemTools::ParseWindowsCommandLine(line.c_str(), expandedArgs);
}
} else {
- expandedArgs.push_back(*i);
+ expandedArgs.push_back(i);
}
}
@@ -1403,8 +1549,38 @@ int cmcmd::VisualStudioLink(std::vector<std::string>& args, int type)
return vsLink.Link();
}
+enum NumberFormat
+{
+ FORMAT_DECIMAL,
+ FORMAT_HEX
+};
+struct NumberFormatter
+{
+ NumberFormat Format;
+ int Value;
+ NumberFormatter(NumberFormat format, int value)
+ : Format(format)
+ , Value(value)
+ {
+ }
+};
+std::ostream& operator<<(std::ostream& stream,
+ NumberFormatter const& formatter)
+{
+ auto const& flags = stream.flags();
+ if (formatter.Format == FORMAT_DECIMAL) {
+ stream << std::dec << formatter.Value;
+ } else {
+ stream << "0x" << std::hex << formatter.Value;
+ }
+ stream.flags(flags);
+ return stream;
+}
+
static bool RunCommand(const char* comment, std::vector<std::string>& command,
- bool verbose, int* retCodeOut = CM_NULLPTR)
+ bool verbose, NumberFormat exitFormat,
+ int* retCodeOut = nullptr,
+ bool (*retCodeOkay)(int) = nullptr)
{
if (verbose) {
std::cout << comment << ":\n";
@@ -1412,32 +1588,32 @@ static bool RunCommand(const char* comment, std::vector<std::string>& command,
}
std::string output;
int retCode = 0;
- // use rc command to create .res file
- bool res =
- cmSystemTools::RunSingleCommand(command, &output, &output, &retCode,
- CM_NULLPTR, cmSystemTools::OUTPUT_NONE);
- // always print the output of the command, unless
- // it is the dumb rc command banner, but if the command
- // returned an error code then print the output anyway as
- // the banner may be mixed with some other important information.
- if (output.find("Resource Compiler Version") == std::string::npos || !res ||
- retCode) {
- std::cout << output;
- }
- if (!res) {
- std::cout << comment << " failed to run." << std::endl;
- return false;
- }
- // if retCodeOut is requested then always return true
- // and set the retCodeOut to retCode
+ bool commandResult = cmSystemTools::RunSingleCommand(
+ command, &output, &output, &retCode, nullptr, cmSystemTools::OUTPUT_NONE);
+ bool const retCodeSuccess =
+ retCode == 0 || (retCodeOkay && retCodeOkay(retCode));
+ bool const success = commandResult && retCodeSuccess;
if (retCodeOut) {
- *retCodeOut = retCode;
- return true;
+ if (commandResult || !retCodeSuccess) {
+ *retCodeOut = retCode;
+ } else {
+ *retCodeOut = -1;
+ }
}
- if (retCode != 0) {
- std::cout << comment << " failed. with " << retCode << "\n";
+ if (!success) {
+ std::cout << comment << ": command \"" << cmJoin(command, " ")
+ << "\" failed (exit code "
+ << NumberFormatter(exitFormat, retCode)
+ << ") with the following output:\n"
+ << output;
+ } else {
+ // always print the output of the command, unless
+ // it is the dumb rc command banner
+ if (output.find("Resource Compiler Version") == std::string::npos) {
+ std::cout << output;
+ }
}
- return retCode == 0;
+ return success;
}
bool cmVSLink::Parse(std::vector<std::string>::const_iterator argBeg,
@@ -1535,6 +1711,13 @@ int cmVSLink::Link()
return LinkNonIncremental();
}
+static bool mtRetIsUpdate(int mtRet)
+{
+ // 'mt /notify_update' returns a special value (differing between
+ // Windows and POSIX hosts) when it updated the manifest file.
+ return mtRet == 0x41020001 || mtRet == 0xbb;
+}
+
int cmVSLink::LinkIncremental()
{
// This follows the steps listed here:
@@ -1587,10 +1770,10 @@ int cmVSLink::LinkIncremental()
// Compile the resource file.
std::vector<std::string> rcCommand;
- rcCommand.push_back(cmSystemTools::FindProgram("rc.exe"));
+ rcCommand.push_back("rc");
rcCommand.push_back("/fo" + this->ManifestFileRes);
rcCommand.push_back(this->ManifestFileRC);
- if (!RunCommand("RC Pass 1", rcCommand, this->Verbose)) {
+ if (!RunCommand("RC Pass 1", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
return -1;
}
@@ -1598,26 +1781,28 @@ int cmVSLink::LinkIncremental()
this->LinkCommand.push_back(this->ManifestFileRes);
// Run the link command (possibly generates intermediate manifest).
- if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose)) {
+ if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose,
+ FORMAT_DECIMAL)) {
return -1;
}
// Run the manifest tool to create the final manifest.
int mtRet = this->RunMT("/out:" + this->ManifestFile, true);
- // If mt returns 1090650113 (or 187 on a posix host) then it updated the
- // manifest file so we need to embed it again. Otherwise we are done.
- if (mtRet != 1090650113 && mtRet != 187) {
+ // If mt returns a special value then it updated the manifest file so
+ // we need to embed it again. Otherwise we are done.
+ if (!mtRetIsUpdate(mtRet)) {
return mtRet;
}
// Compile the resource file again.
- if (!RunCommand("RC Pass 2", rcCommand, this->Verbose)) {
+ if (!RunCommand("RC Pass 2", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
return -1;
}
// Link incrementally again to use the updated resource.
- if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose)) {
+ if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose,
+ FORMAT_DECIMAL)) {
return -1;
}
return 0;
@@ -1626,7 +1811,7 @@ int cmVSLink::LinkIncremental()
int cmVSLink::LinkNonIncremental()
{
// Run the link command (possibly generates intermediate manifest).
- if (!RunCommand("LINK", this->LinkCommand, this->Verbose)) {
+ if (!RunCommand("LINK", this->LinkCommand, this->Verbose, FORMAT_DECIMAL)) {
return -1;
}
@@ -1644,7 +1829,7 @@ int cmVSLink::LinkNonIncremental()
int cmVSLink::RunMT(std::string const& out, bool notify)
{
std::vector<std::string> mtCommand;
- mtCommand.push_back(cmSystemTools::FindProgram("mt.exe"));
+ mtCommand.push_back("mt");
mtCommand.push_back("/nologo");
mtCommand.push_back("/manifest");
if (this->LinkGeneratesManifest) {
@@ -1659,7 +1844,8 @@ int cmVSLink::RunMT(std::string const& out, bool notify)
mtCommand.push_back("/notify_update");
}
int mtRet = 0;
- if (!RunCommand("MT", mtCommand, this->Verbose, &mtRet)) {
+ if (!RunCommand("MT", mtCommand, this->Verbose, FORMAT_HEX, &mtRet,
+ mtRetIsUpdate)) {
return -1;
}
return mtRet;
diff --git a/Source/cmcmd.h b/Source/cmcmd.h
index 929f1ae47..d1e03d01f 100644
--- a/Source/cmcmd.h
+++ b/Source/cmcmd.h
@@ -4,6 +4,7 @@
#define cmcmd_h
#include "cmConfigure.h" // IWYU pragma: keep
+#include "cmCryptoHash.h"
#include <string>
#include <vector>
@@ -18,6 +19,9 @@ public:
static int ExecuteCMakeCommand(std::vector<std::string>&);
protected:
+ static int HandleCoCompileCommands(std::vector<std::string>& args);
+ static int HashSumFile(std::vector<std::string>& args,
+ cmCryptoHash::Algo algo);
static int SymlinkLibrary(std::vector<std::string>& args);
static int SymlinkExecutable(std::vector<std::string>& args);
static bool SymlinkInternal(std::string const& file,
@@ -26,7 +30,7 @@ protected:
static int ExecuteLinkScript(std::vector<std::string>& args);
static int WindowsCEEnvironment(const char* version,
const std::string& name);
- static int VisualStudioLink(std::vector<std::string>& args, int type);
+ static int VisualStudioLink(std::vector<std::string> const& args, int type);
};
#endif
diff --git a/Source/ctest.cxx b/Source/ctest.cxx
index 84e815d1d..f6466fad7 100644
--- a/Source/ctest.cxx
+++ b/Source/ctest.cxx
@@ -1,6 +1,5 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include "cmConfigure.h"
#include "CTest/cmCTestLaunch.h"
#include "CTest/cmCTestScriptHandler.h"
@@ -18,13 +17,13 @@
#include <vector>
static const char* cmDocumentationName[][2] = {
- { CM_NULLPTR, " ctest - Testing driver provided by CMake." },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, " ctest - Testing driver provided by CMake." },
+ { nullptr, nullptr }
};
-static const char* cmDocumentationUsage[][2] = { { CM_NULLPTR,
+static const char* cmDocumentationUsage[][2] = { { nullptr,
" ctest [options]" },
- { CM_NULLPTR, CM_NULLPTR } };
+ { nullptr, nullptr } };
static const char* cmDocumentationOptions[][2] = {
{ "-C <cfg>, --build-config <cfg>", "Choose configuration to test." },
@@ -83,6 +82,8 @@ static const char* cmDocumentationOptions[][2] = {
{ "--max-width <width>", "Set the max width for a test name to output" },
{ "--interactive-debug-mode [0|1]", "Set the interactive mode to 0 or 1." },
{ "--no-label-summary", "Disable timing summary information for labels." },
+ { "--no-subproject-summary", "Disable timing summary information for "
+ "subprojects." },
{ "--build-and-test", "Configure, build and run a test." },
{ "--build-target", "Specify a specific target to build." },
{ "--build-nocmake", "Run the build without running cmake first." },
@@ -118,7 +119,7 @@ static const char* cmDocumentationOptions[][2] = {
{ "--http1.0", "Submit using HTTP 1.0." },
{ "--no-compress-output", "Do not compress test output when submitting." },
{ "--print-labels", "Print all available test labels." },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, nullptr }
};
// this is a test driver program for cmCTest.
@@ -185,6 +186,7 @@ int main(int argc, char const* const* argv)
// copy the args to a vector
std::vector<std::string> args;
+ args.reserve(argc);
for (int i = 0; i < argc; ++i) {
args.push_back(argv[i]);
}
diff --git a/Source/kwsys/.gitattributes b/Source/kwsys/.gitattributes
deleted file mode 100644
index 7065eb5cb..000000000
--- a/Source/kwsys/.gitattributes
+++ /dev/null
@@ -1,13 +0,0 @@
-.git* export-ignore
-
-*.c kwsys-c-style
-*.c.in kwsys-c-style
-*.cxx kwsys-c-style
-*.h kwsys-c-style
-*.h.in kwsys-c-style
-*.hxx kwsys-c-style
-*.hxx.in kwsys-c-style
-
-*.cmake whitespace=tab-in-indent
-*.rst whitespace=tab-in-indent conflict-marker-size=79
-*.txt whitespace=tab-in-indent
diff --git a/Source/kwsys/CMakeLists.txt b/Source/kwsys/CMakeLists.txt
index e915b1a80..21568bbed 100644
--- a/Source/kwsys/CMakeLists.txt
+++ b/Source/kwsys/CMakeLists.txt
@@ -20,6 +20,21 @@
# KWSYS_HEADER_ROOT = The directory into which to generate the kwsys headers.
# A directory called "${KWSYS_NAMESPACE}" will be
# created under this root directory to hold the files.
+# KWSYS_SPLIT_OBJECTS_FROM_INTERFACE
+# = Instead of creating a single ${KWSYS_NAMESPACE} library
+# target, create three separate targets:
+# ${KWSYS_NAMESPACE}
+# - An INTERFACE library only containing usage
+# requirements.
+# ${KWSYS_NAMESPACE}_objects
+# - An OBJECT library for the built kwsys objects.
+# Note: This is omitted from the install rules
+# ${KWSYS_NAMESPACE}_private
+# - An INTERFACE library combining both that is
+# appropriate for use with PRIVATE linking in
+# target_link_libraries. Because of how interface
+# properties propagate, this target is not suitable
+# for use with PUBLIC or INTERFACE linking.
#
# Example:
#
@@ -79,6 +94,10 @@ FOREACH(p
ENDFOREACH()
SET(CMAKE_LEGACY_CYGWIN_WIN32 0)
+IF(CMAKE_VERSION VERSION_LESS 3.0)
+ SET(KWSYS_SPLIT_OBJECTS_FROM_INTERFACE 0)
+ENDIF()
+
#-----------------------------------------------------------------------------
# If a namespace is not specified, use "kwsys" and enable testing.
# This should be the case only when kwsys is not included inside
@@ -430,6 +449,11 @@ SET_SOURCE_FILES_PROPERTIES(ProcessUNIX.c System.c PROPERTIES
COMPILE_FLAGS "-DKWSYS_C_HAS_PTRDIFF_T=${KWSYS_C_HAS_PTRDIFF_T} -DKWSYS_C_HAS_SSIZE_T=${KWSYS_C_HAS_SSIZE_T}"
)
+IF(DEFINED KWSYS_PROCESS_USE_SELECT)
+ GET_PROPERTY(ProcessUNIX_FLAGS SOURCE ProcessUNIX.c PROPERTY COMPILE_FLAGS)
+ SET_PROPERTY(SOURCE ProcessUNIX.c PROPERTY COMPILE_FLAGS "${ProcessUNIX_FLAGS} -DKWSYSPE_USE_SELECT=${KWSYSPE_USE_SELECT}")
+ENDIF()
+
IF(KWSYS_USE_DynamicLoader)
GET_PROPERTY(KWSYS_SUPPORTS_SHARED_LIBS GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS)
IF(KWSYS_SUPPORTS_SHARED_LIBS)
@@ -795,68 +819,144 @@ ENDFOREACH()
#-----------------------------------------------------------------------------
# Add the library with the configured name and list of sources.
IF(KWSYS_C_SRCS OR KWSYS_CXX_SRCS)
- ADD_LIBRARY(${KWSYS_NAMESPACE} ${KWSYS_LIBRARY_TYPE}
- ${KWSYS_C_SRCS} ${KWSYS_CXX_SRCS})
- SET_PROPERTY(TARGET ${KWSYS_NAMESPACE} PROPERTY C_CLANG_TIDY "")
- SET_PROPERTY(TARGET ${KWSYS_NAMESPACE} PROPERTY CXX_CLANG_TIDY "")
- SET_PROPERTY(TARGET ${KWSYS_NAMESPACE} PROPERTY C_INCLUDE_WHAT_YOU_USE "")
- SET_PROPERTY(TARGET ${KWSYS_NAMESPACE} PROPERTY CXX_INCLUDE_WHAT_YOU_USE "")
- SET_PROPERTY(TARGET ${KWSYS_NAMESPACE} PROPERTY LABELS ${KWSYS_LABELS_LIB})
+ IF(KWSYS_SPLIT_OBJECTS_FROM_INTERFACE)
+ SET(KWSYS_TARGET_INTERFACE ${KWSYS_NAMESPACE})
+ SET(KWSYS_TARGET_OBJECT ${KWSYS_NAMESPACE}_objects)
+ SET(KWSYS_TARGET_LINK ${KWSYS_NAMESPACE}_private)
+ SET(KWSYS_TARGET_INSTALL ${KWSYS_TARGET_INTERFACE} ${KWSYS_TARGET_LINK})
+ SET(KWSYS_LINK_DEPENDENCY INTERFACE)
+ ADD_LIBRARY(${KWSYS_TARGET_OBJECT} OBJECT
+ ${KWSYS_C_SRCS} ${KWSYS_CXX_SRCS})
+ IF(KWSYS_BUILD_SHARED)
+ SET_PROPERTY(TARGET ${KWSYS_TARGET_OBJECT} PROPERTY
+ POSITION_INDEPENDENT_CODE TRUE)
+ ENDIF()
+ ADD_LIBRARY(${KWSYS_TARGET_INTERFACE} INTERFACE)
+ ADD_LIBRARY(${KWSYS_TARGET_LINK} INTERFACE)
+ TARGET_LINK_LIBRARIES(${KWSYS_TARGET_LINK} INTERFACE
+ ${KWSYS_TARGET_INTERFACE})
+ TARGET_SOURCES(${KWSYS_TARGET_LINK} INTERFACE
+ $<TARGET_OBJECTS:${KWSYS_TARGET_OBJECT}>)
+ ELSE()
+ SET(KWSYS_TARGET_INTERFACE ${KWSYS_NAMESPACE})
+ SET(KWSYS_TARGET_OBJECT ${KWSYS_NAMESPACE})
+ SET(KWSYS_TARGET_LINK ${KWSYS_NAMESPACE})
+ set(KWSYS_TARGET_INSTALL ${KWSYS_TARGET_LINK})
+ SET(KWSYS_LINK_DEPENDENCY PUBLIC)
+ ADD_LIBRARY(${KWSYS_TARGET_INTERFACE} ${KWSYS_LIBRARY_TYPE}
+ ${KWSYS_C_SRCS} ${KWSYS_CXX_SRCS})
+ ENDIF()
+ SET_TARGET_PROPERTIES(${KWSYS_TARGET_OBJECT} PROPERTIES
+ C_CLANG_TIDY ""
+ CXX_CLANG_TIDY ""
+ C_INCLUDE_WHAT_YOU_USE ""
+ CXX_INCLUDE_WHAT_YOU_USE ""
+ LABELS "${KWSYS_LABELS_LIB}")
IF(KWSYS_USE_DynamicLoader)
IF(UNIX)
- TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE} ${CMAKE_DL_LIBS})
+ TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY}
+ ${CMAKE_DL_LIBS})
ENDIF()
ENDIF()
IF(KWSYS_USE_SystemInformation)
IF(WIN32)
- TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE} ws2_32)
+ TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY} ws2_32)
IF(KWSYS_SYS_HAS_PSAPI)
- TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE} Psapi)
+ TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY}
+ Psapi)
ENDIF()
ELSEIF(UNIX)
IF (EXECINFO_LIB AND KWSYS_CXX_HAS_BACKTRACE)
# backtrace on FreeBSD is not in libc
- TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE} ${EXECINFO_LIB})
+ TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY}
+ ${EXECINFO_LIB})
ENDIF()
IF (KWSYS_CXX_HAS_DLADDR)
# for symbol lookup using dladdr
- TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE} ${CMAKE_DL_LIBS})
+ TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY}
+ ${CMAKE_DL_LIBS})
ENDIF()
IF (CMAKE_SYSTEM_NAME STREQUAL "SunOS")
- TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE} socket)
+ TARGET_LINK_LIBRARIES(${KWSYS_TARGET_INTERFACE} ${KWSYS_LINK_DEPENDENCY}
+ socket)
ENDIF()
ENDIF()
ENDIF()
# Apply user-defined target properties to the library.
IF(KWSYS_PROPERTIES_CXX)
- SET_TARGET_PROPERTIES(${KWSYS_NAMESPACE} PROPERTIES
- ${KWSYS_PROPERTIES_CXX}
- )
+ SET_TARGET_PROPERTIES(${KWSYS_TARGET_INTERFACE} PROPERTIES
+ ${KWSYS_PROPERTIES_CXX})
+ ENDIF()
+
+ # Set up include usage requirement
+ IF(COMMAND TARGET_INCLUDE_DIRECTORIES)
+ TARGET_INCLUDE_DIRECTORIES(${KWSYS_TARGET_INTERFACE} INTERFACE
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>)
+ IF(KWSYS_INSTALL_INCLUDE_DIR)
+ TARGET_INCLUDE_DIRECTORIES(${KWSYS_TARGET_INTERFACE} INTERFACE
+ $<INSTALL_INTERFACE:${KWSYS_INSTALL_INCLUDE_DIR}>)
+ ENDIF()
ENDIF()
# Create an install target for the library.
IF(KWSYS_INSTALL_LIBRARY_RULE)
- INSTALL(TARGETS ${KWSYS_NAMESPACE} ${KWSYS_INSTALL_LIBRARY_RULE})
+ INSTALL(TARGETS ${KWSYS_TARGET_INSTALL} ${KWSYS_INSTALL_LIBRARY_RULE})
ENDIF()
ENDIF()
# Add a C-only library if requested.
IF(KWSYS_ENABLE_C AND KWSYS_C_SRCS)
- ADD_LIBRARY(${KWSYS_NAMESPACE}_c ${KWSYS_LIBRARY_TYPE} ${KWSYS_C_SRCS})
- SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}_c PROPERTY LABELS ${KWSYS_LABELS_LIB})
+ IF(KWSYS_SPLIT_OBJECTS_FROM_INTERFACE)
+ SET(KWSYS_TARGET_C_INTERFACE ${KWSYS_NAMESPACE}_c)
+ SET(KWSYS_TARGET_C_OBJECT ${KWSYS_NAMESPACE}_c_objects)
+ SET(KWSYS_TARGET_C_LINK ${KWSYS_NAMESPACE}_c_private)
+ SET(KWSYS_TARGET_C_INSTALL
+ ${KWSYS_TARGET_C_INTERFACE} ${KWSYS_TARGET_C_LINK})
+ SET(KWSYS_LINK_DEPENDENCY INTERFACE)
+ ADD_LIBRARY(${KWSYS_TARGET_C_OBJECT} OBJECT ${KWSYS_C_SRCS})
+ IF(KWSYS_BUILD_SHARED)
+ SET_PROPERTY(TARGET ${KWSYS_TARGET_C_OBJECT} PROPERTY
+ POSITION_INDEPENDENT_CODE TRUE)
+ ENDIF()
+ ADD_LIBRARY(${KWSYS_TARGET_C_INTERFACE} INTERFACE)
+ ADD_LIBRARY(${KWSYS_TARGET_C_LINK} INTERFACE)
+ TARGET_LINK_LIBRARIES(${KWSYS_TARGET_C_LINK} INTERFACE
+ ${KWSYS_TARGET_C_INTERFACE})
+ TARGET_SOURCES(${KWSYS_TARGET_C_LINK} INTERFACE
+ $<TARGET_OBJECTS:${KWSYS_TARGET_C_OBJECT}>)
+ ELSE()
+ SET(KWSYS_TARGET_C_INTERFACE ${KWSYS_NAMESPACE}_c)
+ SET(KWSYS_TARGET_C_OBJECT ${KWSYS_NAMESPACE}_c)
+ SET(KWSYS_TARGET_C_LINK ${KWSYS_NAMESPACE}_c)
+ SET(KWSYS_TARGET_C_INSTALL ${KWSYS_TARGET_C_LINK})
+ SET(KWSYS_LINK_DEPENDENCY PUBLIC)
+ ADD_LIBRARY(${KWSYS_TARGET_C_INTERFACE} ${KWSYS_LIBRARY_TYPE}
+ ${KWSYS_C_SRCS})
+ ENDIF()
+ SET_TARGET_PROPERTIES(${KWSYS_TARGET_C_OBJECT} PROPERTIES
+ LABELS "${KWSYS_LABELS_LIB}")
# Apply user-defined target properties to the library.
IF(KWSYS_PROPERTIES_C)
- SET_TARGET_PROPERTIES(${KWSYS_NAMESPACE}_c PROPERTIES
- ${KWSYS_PROPERTIES_C}
- )
+ SET_TARGET_PROPERTIES(${KWSYS_TARGET_C_INTERFACE} PROPERTIES
+ ${KWSYS_PROPERTIES_C})
+ ENDIF()
+
+ # Set up include usage requirement
+ IF(COMMAND TARGET_INCLUDE_DIRECTORIES)
+ TARGET_INCLUDE_DIRECTORIES(${KWSYS_TARGET_C_INTERFACE} INTERFACE
+ $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>)
+ IF(KWSYS_INSTALL_INCLUDE_DIR)
+ TARGET_INCLUDE_DIRECTORIES(${KWSYS_TARGET_C_INTERFACE} INTERFACE
+ $<INSTALL_INTERFACE:${KWSYS_INSTALL_INCLUDE_DIR}>)
+ ENDIF()
ENDIF()
# Create an install target for the library.
IF(KWSYS_INSTALL_LIBRARY_RULE)
- INSTALL(TARGETS ${KWSYS_NAMESPACE}_c ${KWSYS_INSTALL_LIBRARY_RULE})
+ INSTALL(TARGETS ${KWSYS_TARGET_C_INSTALL})
ENDIF()
ENDIF()
@@ -915,7 +1015,7 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
)
ADD_EXECUTABLE(${KWSYS_NAMESPACE}TestsC ${KWSYS_C_TEST_SRCS})
SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestsC PROPERTY LABELS ${KWSYS_LABELS_EXE})
- TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE}TestsC ${KWSYS_NAMESPACE}_c)
+ TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE}TestsC ${KWSYS_TARGET_C_LINK})
FOREACH(test ${KWSYS_C_TESTS})
ADD_TEST(kwsys.${test} ${EXEC_DIR}/${KWSYS_NAMESPACE}TestsC ${test} ${KWSYS_TEST_ARGS_${test}})
SET_PROPERTY(TEST kwsys.${test} PROPERTY LABELS ${KWSYS_LABELS_TEST})
@@ -928,10 +1028,10 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
)
ENDIF()
SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS}
- testIOS
testSystemTools
testCommandLineArguments
testCommandLineArguments1
+ testDirectory
)
IF(KWSYS_STL_HAS_WSTRING)
SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS}
@@ -950,7 +1050,7 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
SET_PROPERTY(TARGET testConsoleBufChild PROPERTY C_INCLUDE_WHAT_YOU_USE "")
SET_PROPERTY(TARGET testConsoleBufChild PROPERTY CXX_INCLUDE_WHAT_YOU_USE "")
SET_PROPERTY(TARGET testConsoleBufChild PROPERTY LABELS ${KWSYS_LABELS_EXE})
- TARGET_LINK_LIBRARIES(testConsoleBufChild ${KWSYS_NAMESPACE})
+ TARGET_LINK_LIBRARIES(testConsoleBufChild ${KWSYS_TARGET_LINK})
SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS}
testConsoleBuf
)
@@ -969,7 +1069,7 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
# If kwsys contains the DynamicLoader, need extra library
ADD_LIBRARY(${KWSYS_NAMESPACE}TestDynload MODULE testDynload.c)
SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestDynload PROPERTY LABELS ${KWSYS_LABELS_LIB})
- ADD_DEPENDENCIES(${KWSYS_NAMESPACE}TestDynload ${KWSYS_NAMESPACE})
+ ADD_DEPENDENCIES(${KWSYS_NAMESPACE}TestDynload ${KWSYS_TARGET_INTERFACE})
ENDIF()
CREATE_TEST_SOURCELIST(
KWSYS_CXX_TEST_SRCS ${KWSYS_NAMESPACE}TestsCxx.cxx
@@ -981,7 +1081,7 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY C_INCLUDE_WHAT_YOU_USE "")
SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY CXX_INCLUDE_WHAT_YOU_USE "")
SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestsCxx PROPERTY LABELS ${KWSYS_LABELS_EXE})
- TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE}TestsCxx ${KWSYS_NAMESPACE})
+ TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE}TestsCxx ${KWSYS_TARGET_LINK})
SET(TEST_SYSTEMTOOLS_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
SET(TEST_SYSTEMTOOLS_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}")
@@ -1032,7 +1132,7 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
# Process tests.
ADD_EXECUTABLE(${KWSYS_NAMESPACE}TestProcess testProcess.c)
SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestProcess PROPERTY LABELS ${KWSYS_LABELS_EXE})
- TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE}TestProcess ${KWSYS_NAMESPACE}_c)
+ TARGET_LINK_LIBRARIES(${KWSYS_NAMESPACE}TestProcess ${KWSYS_TARGET_C_LINK})
IF(NOT CYGWIN)
SET(KWSYS_TEST_PROCESS_7 7)
ENDIF()
@@ -1060,7 +1160,7 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR)
ADD_EXECUTABLE(${KWSYS_NAMESPACE}TestSharedForward
${PROJECT_BINARY_DIR}/testSharedForward.c)
SET_PROPERTY(TARGET ${KWSYS_NAMESPACE}TestSharedForward PROPERTY LABELS ${KWSYS_LABELS_EXE})
- ADD_DEPENDENCIES(${KWSYS_NAMESPACE}TestSharedForward ${KWSYS_NAMESPACE}_c)
+ ADD_DEPENDENCIES(${KWSYS_NAMESPACE}TestSharedForward ${KWSYS_TARGET_C_LINK})
ADD_TEST(kwsys.testSharedForward ${EXEC_DIR}/${KWSYS_NAMESPACE}TestSharedForward 1)
SET_PROPERTY(TEST kwsys.testSharedForward PROPERTY LABELS ${KWSYS_LABELS_TEST})
diff --git a/Source/kwsys/Directory.cxx b/Source/kwsys/Directory.cxx
index 5141d4519..69068aaf8 100644
--- a/Source/kwsys/Directory.cxx
+++ b/Source/kwsys/Directory.cxx
@@ -118,8 +118,8 @@ bool Directory::Load(const std::string& name)
struct _wfinddata_t data; // data of current file
// Now put them into the file array
- srchHandle =
- _wfindfirst_func((wchar_t*)Encoding::ToWide(buf).c_str(), &data);
+ srchHandle = _wfindfirst_func(
+ (wchar_t*)Encoding::ToWindowsExtendedPath(buf).c_str(), &data);
delete[] buf;
if (srchHandle == -1) {
diff --git a/Source/kwsys/ProcessUNIX.c b/Source/kwsys/ProcessUNIX.c
index 9ebcfce59..3b32ca7d0 100644
--- a/Source/kwsys/ProcessUNIX.c
+++ b/Source/kwsys/ProcessUNIX.c
@@ -99,7 +99,8 @@ static inline void kwsysProcess_usleep(unsigned int msec)
* pipes' file handles to be non-blocking and just poll them directly
* without select().
*/
-#if !defined(__BEOS__) && !defined(__VMS) && !defined(__MINT__)
+#if !defined(__BEOS__) && !defined(__VMS) && !defined(__MINT__) && \
+ !defined(KWSYSPE_USE_SELECT)
#define KWSYSPE_USE_SELECT 1
#endif
diff --git a/Source/kwsys/RegularExpression.cxx b/Source/kwsys/RegularExpression.cxx
index 6d7f83295..26e84e04e 100644
--- a/Source/kwsys/RegularExpression.cxx
+++ b/Source/kwsys/RegularExpression.cxx
@@ -258,11 +258,6 @@ const unsigned char MAGIC = 0234;
#define UCHARAT(p) (reinterpret_cast<const unsigned char*>(p))[0]
-#define FAIL(m) \
- { \
- regerror(m); \
- return (0); \
- }
#define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
#define META "^$.[()|?+*\\"
diff --git a/Source/kwsys/SystemTools.cxx b/Source/kwsys/SystemTools.cxx
index 1c4fe3389..ecfa3319b 100644
--- a/Source/kwsys/SystemTools.cxx
+++ b/Source/kwsys/SystemTools.cxx
@@ -22,7 +22,6 @@
#include KWSYS_HEADER(FStream.hxx)
#include KWSYS_HEADER(Encoding.hxx)
-#include <algorithm>
#include <fstream>
#include <iostream>
#include <set>
@@ -848,6 +847,8 @@ void SystemTools::ReplaceString(std::string& source, const char* replace,
free(orig);
}
+#if defined(_WIN32) && !defined(__CYGWIN__)
+
#if defined(KEY_WOW64_32KEY) && defined(KEY_WOW64_64KEY)
#define KWSYS_ST_KEY_WOW64_32KEY KEY_WOW64_32KEY
#define KWSYS_ST_KEY_WOW64_64KEY KEY_WOW64_64KEY
@@ -856,7 +857,6 @@ void SystemTools::ReplaceString(std::string& source, const char* replace,
#define KWSYS_ST_KEY_WOW64_64KEY 0x0100
#endif
-#if defined(_WIN32) && !defined(__CYGWIN__)
static bool SystemToolsParseRegistryKey(const std::string& key,
HKEY& primaryKey, std::string& second,
std::string& valuename)
@@ -2269,11 +2269,7 @@ bool SystemTools::CopyADirectory(const std::string& source,
const std::string& destination, bool always)
{
Directory dir;
-#ifdef _WIN32
- dir.Load(Encoding::ToNarrow(Encoding::ToWindowsExtendedPath(source)));
-#else
dir.Load(source);
-#endif
size_t fileNum;
if (!SystemTools::MakeDirectory(destination)) {
return false;
@@ -2375,104 +2371,6 @@ long int SystemTools::CreationTime(const std::string& filename)
return ct;
}
-bool SystemTools::ConvertDateMacroString(const char* str, time_t* tmt)
-{
- if (!str || !tmt || strlen(str) > 11) {
- return false;
- }
-
- struct tm tmt2;
-
- // __DATE__
- // The compilation date of the current source file. The date is a string
- // literal of the form Mmm dd yyyy. The month name Mmm is the same as for
- // dates generated by the library function asctime declared in TIME.H.
-
- // index: 012345678901
- // format: Mmm dd yyyy
- // example: Dec 19 2003
-
- static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
-
- char buffer[12];
- strcpy(buffer, str);
-
- buffer[3] = 0;
- char* ptr = strstr(month_names, buffer);
- if (!ptr) {
- return false;
- }
-
- int month = static_cast<int>((ptr - month_names) / 3);
- int day = atoi(buffer + 4);
- int year = atoi(buffer + 7);
-
- tmt2.tm_isdst = -1;
- tmt2.tm_hour = 0;
- tmt2.tm_min = 0;
- tmt2.tm_sec = 0;
- tmt2.tm_wday = 0;
- tmt2.tm_yday = 0;
- tmt2.tm_mday = day;
- tmt2.tm_mon = month;
- tmt2.tm_year = year - 1900;
-
- *tmt = mktime(&tmt2);
- return true;
-}
-
-bool SystemTools::ConvertTimeStampMacroString(const char* str, time_t* tmt)
-{
- if (!str || !tmt || strlen(str) > 26) {
- return false;
- }
-
- struct tm tmt2;
-
- // __TIMESTAMP__
- // The date and time of the last modification of the current source file,
- // expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy,
- /// where Ddd is the abbreviated day of the week and Date is an integer
- // from 1 to 31.
-
- // index: 0123456789
- // 0123456789
- // 0123456789
- // format: Ddd Mmm Date hh:mm:ss yyyy
- // example: Fri Dec 19 14:34:58 2003
-
- static char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
-
- char buffer[27];
- strcpy(buffer, str);
-
- buffer[7] = 0;
- char* ptr = strstr(month_names, buffer + 4);
- if (!ptr) {
- return false;
- }
-
- int month = static_cast<int>((ptr - month_names) / 3);
- int day = atoi(buffer + 8);
- int hour = atoi(buffer + 11);
- int min = atoi(buffer + 14);
- int sec = atoi(buffer + 17);
- int year = atoi(buffer + 20);
-
- tmt2.tm_isdst = -1;
- tmt2.tm_hour = hour;
- tmt2.tm_min = min;
- tmt2.tm_sec = sec;
- tmt2.tm_wday = 0;
- tmt2.tm_yday = 0;
- tmt2.tm_mday = day;
- tmt2.tm_mon = month;
- tmt2.tm_year = year - 1900;
-
- *tmt = mktime(&tmt2);
- return true;
-}
-
std::string SystemTools::GetLastSystemError()
{
int e = errno;
@@ -2626,11 +2524,7 @@ bool SystemTools::RemoveADirectory(const std::string& source)
}
Directory dir;
-#ifdef _WIN32
- dir.Load(Encoding::ToNarrow(Encoding::ToWindowsExtendedPath(source)));
-#else
dir.Load(source);
-#endif
size_t fileNum;
for (fileNum = 0; fileNum < dir.GetNumberOfFiles(); ++fileNum) {
if (strcmp(dir.GetFile(static_cast<unsigned long>(fileNum)), ".") &&
@@ -3709,16 +3603,6 @@ std::string SystemTools::JoinPath(
return result;
}
-void SystemTools::RemoveEmptyPathElements(std::vector<std::string>& path)
-{
- if (path.empty()) {
- return;
- }
-
- path.erase(std::remove(path.begin() + 1, path.end(), std::string("")),
- path.end());
-}
-
bool SystemTools::ComparePath(const std::string& c1, const std::string& c2)
{
#if defined(_WIN32) || defined(__APPLE__)
@@ -3807,11 +3691,7 @@ std::string SystemTools::GetFilenamePath(const std::string& filename)
*/
std::string SystemTools::GetFilenameName(const std::string& filename)
{
-#if defined(_WIN32)
std::string::size_type slash_pos = filename.find_last_of("/\\");
-#else
- std::string::size_type slash_pos = filename.rfind('/');
-#endif
if (slash_pos != std::string::npos) {
return filename.substr(slash_pos + 1);
} else {
@@ -4124,66 +4004,6 @@ bool SystemTools::GetShortPath(const std::string& path, std::string& shortPath)
#endif
}
-void SystemTools::SplitProgramFromArgs(const std::string& path,
- std::string& program, std::string& args)
-{
- // see if this is a full path to a program
- // if so then set program to path and args to nothing
- if (SystemTools::FileExists(path)) {
- program = path;
- args = "";
- return;
- }
- // Try to find the program in the path, note the program
- // may have spaces in its name so we have to look for it
- std::vector<std::string> e;
- std::string findProg = SystemTools::FindProgram(path, e);
- if (!findProg.empty()) {
- program = findProg;
- args = "";
- return;
- }
-
- // Now try and peel off space separated chunks from the end of the string
- // so the largest path possible is found allowing for spaces in the path
- std::string dir = path;
- std::string::size_type spacePos = dir.rfind(' ');
- while (spacePos != std::string::npos) {
- std::string tryProg = dir.substr(0, spacePos);
- // See if the file exists
- if (SystemTools::FileExists(tryProg)) {
- program = tryProg;
- // remove trailing spaces from program
- std::string::size_type pos = program.size() - 1;
- while (program[pos] == ' ') {
- program.erase(pos);
- pos--;
- }
- args = dir.substr(spacePos, dir.size() - spacePos);
- return;
- }
- // Now try and find the program in the path
- findProg = SystemTools::FindProgram(tryProg, e);
- if (!findProg.empty()) {
- program = findProg;
- // remove trailing spaces from program
- std::string::size_type pos = program.size() - 1;
- while (program[pos] == ' ') {
- program.erase(pos);
- pos--;
- }
- args = dir.substr(spacePos, dir.size() - spacePos);
- return;
- }
- // move past the space for the next search
- spacePos--;
- spacePos = dir.rfind(' ', spacePos);
- }
-
- program = "";
- args = "";
-}
-
std::string SystemTools::GetCurrentDateTime(const char* format)
{
char buf[1024];
diff --git a/Source/kwsys/SystemTools.hxx.in b/Source/kwsys/SystemTools.hxx.in
index 5e091c2af..35bc1b19b 100644
--- a/Source/kwsys/SystemTools.hxx.in
+++ b/Source/kwsys/SystemTools.hxx.in
@@ -206,13 +206,6 @@ public:
static int Strucmp(const char* s1, const char* s2);
/**
- * Convert a string in __DATE__ or __TIMESTAMP__ format into a time_t.
- * Return false on error, true on success
- */
- static bool ConvertDateMacroString(const char* str, time_t* tmt);
- static bool ConvertTimeStampMacroString(const char* str, time_t* tmt);
-
- /**
* Split a string on its newlines into multiple lines
* Return false only if the last line stored had no newline
*/
@@ -461,6 +454,10 @@ public:
* produce the original path. Home directory references are
* automatically expanded if expand_home_dir is true and this
* platform supports them.
+ *
+ * This does *not* normalize the input path. All components are
+ * preserved, including empty ones. Typically callers should use
+ * this only on paths that have already been normalized.
*/
static void SplitPath(const std::string& p,
std::vector<std::string>& components,
@@ -469,15 +466,15 @@ public:
/**
* Join components of a path name into a single string. See
* SplitPath for the format of the components.
+ *
+ * This does *not* normalize the input path. All components are
+ * preserved, including empty ones. Typically callers should use
+ * this only on paths that have already been normalized.
*/
static std::string JoinPath(const std::vector<std::string>& components);
static std::string JoinPath(std::vector<std::string>::const_iterator first,
std::vector<std::string>::const_iterator last);
- /** Removes empty components from path.
- */
- static void RemoveEmptyPathElements(std::vector<std::string>& path);
-
/**
* Compare a path or components of a path.
*/
@@ -494,12 +491,6 @@ public:
static std::string GetFilenameName(const std::string&);
/**
- * Split a program from its arguments and handle spaces in the paths
- */
- static void SplitProgramFromArgs(const std::string& path,
- std::string& program, std::string& args);
-
- /**
* Return longest file extension of a full filename (dot included)
*/
static std::string GetFilenameExtension(const std::string&);
diff --git a/Source/kwsys/kwsysPlatformTestsCXX.cxx b/Source/kwsys/kwsysPlatformTestsCXX.cxx
index 01c69514c..e67d43662 100644
--- a/Source/kwsys/kwsysPlatformTestsCXX.cxx
+++ b/Source/kwsys/kwsysPlatformTestsCXX.cxx
@@ -265,6 +265,12 @@ int main()
#ifdef TEST_KWSYS_CXX_HAS_UTIMENSAT
#include <fcntl.h>
#include <sys/stat.h>
+#if defined(__APPLE__)
+#include <AvailabilityMacros.h>
+#if MAC_OS_X_VERSION_MIN_REQUIRED < 101300
+#error "utimensat not available on macOS < 10.13"
+#endif
+#endif
int main()
{
struct timespec times[2] = { { 0, UTIME_OMIT }, { 0, UTIME_NOW } };
diff --git a/Source/kwsys/testDirectory.cxx b/Source/kwsys/testDirectory.cxx
new file mode 100644
index 000000000..983f2c631
--- /dev/null
+++ b/Source/kwsys/testDirectory.cxx
@@ -0,0 +1,79 @@
+/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
+file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
+#include "kwsysPrivate.h"
+#include KWSYS_HEADER(Directory.hxx)
+#include KWSYS_HEADER(Encoding.hxx)
+#include KWSYS_HEADER(SystemTools.hxx)
+
+// Work-around CMake dependency scanning limitation. This must
+// duplicate the above list of headers.
+#if 0
+#include "Directory.hxx.in"
+#include "Encoding.hxx.in"
+#include "SystemTools.hxx.in"
+#endif
+
+#include <fstream>
+#include <iostream>
+#include <sstream>
+
+#include <testSystemTools.h>
+
+int _doLongPathTest()
+{
+ using namespace kwsys;
+ static const int LONG_PATH_THRESHOLD = 512;
+ int res = 0;
+ std::string topdir(TEST_SYSTEMTOOLS_BINARY_DIR "/directory_testing/");
+ std::stringstream testpathstrm;
+ std::string testdirpath;
+ std::string extendedtestdirpath;
+
+ testpathstrm << topdir;
+ size_t pathlen = testpathstrm.str().length();
+ testpathstrm.seekp(0, std::ios_base::end);
+ while (pathlen < LONG_PATH_THRESHOLD) {
+ testpathstrm << "0123456789/";
+ pathlen = testpathstrm.str().length();
+ }
+
+ testdirpath = testpathstrm.str();
+#ifdef _WIN32
+ extendedtestdirpath =
+ Encoding::ToNarrow(SystemTools::ConvertToWindowsExtendedPath(testdirpath));
+#else
+ extendedtestdirpath = testdirpath;
+#endif
+
+ if (SystemTools::MakeDirectory(extendedtestdirpath)) {
+ std::ofstream testfile1(
+ (extendedtestdirpath + "longfilepathtest1.txt").c_str());
+ std::ofstream testfile2(
+ (extendedtestdirpath + "longfilepathtest2.txt").c_str());
+ testfile1 << "foo";
+ testfile2 << "bar";
+ testfile1.close();
+ testfile2.close();
+
+ Directory testdir;
+ // Set res to failure if the directory doesn't load
+ res += !testdir.Load(testdirpath);
+ // Increment res failure if the directory appears empty
+ res += testdir.GetNumberOfFiles() == 0;
+ // Increment res failures if the path has changed from
+ // what was provided.
+ res += testdirpath != testdir.GetPath();
+
+ SystemTools::RemoveADirectory(topdir);
+ } else {
+ std::cerr << "Failed to create directory with long path: "
+ << extendedtestdirpath << std::endl;
+ res += 1;
+ }
+ return res;
+}
+
+int testDirectory(int, char* [])
+{
+ return _doLongPathTest();
+}
diff --git a/Source/kwsys/testIOS.cxx b/Source/kwsys/testIOS.cxx
deleted file mode 100644
index 3e4c325c7..000000000
--- a/Source/kwsys/testIOS.cxx
+++ /dev/null
@@ -1,139 +0,0 @@
-/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
- file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
-#include "kwsysPrivate.h"
-#include KWSYS_HEADER(Configure.hxx)
-
-#include <fstream>
-#include <iostream>
-#include <sstream>
-#include <string.h> /* strlen */
-#include <vector>
-
-// Work-around CMake dependency scanning limitation. This must
-// duplicate the above list of headers.
-#if 0
-#include "Configure.hxx.in"
-#endif
-
-int testIOS(int, char* [])
-{
- std::ostringstream ostr;
- const char hello[] = "hello";
- ostr << hello;
- if (ostr.str() != hello) {
- std::cerr << "failed to write hello to ostr" << std::endl;
- return 1;
- }
- const char world[] = "world";
- std::ostringstream ostr2;
- ostr2.write(hello, strlen(hello)); /* I could do sizeof */
- ostr2.put('\0');
- ostr2.write(world, strlen(world));
- if (ostr2.str().size() != strlen(hello) + 1 + strlen(world)) {
- std::cerr << "failed to write hello to ostr2" << std::endl;
- return 1;
- }
- static const unsigned char array[] = {
- 0xff, 0x4f, 0xff, 0x51, 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30,
- 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x01, 0x01, 0xff, 0x52, 0x00,
- 0x0c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x05, 0x04, 0x04, 0x00, 0x01, 0xff,
- 0x5c, 0x00, 0x13, 0x40, 0x40, 0x48, 0x48, 0x50, 0x48, 0x48, 0x50, 0x48,
- 0x48, 0x50, 0x48, 0x48, 0x50, 0x48, 0x48, 0x50, 0xff, 0x64, 0x00, 0x2c,
- 0x00, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79,
- 0x20, 0x49, 0x54, 0x4b, 0x2f, 0x47, 0x44, 0x43, 0x4d, 0x2f, 0x4f, 0x70,
- 0x65, 0x6e, 0x4a, 0x50, 0x45, 0x47, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
- 0x6f, 0x6e, 0x20, 0x31, 0x2e, 0x30, 0xff, 0x90, 0x00, 0x0a, 0x00, 0x00,
- 0x00, 0x00, 0x06, 0x2c, 0x00, 0x01, 0xff, 0x93, 0xcf, 0xb0, 0x18, 0x08,
- 0x7f, 0xc6, 0x99, 0xbf, 0xff, 0xc0, 0xf8, 0xc1, 0xc1, 0xf3, 0x05, 0x81,
- 0xf2, 0x83, 0x0a, 0xa5, 0xff, 0x10, 0x90, 0xbf, 0x2f, 0xff, 0x04, 0xa8,
- 0x7f, 0xc0, 0xf8, 0xc4, 0xc1, 0xf3, 0x09, 0x81, 0xf3, 0x0c, 0x19, 0x34
- };
- const size_t narray = sizeof(array); // 180
- std::stringstream strstr;
- strstr.write((char*)array, narray);
- // strstr.seekp( narray / 2 ); // set position of put pointer in mid string
- if (strstr.str().size() != narray) {
- std::cerr << "failed to write array to strstr" << std::endl;
- return 1;
- }
-
- std::istringstream istr(" 10 20 str ");
- std::string s;
- int x;
- if (istr >> x) {
- if (x != 10) {
- std::cerr << "x != 10" << std::endl;
- return 1;
- }
- } else {
- std::cerr << "Failed to read 10 from istr" << std::endl;
- return 1;
- }
- if (istr >> x) {
- if (x != 20) {
- std::cerr << "x != 20" << std::endl;
- return 1;
- }
- } else {
- std::cerr << "Failed to read 20 from istr" << std::endl;
- return 1;
- }
- if (istr >> s) {
- if (s != "str") {
- std::cerr << "s != \"str\"" << std::endl;
- return 1;
- }
- } else {
- std::cerr << "Failed to read str from istr" << std::endl;
- return 1;
- }
- if (istr >> s) {
- std::cerr << "Able to read past end of stream" << std::endl;
- return 1;
- } else {
- // Clear the failure.
- istr.clear(istr.rdstate() & ~std::ios::eofbit);
- istr.clear(istr.rdstate() & ~std::ios::failbit);
- }
- istr.str("30");
- if (istr >> x) {
- if (x != 30) {
- std::cerr << "x != 30" << std::endl;
- return 1;
- }
- } else {
- std::cerr << "Failed to read 30 from istr" << std::endl;
- return 1;
- }
-
- std::stringstream sstr;
- sstr << "40 str2";
- if (sstr >> x) {
- if (x != 40) {
- std::cerr << "x != 40" << std::endl;
- return 1;
- }
- } else {
- std::cerr << "Failed to read 40 from sstr" << std::endl;
- return 1;
- }
- if (sstr >> s) {
- if (s != "str2") {
- std::cerr << "s != \"str2\"" << std::endl;
- return 1;
- }
- } else {
- std::cerr << "Failed to read str2 from sstr" << std::endl;
- return 1;
- }
-
- // Just try to compile this.
- if (x == 12345) {
- std::ifstream fin("/does_not_exist", std::ios::in | std::ios::binary);
- }
-
- std::cout << "IOS tests passed" << std::endl;
- return 0;
-}
diff --git a/Source/kwsys/testSystemTools.cxx b/Source/kwsys/testSystemTools.cxx
index e6fbf6cda..768eb4d12 100644
--- a/Source/kwsys/testSystemTools.cxx
+++ b/Source/kwsys/testSystemTools.cxx
@@ -22,6 +22,7 @@
#include <iostream>
#include <sstream>
+#include <stdlib.h> /* free */
#include <string.h> /* strcmp */
#if defined(_WIN32) && !defined(__CYGWIN__)
#include <io.h> /* _umask (MSVC) / umask (Borland) */
@@ -535,15 +536,14 @@ static bool CheckStringOperations()
}
delete[] cres;
- char* cres2 = new char[strlen("Mary Had A Little Lamb.") + 1];
- strcpy(cres2, "Mary Had A Little Lamb.");
+ char* cres2 = strdup("Mary Had A Little Lamb.");
kwsys::SystemTools::ReplaceChars(cres2, "aeiou", 'X');
if (strcmp(cres2, "MXry HXd A LXttlX LXmb.")) {
std::cerr << "Problem with ReplaceChars "
<< "\"Mary Had A Little Lamb.\"" << std::endl;
res = false;
}
- delete[] cres2;
+ free(cres2);
if (!kwsys::SystemTools::StringStartsWith("Mary Had A Little Lamb.",
"Mary ")) {
@@ -758,6 +758,30 @@ static bool CheckGetPath()
return res;
}
+static bool CheckGetFilenameName()
+{
+ const char* windowsFilepath = "C:\\somewhere\\something";
+ const char* unixFilepath = "/somewhere/something";
+
+ std::string expectedFilename = "something";
+
+ bool res = true;
+ std::string filename = kwsys::SystemTools::GetFilenameName(windowsFilepath);
+ if (filename != expectedFilename) {
+ std::cerr << "GetFilenameName(" << windowsFilepath << ") yielded "
+ << filename << " instead of " << expectedFilename << std::endl;
+ res = false;
+ }
+
+ filename = kwsys::SystemTools::GetFilenameName(unixFilepath);
+ if (filename != expectedFilename) {
+ std::cerr << "GetFilenameName(" << unixFilepath << ") yielded " << filename
+ << " instead of " << expectedFilename << std::endl;
+ res = false;
+ }
+ return res;
+}
+
static bool CheckFind()
{
bool res = true;
@@ -875,5 +899,7 @@ int testSystemTools(int, char* [])
res &= CheckGetLineFromStream();
+ res &= CheckGetFilenameName();
+
return res ? 0 : 1;
}
diff --git a/Tests/AliasTarget/CMakeLists.txt b/Tests/AliasTarget/CMakeLists.txt
index e156420db..fc7013598 100644
--- a/Tests/AliasTarget/CMakeLists.txt
+++ b/Tests/AliasTarget/CMakeLists.txt
@@ -4,13 +4,6 @@ project(AliasTarget)
set(CMAKE_CXX_STANDARD 98)
-# Those versions of the HP compiler that need a flag to get proper C++98
-# template support also need a flag to use the newer C++ library.
-if (CMAKE_CXX_COMPILER_ID STREQUAL HP AND
- CMAKE_CXX98_STANDARD_COMPILE_OPTION STREQUAL "+hpxstd98")
- string(APPEND CMAKE_CXX_FLAGS " -AA")
-endif ()
-
# Clang/C2 in C++98 mode cannot properly handle some of MSVC headers
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND
CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
diff --git a/Tests/CMakeLib/run_compile_commands.cxx b/Tests/CMakeLib/run_compile_commands.cxx
index 46431bc33..b49803bd6 100644
--- a/Tests/CMakeLib/run_compile_commands.cxx
+++ b/Tests/CMakeLib/run_compile_commands.cxx
@@ -1,4 +1,4 @@
-#include <cmConfigure.h>
+#include "cmConfigure.h" // IWYU pragma: keep
#include "cmsys/FStream.hxx"
#include <iostream>
@@ -144,15 +144,11 @@ int main()
cmsys::ifstream file("compile_commands.json");
CompileCommandParser parser(file);
parser.Parse();
- for (CompileCommandParser::TranslationUnitsType::const_iterator
- it = parser.GetTranslationUnits().begin(),
- end = parser.GetTranslationUnits().end();
- it != end; ++it) {
+ for (auto const& tu : parser.GetTranslationUnits()) {
std::vector<std::string> command;
- cmSystemTools::ParseUnixCommandLine(it->at("command").c_str(), command);
- if (!cmSystemTools::RunSingleCommand(command, CM_NULLPTR, CM_NULLPTR,
- CM_NULLPTR,
- it->at("directory").c_str())) {
+ cmSystemTools::ParseUnixCommandLine(tu.at("command").c_str(), command);
+ if (!cmSystemTools::RunSingleCommand(command, nullptr, nullptr, nullptr,
+ tu.at("directory").c_str())) {
std::cout << "ERROR: Failed to run command \"" << command[0] << "\""
<< std::endl;
exit(1);
diff --git a/Tests/CMakeLib/testUTF8.cxx b/Tests/CMakeLib/testUTF8.cxx
index fb5f3d815..c99c46db5 100644
--- a/Tests/CMakeLib/testUTF8.cxx
+++ b/Tests/CMakeLib/testUTF8.cxx
@@ -8,8 +8,9 @@ typedef char test_utf8_char[5];
static void test_utf8_char_print(test_utf8_char const c)
{
unsigned char const* d = reinterpret_cast<unsigned char const*>(c);
- printf("[0x%02X,0x%02X,0x%02X,0x%02X]", (int)d[0], (int)d[1], (int)d[2],
- (int)d[3]);
+ printf("[0x%02X,0x%02X,0x%02X,0x%02X]", static_cast<int>(d[0]),
+ static_cast<int>(d[1]), static_cast<int>(d[2]),
+ static_cast<int>(d[3]));
}
struct test_utf8_entry
diff --git a/Tests/CMakeLib/testVisualStudioSlnParser_data/.gitattributes b/Tests/CMakeLib/testVisualStudioSlnParser_data/.gitattributes
deleted file mode 100644
index 5be3dc5bc..000000000
--- a/Tests/CMakeLib/testVisualStudioSlnParser_data/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-*.sln-file -crlf whitespace=cr-at-eol
diff --git a/Tests/CMakeLib/testXMLSafe.cxx b/Tests/CMakeLib/testXMLSafe.cxx
index fe776c587..21bb95292 100644
--- a/Tests/CMakeLib/testXMLSafe.cxx
+++ b/Tests/CMakeLib/testXMLSafe.cxx
@@ -1,7 +1,7 @@
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
-#include <cmConfigure.h>
+#include "cmConfigure.h" // IWYU pragma: keep
#include <sstream>
#include <stdio.h>
@@ -21,7 +21,7 @@ static test_pair const pairs[] = {
{ "angles <>", "angles &lt;&gt;" },
{ "ampersand &", "ampersand &amp;" },
{ "bad-byte \x80", "bad-byte [NON-UTF-8-BYTE-0x80]" },
- { CM_NULLPTR, CM_NULLPTR }
+ { nullptr, nullptr }
};
int testXMLSafe(int /*unused*/, char* /*unused*/ [])
diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt
index d16df1cf5..533788a44 100644
--- a/Tests/CMakeLists.txt
+++ b/Tests/CMakeLists.txt
@@ -146,6 +146,10 @@ if(BUILD_TESTING)
if(NOT CMake_TEST_EXTERNAL_CMAKE)
add_subdirectory(CMakeLib)
+
+ if(CMake_TEST_SERVER_MODE)
+ add_subdirectory(CMakeServerLib)
+ endif()
endif()
add_subdirectory(CMakeOnly)
add_subdirectory(RunCMake)
@@ -264,7 +268,7 @@ if(BUILD_TESTING)
endif()
add_test(NAME CMake.Copyright
- COMMAND cmake -P ${CMAKE_CURRENT_SOURCE_DIR}/CMakeCopyright.cmake)
+ COMMAND ${CMAKE_CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/CMakeCopyright.cmake)
# add a bunch of standard build-and-test style tests
ADD_TEST_MACRO(CommandLineTest CommandLineTest)
@@ -325,7 +329,7 @@ if(BUILD_TESTING)
set(CMAKE_SKIP_VSGNUFortran TRUE)
endif()
if(NOT CMAKE_SKIP_VSGNUFortran)
- ADD_TEST_MACRO(VSGNUFortran ${CMAKE_COMMAND} -P runtest.cmake)
+ ADD_TEST_MACRO(VSGNUFortran ${CMAKE_CMAKE_COMMAND} -P runtest.cmake)
endif()
endif()
@@ -403,11 +407,14 @@ if(BUILD_TESTING)
list(APPEND TEST_BUILD_DIRS ${CMake_TEST_INSTALL_PREFIX})
- if(NOT QT4_FOUND)
+ if(NOT DEFINED CMake_TEST_Qt4)
+ set(CMake_TEST_Qt4 1)
+ endif()
+ if(CMake_TEST_Qt4 AND NOT QT4_FOUND)
find_package(Qt4 QUIET)
endif()
- if(QT4_FOUND)
+ if(CMake_TEST_Qt4 AND QT4_FOUND)
# test whether the Qt4 which has been found works, on some machines
# which run nightly builds there were errors like "wrong file format"
# for libQtCore.so. So first check it works, and only if it does add
@@ -809,31 +816,6 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
)
list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/CustomCommandWorkingDirectory")
- #add_test(SimpleExclude ${CMAKE_CTEST_COMMAND}
- # --build-and-test
- # "${CMake_SOURCE_DIR}/Tests/SimpleExclude"
- # "${CMake_BINARY_DIR}/Tests/SimpleExclude"
- # ${build_generator_args}
- # --build-project SimpleExclude
- # --build-two-config
- # --build-options ${build_options}
- # --test-command t4
- #--test-command "${CMAKE_COMMAND}"
- #"-DCONFIGURATION=\${CTEST_CONFIGURATION_TYPE}"
- #-P "${CMake_BINARY_DIR}/Tests/SimpleExclude/run.cmake"
- #)
-
-# add_test(SameName ${CMAKE_CTEST_COMMAND}
-# --build-and-test
-# "${CMake_SOURCE_DIR}/Tests/SameName"
-# "${CMake_BINARY_DIR}/Tests/SameName"
-# ${build_generator_args}
-# --build-project SameName
-# --build-two-config
-# --build-options ${build_options}
-# --test-command
-# "${CMake_BINARY_DIR}/Tests/SameName/Exe1/mytest2")
-
add_test(OutOfSource ${CMAKE_CTEST_COMMAND}
--build-and-test
"${CMake_SOURCE_DIR}/Tests/OutOfSource"
@@ -1274,8 +1256,13 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
set(QtAutogen_BUILD_OPTIONS -DCMAKE_BUILD_TYPE=$<CONFIGURATION>)
endif()
- find_package(Qt5Widgets QUIET NO_MODULE)
- if(Qt5Widgets_FOUND)
+ if(NOT DEFINED CMake_TEST_Qt5)
+ set(CMake_TEST_Qt5 1)
+ endif()
+ if(CMake_TEST_Qt5)
+ find_package(Qt5Widgets QUIET NO_MODULE)
+ endif()
+ if(CMake_TEST_Qt5 AND Qt5Widgets_FOUND)
add_test(NAME Qt5Autogen COMMAND ${CMAKE_CTEST_COMMAND}
--build-and-test
"${CMake_SOURCE_DIR}/Tests/QtAutogen"
@@ -1285,12 +1272,28 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
--build-exe-dir "${CMake_BINARY_DIR}/Tests/Qt5Autogen"
--force-new-ctest-process
--build-options ${build_options}
- -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE} -DQT_TEST_VERSION=5
+ -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}
+ -DQT_TEST_VERSION=5
${QtAutogen_BUILD_OPTIONS}
--test-command ${run_autogen_test}
)
list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/Qt5Autogen")
+ add_test(NAME Qt5AutogenRerun COMMAND ${CMAKE_CTEST_COMMAND}
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/QtAutogenRerun"
+ "${CMake_BINARY_DIR}/Tests/Qt5AutogenRerun"
+ ${build_generator_args}
+ --build-project QtAutogenRerun
+ --build-exe-dir "${CMake_BINARY_DIR}/Tests/Qt5AutogenRerun"
+ --force-new-ctest-process
+ --build-options ${build_options}
+ -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}
+ -DQT_TEST_VERSION=5
+ ${QtAutogen_BUILD_OPTIONS}
+ )
+ list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/Qt5AutogenRerun")
+
add_test(Qt5AutoUicInterface ${CMAKE_CTEST_COMMAND}
--build-and-test
"${CMake_SOURCE_DIR}/Tests/QtAutoUicInterface"
@@ -1315,12 +1318,28 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
--build-exe-dir "${CMake_BINARY_DIR}/Tests/Qt4Autogen"
--force-new-ctest-process
--build-options ${build_options}
- -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE} -DQT_TEST_VERSION=4
+ -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}
+ -DQT_TEST_VERSION=4
${QtAutogen_BUILD_OPTIONS}
--test-command ${run_autogen_test}
)
list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/Qt4Autogen")
+ add_test(NAME Qt4AutogenRerun COMMAND ${CMAKE_CTEST_COMMAND}
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/QtAutogenRerun"
+ "${CMake_BINARY_DIR}/Tests/Qt4AutogenRerun"
+ ${build_generator_args}
+ --build-project QtAutogenRerun
+ --build-exe-dir "${CMake_BINARY_DIR}/Tests/Qt4AutogenRerun"
+ --force-new-ctest-process
+ --build-options ${build_options}
+ -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}
+ -DQT_TEST_VERSION=4
+ ${QtAutogen_BUILD_OPTIONS}
+ )
+ list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/Qt4AutogenRerun")
+
add_test(Qt4AutoUicInterface ${CMAKE_CTEST_COMMAND}
--build-and-test
"${CMake_SOURCE_DIR}/Tests/QtAutoUicInterface"
@@ -1330,7 +1349,8 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
--build-exe-dir "${CMake_BINARY_DIR}/Tests/Qt4AutoUicInterface"
--force-new-ctest-process
--build-options ${build_options}
- -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE} -DQT_TEST_VERSION=4
+ -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}
+ -DQT_TEST_VERSION=4
--test-command ${run_autouic_test}
)
list(APPEND TEST_BUILD_DIRS "${CMake_BINARY_DIR}/Tests/Qt4AutoUicInterface")
@@ -1394,6 +1414,14 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
add_subdirectory(FindDoxygen)
endif()
+ if(CMake_TEST_FindEXPAT)
+ add_subdirectory(FindEXPAT)
+ endif()
+
+ if(CMake_TEST_FindFreetype)
+ add_subdirectory(FindFreetype)
+ endif()
+
if(CMake_TEST_FindGSL)
add_subdirectory(FindGSL)
endif()
@@ -1447,6 +1475,10 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
add_subdirectory(FindPNG)
endif()
+ if(CMake_TEST_FindPatch)
+ add_subdirectory(FindPatch)
+ endif()
+
if(CMake_TEST_FindProtobuf)
add_subdirectory(FindProtobuf)
endif()
@@ -2082,7 +2114,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
set(reg_nasm "[HKEY_CURRENT_USER\\SOFTWARE\\nasm]")
foreach(reg vs10 vs11 vs12 vs14 ws80 ws81 ws10_0 wp80 wp81 wince tegra nasm)
get_filename_component(r "${reg_${reg}}" ABSOLUTE)
- if(IS_DIRECTORY "${r}")
+ if(IS_DIRECTORY "${r}" AND NOT "${r}" STREQUAL "/registry")
set(${reg} 1)
else()
set(${reg} 0)
@@ -2617,7 +2649,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
file(COPY "${CMake_SOURCE_DIR}/Tests/MumpsCoverage/VistA-FOIA"
DESTINATION "${CMake_BINARY_DIR}/Testing/MumpsCoverage")
add_test(NAME CTestGTMCoverage
- COMMAND cmake -E chdir
+ COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir
${CMake_BINARY_DIR}/Testing/MumpsCoverage
$<TARGET_FILE:ctest> -T Coverage --debug)
set_tests_properties(CTestGTMCoverage PROPERTIES
@@ -2635,7 +2667,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
file(COPY "${CMake_SOURCE_DIR}/Tests/MumpsCoverage/VistA-FOIA"
DESTINATION "${CMake_BINARY_DIR}/Testing/MumpsCacheCoverage")
add_test(NAME CTestCacheCoverage
- COMMAND cmake -E chdir
+ COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir
${CMake_BINARY_DIR}/Testing/MumpsCacheCoverage
$<TARGET_FILE:ctest> -T Coverage --debug)
set_tests_properties(CTestCacheCoverage PROPERTIES
@@ -2653,7 +2685,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
file(COPY "${CMake_SOURCE_DIR}/Tests/PythonCoverage/coveragetest"
DESTINATION "${CMake_BINARY_DIR}/Testing/PythonCoverage")
add_test(NAME CTestPythonCoverage
- COMMAND cmake -E chdir
+ COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir
${CMake_BINARY_DIR}/Testing/PythonCoverage
$<TARGET_FILE:ctest> -T Coverage --debug)
set_tests_properties(CTestPythonCoverage PROPERTIES
@@ -2671,7 +2703,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
file(COPY "${CMake_SOURCE_DIR}/Tests/CoberturaCoverage/src"
DESTINATION "${CMake_BINARY_DIR}/Testing/CoberturaCoverage")
add_test(NAME CTestCoberturaCoverage
- COMMAND cmake -E chdir
+ COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir
${CMake_BINARY_DIR}/Testing/CoberturaCoverage
$<TARGET_FILE:ctest> -T Coverage --debug)
set_tests_properties(CTestCoberturaCoverage PROPERTIES
@@ -2690,7 +2722,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
configure_file("${CMake_BINARY_DIR}/Testing/JacocoCoverage/Coverage/target/site/jacoco.xml.in"
"${CMake_BINARY_DIR}/Testing/JacocoCoverage/Coverage/target/site/jacoco.xml")
add_test(NAME CTestJacocoCoverage
- COMMAND cmake -E chdir
+ COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir
${CMake_BINARY_DIR}/Testing/JacocoCoverage
$<TARGET_FILE:ctest> -T Coverage --debug)
set_tests_properties(CTestJacocoCoverage PROPERTIES
@@ -2709,7 +2741,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
DESTINATION "${CMake_BINARY_DIR}/Testing/JavascriptCoverage"
FILES_MATCHING PATTERN "*.js")
add_test(NAME CTestJavascriptCoverage
- COMMAND cmake -E chdir
+ COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir
${CMake_BINARY_DIR}/Testing/JavascriptCoverage
$<TARGET_FILE:ctest> -T Coverage --debug)
set_tests_properties(CTestJavascriptCoverage PROPERTIES
@@ -2727,7 +2759,7 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
"${CMake_SOURCE_DIR}/Tests/DelphiCoverage/UTCovTest(UTCovTest.pas).html.in"
"${CMake_BINARY_DIR}/Testing/DelphiCoverage/UTCovTest(UTCovTest.pas).html")
add_test(NAME CTestDelphiCoverage
- COMMAND cmake -E chdir
+ COMMAND ${CMAKE_CMAKE_COMMAND} -E chdir
${CMake_BINARY_DIR}/Testing/DelphiCoverage
$<TARGET_FILE:ctest> -T Coverage --debug)
set_tests_properties(CTestDelphiCoverage PROPERTIES
@@ -2785,13 +2817,11 @@ ${CMake_BINARY_DIR}/bin/cmake -DDIR=dev -P ${CMake_SOURCE_DIR}/Utilities/Release
ADD_TEST_MACRO(CMakeCommands.target_compile_definitions target_compile_definitions)
ADD_TEST_MACRO(CMakeCommands.target_compile_options target_compile_options)
- if(CMake_TEST_SERVER_MODE)
- # The cmake server-mode test requires python for a simple client.
- find_package(PythonInterp QUIET)
- if(PYTHON_EXECUTABLE)
- set(Server_BUILD_OPTIONS -DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE})
- ADD_TEST_MACRO(Server Server)
- endif()
+ # The cmake server-mode test requires python for a simple client.
+ find_package(PythonInterp QUIET)
+ if(PYTHON_EXECUTABLE)
+ set(Server_BUILD_OPTIONS -DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE})
+ ADD_TEST_MACRO(Server Server)
endif()
configure_file(
diff --git a/Tests/CMakeServerLib/CMakeLists.txt b/Tests/CMakeServerLib/CMakeLists.txt
new file mode 100644
index 000000000..f5351fd12
--- /dev/null
+++ b/Tests/CMakeServerLib/CMakeLists.txt
@@ -0,0 +1,17 @@
+include_directories(
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${CMake_BINARY_DIR}/Source
+ ${CMake_SOURCE_DIR}/Source
+ )
+
+set(CMakeServerLib_TESTS
+ testServerBuffering
+ )
+
+create_test_sourcelist(CMakeLib_TEST_SRCS CMakeServerLibTests.cxx ${CMakeServerLib_TESTS})
+add_executable(CMakeServerLibTests ${CMakeLib_TEST_SRCS})
+target_link_libraries(CMakeServerLibTests CMakeLib CMakeServerLib)
+
+foreach(test ${CMakeServerLib_TESTS})
+ add_test(CMakeServerLib.${test} CMakeServerLibTests ${test} ${${test}_ARGS})
+endforeach()
diff --git a/Tests/CMakeServerLib/testServerBuffering.cpp b/Tests/CMakeServerLib/testServerBuffering.cpp
new file mode 100644
index 000000000..97be89191
--- /dev/null
+++ b/Tests/CMakeServerLib/testServerBuffering.cpp
@@ -0,0 +1,86 @@
+#include "cmConnection.h"
+#include "cmServerConnection.h"
+#include <iostream>
+#include <stddef.h>
+#include <string>
+#include <vector>
+
+void print_error(const std::vector<std::string>& input,
+ const std::vector<std::string>& output)
+{
+ std::cerr << "Responses don't equal input messages input." << std::endl;
+ std::cerr << "Responses: " << std::endl;
+
+ for (auto& msg : output) {
+ std::cerr << "'" << msg << "'" << std::endl;
+ }
+
+ std::cerr << "Input messages" << std::endl;
+ for (auto& msg : input) {
+ std::cerr << "'" << msg << "'" << std::endl;
+ }
+}
+
+std::string trim_newline(const std::string& _buffer)
+{
+ auto buffer = _buffer;
+ while (!buffer.empty() && (buffer.back() == '\n' || buffer.back() == '\r')) {
+ buffer.pop_back();
+ }
+ return buffer;
+}
+
+int testServerBuffering(int, char** const)
+{
+ std::vector<std::string> messages = {
+ "{ \"test\": 10}", "{ \"test\": { \"test2\": false} }",
+ "{ \"test\": [1, 2, 3] }",
+ "{ \"a\": { \"1\": {}, \n\n\n \"2\":[] \t\t\t\t}}"
+ };
+
+ std::string fullMessage;
+ for (auto& msg : messages) {
+ fullMessage += "[== \"CMake Server\" ==[\n";
+ fullMessage += msg;
+ fullMessage += "\n]== \"CMake Server\" ==]\n";
+ }
+
+ // The buffering strategy should cope with any fragmentation, including
+ // just getting the characters one at a time.
+ auto bufferingStrategy =
+ std::unique_ptr<cmConnectionBufferStrategy>(new cmServerBufferStrategy);
+ std::vector<std::string> response;
+ std::string rawBuffer;
+ for (size_t i = 0; i < fullMessage.size(); i++) {
+ rawBuffer += fullMessage[i];
+ std::string packet = bufferingStrategy->BufferMessage(rawBuffer);
+ do {
+ if (!packet.empty() && packet != "\r\n") {
+ response.push_back(trim_newline(packet));
+ }
+ packet = bufferingStrategy->BufferMessage(rawBuffer);
+ } while (!packet.empty());
+ }
+
+ if (response != messages) {
+ print_error(messages, response);
+ return 1;
+ }
+
+ // We should also be able to deal with getting a bunch at once
+ response.clear();
+ std::string packet = bufferingStrategy->BufferMessage(fullMessage);
+ do {
+ if (!packet.empty() && packet != "\r\n") {
+ response.push_back(trim_newline(packet));
+ }
+ packet = bufferingStrategy->BufferMessage(fullMessage);
+ } while (!packet.empty());
+
+ if (response != messages) {
+ print_error(messages, response);
+ return 1;
+ }
+
+ return 0;
+}
diff --git a/Tests/CMakeTests/.gitattributes b/Tests/CMakeTests/.gitattributes
deleted file mode 100644
index c34e350e5..000000000
--- a/Tests/CMakeTests/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-File-HASH-Input.txt crlf=input
diff --git a/Tests/CMakeTests/CMakeHostSystemInformationTest.cmake.in b/Tests/CMakeTests/CMakeHostSystemInformationTest.cmake.in
index 3294a2f0d..a3c2b055a 100644
--- a/Tests/CMakeTests/CMakeHostSystemInformationTest.cmake.in
+++ b/Tests/CMakeTests/CMakeHostSystemInformationTest.cmake.in
@@ -22,6 +22,25 @@ try_and_print(TOTAL_VIRTUAL_MEMORY)
try_and_print(AVAILABLE_VIRTUAL_MEMORY)
try_and_print(TOTAL_PHYSICAL_MEMORY)
try_and_print(AVAILABLE_PHYSICAL_MEMORY)
+try_and_print(IS_64BIT)
+try_and_print(HAS_FPU)
+try_and_print(HAS_MMX)
+try_and_print(HAS_MMX_PLUS)
+try_and_print(HAS_SSE)
+try_and_print(HAS_SSE2)
+try_and_print(HAS_SSE_FP)
+try_and_print(HAS_SSE_MMX)
+try_and_print(HAS_AMD_3DNOW)
+try_and_print(HAS_AMD_3DNOW_PLUS)
+try_and_print(HAS_IA64)
+try_and_print(HAS_SERIAL_NUMBER)
+try_and_print(PROCESSOR_SERIAL_NUMBER)
+try_and_print(PROCESSOR_NAME)
+try_and_print(PROCESSOR_DESCRIPTION)
+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")
diff --git a/Tests/CMakeTests/PushCheckStateTest.cmake.in b/Tests/CMakeTests/PushCheckStateTest.cmake.in
index b4c48f4f4..cbd879def 100644
--- a/Tests/CMakeTests/PushCheckStateTest.cmake.in
+++ b/Tests/CMakeTests/PushCheckStateTest.cmake.in
@@ -1,3 +1,4 @@
+cmake_minimum_required(VERSION 3.8)
include(CMakePushCheckState)
set(CMAKE_EXTRA_INCLUDE_FILES file1)
@@ -26,6 +27,27 @@ set(CMAKE_REQUIRED_LIBRARIES lib3)
set(CMAKE_REQUIRED_FLAGS flag3)
set(CMAKE_REQUIRED_QUIET 3)
+cmake_push_check_state(RESET)
+
+foreach(pair IN ITEMS
+ EXTRA_INCLUDE_FILES|
+ REQUIRED_INCLUDES|
+ REQUIRED_DEFINITIONS|
+ REQUIRED_LIBRARIES|
+ REQUIRED_FLAGS|
+ REQUIRED_QUIET|
+ )
+ string(REPLACE "|" ";" pair "${pair}")
+ list(GET pair 0 var)
+ list(GET pair 1 expected)
+ if (NOT "${CMAKE_${var}}" STREQUAL "${expected}")
+ set(fatal TRUE)
+ message("ERROR: CMAKE_${var} is \"${CMAKE_${var}}\" (expected \"${expected}\")" )
+ endif()
+endforeach()
+
+cmake_pop_check_state()
+
cmake_pop_check_state()
foreach(pair IN ITEMS
diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend1.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend1.cmake
index 70d6edf49..73fd0abe2 100644
--- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend1.cmake
+++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend1.cmake
@@ -6,7 +6,7 @@ include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake)
# expected results
-set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb")
+set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb")
set(expected_count 3)
diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend2.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend2.cmake
index 415d5360a..81dbbc515 100644
--- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend2.cmake
+++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-depend2.cmake
@@ -6,7 +6,7 @@ include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake)
# expected results
-set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb")
+set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb")
set(expected_count 3)
set(config_verbose -V)
diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description1.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description1.cmake
index 337cc1675..ad52f56b7 100644
--- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description1.cmake
+++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description1.cmake
@@ -6,7 +6,7 @@ include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake)
# expected results
-set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb")
+set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb")
set(expected_count 3)
diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description2.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description2.cmake
index 35ca74cdd..af27c5183 100644
--- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description2.cmake
+++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-description2.cmake
@@ -7,7 +7,7 @@ include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake)
# expected results
-set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb")
+set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb")
set(expected_count 3)
diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake
index f1391cd73..1fe9258b9 100644
--- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake
+++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-lintian-dpkgdeb-checks.cmake
@@ -5,7 +5,7 @@ endif()
include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake)
# TODO: currently debian doens't produce lower cased names
-set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb")
+set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb")
set(expected_count 3)
diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-shlibdeps1.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-shlibdeps1.cmake
index fcfc7eaee..e57488cbb 100644
--- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-shlibdeps1.cmake
+++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-shlibdeps1.cmake
@@ -9,7 +9,7 @@ include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake)
# requirements
# debian now produces lower case names
-set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb")
+set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb")
set(expected_count 3)
diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-source.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-source.cmake
index 351bf2148..5ee057a3d 100644
--- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-source.cmake
+++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-components-source.cmake
@@ -6,7 +6,7 @@ include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake)
# expected results
-set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2-1_*.deb")
+set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib-*_1.0.2_*.deb")
set(expected_count 3)
set(config_verbose -V)
diff --git a/Tests/CPackComponentsDEB/RunCPackVerifyResult-compression.cmake b/Tests/CPackComponentsDEB/RunCPackVerifyResult-compression.cmake
index c97ecb019..13a626a45 100644
--- a/Tests/CPackComponentsDEB/RunCPackVerifyResult-compression.cmake
+++ b/Tests/CPackComponentsDEB/RunCPackVerifyResult-compression.cmake
@@ -5,7 +5,7 @@ endif()
include(${CPackComponentsDEB_SOURCE_DIR}/RunCPackVerifyResult.cmake)
# TODO: currently debian doens't produce lower cased names
-set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib_1.0.2-1_*.deb")
+set(expected_file_mask "${CPackComponentsDEB_BINARY_DIR}/mylib_1.0.2_*.deb")
set(expected_count 1)
set(actual_output)
diff --git a/Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake b/Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake
index a5b38fdb6..2c3a8494a 100644
--- a/Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake
+++ b/Tests/CPackComponentsForAll/RunCPackVerifyResult.cmake
@@ -60,7 +60,7 @@ elseif (CPackGen MATCHES "RPM")
set(expected_count 1)
endif ()
elseif (CPackGen MATCHES "DEB")
- set(expected_file_mask "${CPackComponentsForAll_BINARY_DIR}/mylib*_1.0.2-1_*.deb")
+ set(expected_file_mask "${CPackComponentsForAll_BINARY_DIR}/mylib*_1.0.2_*.deb")
if (${CPackComponentWay} STREQUAL "default")
set(expected_count 1)
elseif (${CPackComponentWay} STREQUAL "OnePackPerGroup")
diff --git a/Tests/CompileFeatures/.gitattributes b/Tests/CompileFeatures/.gitattributes
deleted file mode 100644
index 83da28dac..000000000
--- a/Tests/CompileFeatures/.gitattributes
+++ /dev/null
@@ -1,2 +0,0 @@
-# Do not format a source containing C++11 '>>' syntax as C++98.
-cxx_right_angle_brackets.cpp -format.clang-format
diff --git a/Tests/CompileFeatures/CMakeLists.txt b/Tests/CompileFeatures/CMakeLists.txt
index 4a5558d48..b560acd7e 100644
--- a/Tests/CompileFeatures/CMakeLists.txt
+++ b/Tests/CompileFeatures/CMakeLists.txt
@@ -428,6 +428,14 @@ else()
HAVE_FINAL=$<COMPILE_FEATURES:cxx_final>
HAVE_INHERITING_CONSTRUCTORS_AND_FINAL=$<COMPILE_FEATURES:cxx_inheriting_constructors,cxx_final>
)
+ if (CMAKE_CXX_STANDARD_DEFAULT)
+ target_compile_definitions(CompileFeaturesGenex PRIVATE
+ TEST_CXX_STD
+ HAVE_CXX_STD_11=$<COMPILE_FEATURES:cxx_std_11>
+ HAVE_CXX_STD_14=$<COMPILE_FEATURES:cxx_std_14>
+ HAVE_CXX_STD_17=$<COMPILE_FEATURES:cxx_std_17>
+ )
+ endif()
add_executable(CompileFeaturesGenex2 genex_test.cpp)
target_compile_features(CompileFeaturesGenex2 PRIVATE cxx_std_11)
diff --git a/Tests/CompileFeatures/cxx_digit_separators.cpp b/Tests/CompileFeatures/cxx_digit_separators.cpp
index a40ac0aac..abcd1c8fa 100644
--- a/Tests/CompileFeatures/cxx_digit_separators.cpp
+++ b/Tests/CompileFeatures/cxx_digit_separators.cpp
@@ -1,5 +1,6 @@
int someFunc()
{
- int one_thousand = 1'000; return one_thousand - 1000;
+ int one_thousand = 1'000;
+ return one_thousand - 1000;
}
diff --git a/Tests/CompileFeatures/cxx_raw_string_literals.cpp b/Tests/CompileFeatures/cxx_raw_string_literals.cpp
index ea4d2312c..0f83a7c9a 100644
--- a/Tests/CompileFeatures/cxx_raw_string_literals.cpp
+++ b/Tests/CompileFeatures/cxx_raw_string_literals.cpp
@@ -1,7 +1,7 @@
void someFunc()
{
-const char p[] = R"(a\
+ const char p[] = R"(a\
b
c)";
}
diff --git a/Tests/CompileFeatures/cxx_variadic_templates.cpp b/Tests/CompileFeatures/cxx_variadic_templates.cpp
index 3dc25704d..695123052 100644
--- a/Tests/CompileFeatures/cxx_variadic_templates.cpp
+++ b/Tests/CompileFeatures/cxx_variadic_templates.cpp
@@ -35,7 +35,7 @@ struct eval
};
template <template <typename...> class T, typename... U>
-struct eval<T<U...> >
+struct eval<T<U...>>
{
enum
{
@@ -62,11 +62,11 @@ struct D
// Note: This test assumes that a compiler supporting this feature
// supports static_assert. Add a workaround if that does not hold.
-static_assert(eval<A<> >::Matched, "A Matches");
-static_assert(eval<A<int> >::Matched, "A Matches");
-static_assert(eval<A<int, char> >::Matched, "A Matches");
-static_assert(eval<B<int> >::Matched, "B Matches");
-static_assert(eval<C<int, char> >::Matched, "C Matches");
-static_assert(eval<D<int, char> >::Matched, "D Matches");
-static_assert(eval<D<int, char, bool> >::Matched, "D Matches");
-static_assert(eval<D<int, char, bool, double> >::Matched, "D Matches");
+static_assert(eval<A<>>::Matched, "A Matches");
+static_assert(eval<A<int>>::Matched, "A Matches");
+static_assert(eval<A<int, char>>::Matched, "A Matches");
+static_assert(eval<B<int>>::Matched, "B Matches");
+static_assert(eval<C<int, char>>::Matched, "C Matches");
+static_assert(eval<D<int, char>>::Matched, "D Matches");
+static_assert(eval<D<int, char, bool>>::Matched, "D Matches");
+static_assert(eval<D<int, char, bool, double>>::Matched, "D Matches");
diff --git a/Tests/CompileFeatures/default_dialect.cpp b/Tests/CompileFeatures/default_dialect.cpp
index 9b65b424a..0de11255f 100644
--- a/Tests/CompileFeatures/default_dialect.cpp
+++ b/Tests/CompileFeatures/default_dialect.cpp
@@ -2,25 +2,30 @@
template <long l>
struct Outputter;
+#if defined(_MSC_VER) && defined(_MSVC_LANG)
+#define CXX_STD _MSVC_LANG
+#else
+#define CXX_STD __cplusplus
+#endif
+
#if DEFAULT_CXX17
-#if __cplusplus <= 201402L
-Outputter<__cplusplus> o;
+#if CXX_STD <= 201402L
+Outputter<CXX_STD> o;
#endif
#elif DEFAULT_CXX14
-#if __cplusplus != 201402L
-Outputter<__cplusplus> o;
+#if CXX_STD != 201402L
+Outputter<CXX_STD> o;
#endif
#elif DEFAULT_CXX11
-#if __cplusplus != 201103L
-Outputter<__cplusplus> o;
+#if CXX_STD != 201103L
+Outputter<CXX_STD> o;
#endif
#else
#if !DEFAULT_CXX98
#error Buildsystem error
#endif
-#if __cplusplus != 199711L && __cplusplus != 1 && \
- !defined(__GXX_EXPERIMENTAL_CXX0X__)
-Outputter<__cplusplus> o;
+#if CXX_STD != 199711L && CXX_STD != 1 && !defined(__GXX_EXPERIMENTAL_CXX0X__)
+Outputter<CXX_STD> o;
#endif
#endif
diff --git a/Tests/CompileFeatures/genex_test.cpp b/Tests/CompileFeatures/genex_test.cpp
index 5ae8a7880..5303e738e 100644
--- a/Tests/CompileFeatures/genex_test.cpp
+++ b/Tests/CompileFeatures/genex_test.cpp
@@ -11,6 +11,18 @@
#error EXPECT_OVERRIDE_CONTROL not defined
#endif
+#ifdef TEST_CXX_STD
+#if !HAVE_CXX_STD_11
+#error HAVE_CXX_STD_11 is false with CXX_STANDARD == 11
+#endif
+#if HAVE_CXX_STD_14
+#error HAVE_CXX_STD_14 is true with CXX_STANDARD == 11
+#endif
+#if HAVE_CXX_STD_17
+#error HAVE_CXX_STD_17 is true with CXX_STANDARD == 11
+#endif
+#endif
+
#if !HAVE_OVERRIDE_CONTROL
#if EXPECT_OVERRIDE_CONTROL
#error "Expect override control feature"
diff --git a/Tests/Complex/CMakeLists.txt b/Tests/Complex/CMakeLists.txt
index 075faa768..2e4175442 100644
--- a/Tests/Complex/CMakeLists.txt
+++ b/Tests/Complex/CMakeLists.txt
@@ -356,6 +356,8 @@ endwhile()
set(SHOULD_BE_ZERO )
set(SHOULD_BE_ONE 1)
+set(SHOULD_BE_ZERO_AND_INDENTED )
+set(SHOULD_BE_ONE_AND_INDENTED 1)
# test elseif functionality, the mess below tries to catch problem
# of clauses being executed early or late etc
@@ -438,13 +440,6 @@ set(CMAKE_CXX_STANDARD 98)
#
set(CMAKE_CXX_EXTENSIONS TRUE)
-# Those versions of the HP compiler that need a flag to get proper C++98
-# template support also need a flag to use the newer C++ library.
-if (CMAKE_CXX_COMPILER_ID STREQUAL HP AND
- CMAKE_CXX98_STANDARD_COMPILE_OPTION STREQUAL "+hpxstd98")
- string(APPEND CMAKE_CXX_FLAGS " -AA")
-endif ()
-
# Clang/C2 in C++98 mode cannot properly handle some of MSVC headers
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND
CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
diff --git a/Tests/Complex/Executable/complex.cxx b/Tests/Complex/Executable/complex.cxx
index 3b09229ba..ca39870f2 100644
--- a/Tests/Complex/Executable/complex.cxx
+++ b/Tests/Complex/Executable/complex.cxx
@@ -261,6 +261,12 @@ int main()
cmPassed("ONE_VAR is defined.");
#endif
+#ifndef ONE_VAR_AND_INDENTED
+ cmFailed("cmakedefine is broken, ONE_VAR_AND_INDENTED is not defined.");
+#else
+ cmPassed("ONE_VAR_AND_INDENTED is defined.");
+#endif
+
#ifndef ONE_VAR_IS_DEFINED
cmFailed("cmakedefine, SET or VARIABLE_REQUIRES is broken, "
"ONE_VAR_IS_DEFINED is not defined.");
@@ -274,6 +280,12 @@ int main()
cmPassed("ZERO_VAR is not defined.");
#endif
+#ifdef ZERO_VAR_AND_INDENTED
+ cmFailed("cmakedefine is broken, ZERO_VAR_AND_INDENTED is defined.");
+#else
+ cmPassed("ZERO_VAR_AND_INDENTED is not defined.");
+#endif
+
#ifndef STRING_VAR
cmFailed("the CONFIGURE_FILE command is broken, STRING_VAR is not defined.");
#else
@@ -1030,6 +1042,16 @@ int main()
} else {
cmFailed("cmakedefine01 is not working for 1");
}
+ if (SHOULD_BE_ZERO_AND_INDENTED == 0) {
+ cmPassed("cmakedefine01 is working for 0 and indented");
+ } else {
+ cmFailed("cmakedefine01 is not working for 0 and indented");
+ }
+ if (SHOULD_BE_ONE_AND_INDENTED == 1) {
+ cmPassed("cmakedefine01 is working for 1 and indented");
+ } else {
+ cmFailed("cmakedefine01 is not working for 1 and indented");
+ }
#ifdef FORCE_TEST
cmFailed("CMake SET CACHE FORCE");
#else
diff --git a/Tests/Complex/VarTests.cmake b/Tests/Complex/VarTests.cmake
index 8be59be5e..9761986ab 100644
--- a/Tests/Complex/VarTests.cmake
+++ b/Tests/Complex/VarTests.cmake
@@ -2,6 +2,7 @@
# Test SET
#
set (ZERO_VAR 0)
+set (ZERO_VAR_AND_INDENTED 0)
set (ZERO_VAR2 0)
if(ZERO_VAR)
@@ -11,6 +12,7 @@ else()
endif()
set(ONE_VAR 1)
+set(ONE_VAR_AND_INDENTED 1)
set(ONE_VAR2 1)
set(STRING_VAR "CMake is great" CACHE STRING "test a cache variable")
diff --git a/Tests/Complex/cmTestConfigure.h.in b/Tests/Complex/cmTestConfigure.h.in
index d7424b184..72317bcc8 100644
--- a/Tests/Complex/cmTestConfigure.h.in
+++ b/Tests/Complex/cmTestConfigure.h.in
@@ -1,8 +1,10 @@
// Test SET, VARIABLE_REQUIRES
#cmakedefine ONE_VAR
+# cmakedefine ONE_VAR_AND_INDENTED
#cmakedefine ONE_VAR_IS_DEFINED
#cmakedefine ZERO_VAR
+# cmakedefine ZERO_VAR_AND_INDENTED
#define STRING_VAR "${STRING_VAR}"
@@ -32,6 +34,8 @@
#cmakedefine01 SHOULD_BE_ZERO
#cmakedefine01 SHOULD_BE_ONE
+# cmakedefine01 SHOULD_BE_ZERO_AND_INDENTED
+# cmakedefine01 SHOULD_BE_ONE_AND_INDENTED
// Needed to check for files
#define BINARY_DIR "${Complex_BINARY_DIR}"
diff --git a/Tests/ComplexOneConfig/CMakeLists.txt b/Tests/ComplexOneConfig/CMakeLists.txt
index 1b833b241..628cd4ec3 100644
--- a/Tests/ComplexOneConfig/CMakeLists.txt
+++ b/Tests/ComplexOneConfig/CMakeLists.txt
@@ -313,6 +313,8 @@ endwhile()
set(SHOULD_BE_ZERO )
set(SHOULD_BE_ONE 1)
+set(SHOULD_BE_ZERO_AND_INDENTED )
+set(SHOULD_BE_ONE_AND_INDENTED 1)
# test elseif functionality, the mess below tries to catch problem
# of clauses being executed early or late etc
@@ -395,13 +397,6 @@ set(CMAKE_CXX_STANDARD 98)
#
set(CMAKE_CXX_EXTENSIONS TRUE)
-# Those versions of the HP compiler that need a flag to get proper C++98
-# template support also need a flag to use the newer C++ library.
-if (CMAKE_CXX_COMPILER_ID STREQUAL HP AND
- CMAKE_CXX98_STANDARD_COMPILE_OPTION STREQUAL "+hpxstd98")
- string(APPEND CMAKE_CXX_FLAGS " -AA")
-endif ()
-
# Clang/C2 in C++98 mode cannot properly handle some of MSVC headers
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND
CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
diff --git a/Tests/ComplexOneConfig/Executable/complex.cxx b/Tests/ComplexOneConfig/Executable/complex.cxx
index 9e4eaadf7..9b94962e1 100644
--- a/Tests/ComplexOneConfig/Executable/complex.cxx
+++ b/Tests/ComplexOneConfig/Executable/complex.cxx
@@ -261,6 +261,12 @@ int main()
cmPassed("ONE_VAR is defined.");
#endif
+#ifndef ONE_VAR_AND_INDENTED
+ cmFailed("cmakedefine is broken, ONE_VAR_AND_INDENTED is not defined.");
+#else
+ cmPassed("ONE_VAR_AND_INDENTED is defined.");
+#endif
+
#ifndef ONE_VAR_IS_DEFINED
cmFailed("cmakedefine, SET or VARIABLE_REQUIRES is broken, "
"ONE_VAR_IS_DEFINED is not defined.");
@@ -274,6 +280,12 @@ int main()
cmPassed("ZERO_VAR is not defined.");
#endif
+#ifdef ZERO_VAR_AND_INDENTED
+ cmFailed("cmakedefine is broken, ZERO_VAR_AND_INDENTED is defined.");
+#else
+ cmPassed("ZERO_VAR_AND_INDENTED is not defined.");
+#endif
+
#ifndef STRING_VAR
cmFailed("the CONFIGURE_FILE command is broken, STRING_VAR is not defined.");
#else
@@ -1030,6 +1042,16 @@ int main()
} else {
cmFailed("cmakedefine01 is not working for 1");
}
+ if (SHOULD_BE_ZERO_AND_INDENTED == 0) {
+ cmPassed("cmakedefine01 is working for 0 and indented");
+ } else {
+ cmFailed("cmakedefine01 is not working for 0 and indented");
+ }
+ if (SHOULD_BE_ONE_AND_INDENTED == 1) {
+ cmPassed("cmakedefine01 is working for 1 and indented");
+ } else {
+ cmFailed("cmakedefine01 is not working for 1 and indented");
+ }
#ifdef FORCE_TEST
cmFailed("CMake SET CACHE FORCE");
#else
diff --git a/Tests/ComplexOneConfig/VarTests.cmake b/Tests/ComplexOneConfig/VarTests.cmake
index 7dd851974..42afd19ea 100644
--- a/Tests/ComplexOneConfig/VarTests.cmake
+++ b/Tests/ComplexOneConfig/VarTests.cmake
@@ -2,6 +2,7 @@
# Test SET
#
set (ZERO_VAR 0)
+set (ZERO_VAR_AND_INDENTED 0)
set (ZERO_VAR2 0)
if(ZERO_VAR)
@@ -11,6 +12,7 @@ else()
endif()
set(ONE_VAR 1)
+set(ONE_VAR_AND_INDENTED 1)
set(ONE_VAR2 1)
set(STRING_VAR "CMake is great" CACHE STRING "test a cache variable")
diff --git a/Tests/ComplexOneConfig/cmTestConfigure.h.in b/Tests/ComplexOneConfig/cmTestConfigure.h.in
index d7424b184..72317bcc8 100644
--- a/Tests/ComplexOneConfig/cmTestConfigure.h.in
+++ b/Tests/ComplexOneConfig/cmTestConfigure.h.in
@@ -1,8 +1,10 @@
// Test SET, VARIABLE_REQUIRES
#cmakedefine ONE_VAR
+# cmakedefine ONE_VAR_AND_INDENTED
#cmakedefine ONE_VAR_IS_DEFINED
#cmakedefine ZERO_VAR
+# cmakedefine ZERO_VAR_AND_INDENTED
#define STRING_VAR "${STRING_VAR}"
@@ -32,6 +34,8 @@
#cmakedefine01 SHOULD_BE_ZERO
#cmakedefine01 SHOULD_BE_ONE
+# cmakedefine01 SHOULD_BE_ZERO_AND_INDENTED
+# cmakedefine01 SHOULD_BE_ONE_AND_INDENTED
// Needed to check for files
#define BINARY_DIR "${Complex_BINARY_DIR}"
diff --git a/Tests/Cuda/.clang-format b/Tests/Cuda/.clang-format
deleted file mode 100644
index a77589a2d..000000000
--- a/Tests/Cuda/.clang-format
+++ /dev/null
@@ -1,9 +0,0 @@
----
-# This configuration requires clang-format 3.8 or higher.
-BasedOnStyle: Mozilla
-AlignOperands: false
-AlwaysBreakAfterReturnType: None
-AlwaysBreakAfterDefinitionReturnType: None
-ColumnLimit: 79
-Standard: Cpp11
-...
diff --git a/Tests/Cuda/Complex/CMakeLists.txt b/Tests/Cuda/Complex/CMakeLists.txt
index 450ef487c..a7137e3ae 100644
--- a/Tests/Cuda/Complex/CMakeLists.txt
+++ b/Tests/Cuda/Complex/CMakeLists.txt
@@ -42,7 +42,6 @@ add_executable(CudaComplex main.cpp)
target_link_libraries(CudaComplex PUBLIC CudaComplexMixedLib)
if(APPLE)
- # We need to add the default path to the driver (libcuda.dylib) as an rpath, so that
- # the static cuda runtime can find it at runtime.
- target_link_libraries(CudaComplex PRIVATE -Wl,-rpath,/usr/local/cuda/lib)
+ # Help the static cuda runtime find the driver (libcuda.dyllib) at runtime.
+ set_property(TARGET CudaComplex PROPERTY BUILD_RPATH ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES})
endif()
diff --git a/Tests/Cuda/ObjectLibrary/CMakeLists.txt b/Tests/Cuda/ObjectLibrary/CMakeLists.txt
index 1d93be732..276dc9225 100644
--- a/Tests/Cuda/ObjectLibrary/CMakeLists.txt
+++ b/Tests/Cuda/ObjectLibrary/CMakeLists.txt
@@ -10,8 +10,8 @@ add_library(CudaMixedObjectLib OBJECT static.cu static.cpp)
add_executable(CudaObjectLibrary
main.cpp
$<TARGET_OBJECTS:CudaMixedObjectLib>)
+
if(APPLE)
- # We need to add the default path to the driver (libcuda.dylib) as an rpath, so that
- # the static cuda runtime can find it at runtime.
- target_link_libraries(CudaObjectLibrary PRIVATE -Wl,-rpath,/usr/local/cuda/lib)
+ # Help the static cuda runtime find the driver (libcuda.dyllib) at runtime.
+ set_property(TARGET CudaObjectLibrary PROPERTY BUILD_RPATH ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES})
endif()
diff --git a/Tests/Cuda/WithC/CMakeLists.txt b/Tests/Cuda/WithC/CMakeLists.txt
index 1f25ab43e..831ce12c9 100644
--- a/Tests/Cuda/WithC/CMakeLists.txt
+++ b/Tests/Cuda/WithC/CMakeLists.txt
@@ -6,7 +6,6 @@ string(APPEND CMAKE_CUDA_FLAGS " -gencode arch=compute_30,code=compute_30")
add_executable(CudaWithC main.c cuda.cu)
if(APPLE)
- # We need to add the default path to the driver (libcuda.dylib) as an rpath, so that
- # the static cuda runtime can find it at runtime.
- target_link_libraries(CudaWithC PRIVATE -Wl,-rpath,/usr/local/cuda/lib)
+ # Help the static cuda runtime find the driver (libcuda.dyllib) at runtime.
+ set_property(TARGET CudaWithC PROPERTY BUILD_RPATH ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES})
endif()
diff --git a/Tests/CudaOnly/.clang-format b/Tests/CudaOnly/.clang-format
deleted file mode 100644
index a77589a2d..000000000
--- a/Tests/CudaOnly/.clang-format
+++ /dev/null
@@ -1,9 +0,0 @@
----
-# This configuration requires clang-format 3.8 or higher.
-BasedOnStyle: Mozilla
-AlignOperands: false
-AlwaysBreakAfterReturnType: None
-AlwaysBreakAfterDefinitionReturnType: None
-ColumnLimit: 79
-Standard: Cpp11
-...
diff --git a/Tests/CudaOnly/ExportPTX/CMakeLists.txt b/Tests/CudaOnly/ExportPTX/CMakeLists.txt
index 10249c614..65d524339 100644
--- a/Tests/CudaOnly/ExportPTX/CMakeLists.txt
+++ b/Tests/CudaOnly/ExportPTX/CMakeLists.txt
@@ -67,9 +67,8 @@ target_compile_definitions(CudaOnlyExportPTX PRIVATE
"CONFIG_TYPE=gen_$<LOWER_CASE:$<CONFIG>>")
if(APPLE)
- # We need to add the default path to the driver (libcuda.dylib) as an rpath, so that
- # the static cuda runtime can find it at runtime.
- target_link_libraries(CudaOnlyExportPTX PRIVATE -Wl,-rpath,/usr/local/cuda/lib)
+ # Help the static cuda runtime find the driver (libcuda.dyllib) at runtime.
+ set_property(TARGET CudaOnlyExportPTX PROPERTY BUILD_RPATH ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES})
endif()
#Verify that we can install object targets properly
diff --git a/Tests/CudaOnly/ResolveDeviceSymbols/CMakeLists.txt b/Tests/CudaOnly/ResolveDeviceSymbols/CMakeLists.txt
index b96bb984b..8d6551b7c 100644
--- a/Tests/CudaOnly/ResolveDeviceSymbols/CMakeLists.txt
+++ b/Tests/CudaOnly/ResolveDeviceSymbols/CMakeLists.txt
@@ -46,7 +46,6 @@ add_executable(CudaOnlyResolveDeviceSymbols main.cu)
target_link_libraries(CudaOnlyResolveDeviceSymbols PRIVATE CUDAResolveDeviceLib)
if(APPLE)
- # We need to add the default path to the driver (libcuda.dylib) as an rpath, so that
- # the static cuda runtime can find it at runtime.
- target_link_libraries(CudaOnlyResolveDeviceSymbols PRIVATE -Wl,-rpath,/usr/local/cuda/lib)
+ # Help the static cuda runtime find the driver (libcuda.dyllib) at runtime.
+ set_property(TARGET CudaOnlyResolveDeviceSymbols PROPERTY BUILD_RPATH ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES})
endif()
diff --git a/Tests/CudaOnly/SeparateCompilation/CMakeLists.txt b/Tests/CudaOnly/SeparateCompilation/CMakeLists.txt
index 3d4a17073..7ef626f67 100644
--- a/Tests/CudaOnly/SeparateCompilation/CMakeLists.txt
+++ b/Tests/CudaOnly/SeparateCompilation/CMakeLists.txt
@@ -48,8 +48,7 @@ if (CMAKE_GENERATOR MATCHES "^Visual Studio")
PROPERTIES CUDA_SEPARABLE_COMPILATION ON)
endif()
-if (APPLE)
- # We need to add the default path to the driver (libcuda.dylib) as an rpath, so that
- # the static cuda runtime can find it at runtime.
- target_link_libraries(CudaOnlySeparateCompilation PRIVATE -Wl,-rpath,/usr/local/cuda/lib)
+if(APPLE)
+ # Help the static cuda runtime find the driver (libcuda.dyllib) at runtime.
+ set_property(TARGET CudaOnlySeparateCompilation PROPERTY BUILD_RPATH ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES})
endif()
diff --git a/Tests/CudaOnly/WithDefs/CMakeLists.txt b/Tests/CudaOnly/WithDefs/CMakeLists.txt
index e25f141ea..9b823667f 100644
--- a/Tests/CudaOnly/WithDefs/CMakeLists.txt
+++ b/Tests/CudaOnly/WithDefs/CMakeLists.txt
@@ -4,7 +4,11 @@ project (CudaOnlyWithDefs CUDA)
#verify that we can pass explicit cuda arch flags
string(APPEND CMAKE_CUDA_FLAGS " -gencode arch=compute_30,code=compute_30")
-set(debug_compile_flags --generate-code arch=compute_20,code=sm_20)
+if(CMAKE_CUDA_COMPILER_VERSION VERSION_GREATER_EQUAL 9)
+ set(debug_compile_flags --generate-code arch=compute_32,code=sm_32)
+else()
+ set(debug_compile_flags --generate-code arch=compute_20,code=sm_20)
+endif()
if(CMAKE_CUDA_SIMULATE_ID STREQUAL "MSVC")
list(APPEND debug_compile_flags -Xcompiler=-WX)
else()
@@ -37,8 +41,7 @@ target_compile_definitions(CudaOnlyWithDefs
$<$<CONFIG:RELEASE>:$<BUILD_INTERFACE:${release_compile_defs}>>
)
-#we need to add an rpath for the cuda library so that everything
-#loads properly on the mac
-if(CMAKE_SYSTEM_NAME MATCHES "Darwin")
- set_target_properties(CudaOnlyWithDefs PROPERTIES LINK_FLAGS "-Wl,-rpath,${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES}")
+if(APPLE)
+ # Help the static cuda runtime find the driver (libcuda.dyllib) at runtime.
+ set_property(TARGET CudaOnlyWithDefs PROPERTY BUILD_RPATH ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES})
endif()
diff --git a/Tests/FindEXPAT/CMakeLists.txt b/Tests/FindEXPAT/CMakeLists.txt
new file mode 100644
index 000000000..a74174a30
--- /dev/null
+++ b/Tests/FindEXPAT/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindEXPAT.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindEXPAT/Test"
+ "${CMake_BINARY_DIR}/Tests/FindEXPAT/Test"
+ ${build_generator_args}
+ --build-project TestFindEXPAT
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindEXPAT/Test/CMakeLists.txt b/Tests/FindEXPAT/Test/CMakeLists.txt
new file mode 100644
index 000000000..5681f7471
--- /dev/null
+++ b/Tests/FindEXPAT/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.9)
+project(TestFindEXPAT C)
+include(CTest)
+
+find_package(EXPAT REQUIRED)
+
+add_definitions(-DCMAKE_EXPECTED_EXPAT_VERSION="${EXPAT_VERSION_STRING}")
+
+add_executable(testexpat_tgt main.c)
+target_link_libraries(testexpat_tgt EXPAT::EXPAT)
+add_test(NAME testexpat_tgt COMMAND testexpat_tgt)
+
+add_executable(testexpat_var main.c)
+target_include_directories(testexpat_var PRIVATE ${EXPAT_INCLUDE_DIRS})
+target_link_libraries(testexpat_var PRIVATE ${EXPAT_LIBRARIES})
+add_test(NAME testexpat_var COMMAND testexpat_var)
diff --git a/Tests/FindEXPAT/Test/main.c b/Tests/FindEXPAT/Test/main.c
new file mode 100644
index 000000000..94ee3ef24
--- /dev/null
+++ b/Tests/FindEXPAT/Test/main.c
@@ -0,0 +1,21 @@
+#include <expat.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+int main()
+{
+ XML_Expat_Version expat_version;
+ char expat_version_string[16];
+
+ expat_version = XML_ExpatVersionInfo();
+
+ snprintf(expat_version_string, 16, "%i.%i.%i", expat_version.major,
+ expat_version.minor, expat_version.micro);
+
+ if (strcmp(expat_version_string, CMAKE_EXPECTED_EXPAT_VERSION) != 0) {
+ return EXIT_FAILURE;
+ }
+
+ return EXIT_SUCCESS;
+}
diff --git a/Tests/FindFreetype/CMakeLists.txt b/Tests/FindFreetype/CMakeLists.txt
new file mode 100644
index 000000000..490c25bd6
--- /dev/null
+++ b/Tests/FindFreetype/CMakeLists.txt
@@ -0,0 +1,10 @@
+add_test(NAME FindFreetype.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindFreetype/Test"
+ "${CMake_BINARY_DIR}/Tests/FindFreetype/Test"
+ ${build_generator_args}
+ --build-project TestFindFreetype
+ --build-options ${build_options}
+ --test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
+ )
diff --git a/Tests/FindFreetype/Test/CMakeLists.txt b/Tests/FindFreetype/Test/CMakeLists.txt
new file mode 100644
index 000000000..bc869a13f
--- /dev/null
+++ b/Tests/FindFreetype/Test/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.9)
+project(TestFindFreetype C)
+include(CTest)
+
+find_package(Freetype REQUIRED)
+
+add_definitions(-DCMAKE_EXPECTED_FREETYPE_VERSION="${FREETYPE_VERSION_STRING}")
+
+add_executable(testfreetype_tgt main.c)
+target_link_libraries(testfreetype_tgt Freetype::Freetype)
+add_test(NAME testfreetype_tgt COMMAND testfreetype_tgt)
+
+add_executable(testfreetype_var main.c)
+target_include_directories(testfreetype_var PRIVATE ${FREETYPE_INCLUDE_DIRS})
+target_link_libraries(testfreetype_var PRIVATE ${FREETYPE_LIBRARIES})
+add_test(NAME testfreetype_var COMMAND testfreetype_var)
diff --git a/Tests/FindFreetype/Test/main.c b/Tests/FindFreetype/Test/main.c
new file mode 100644
index 000000000..bb838a5ce
--- /dev/null
+++ b/Tests/FindFreetype/Test/main.c
@@ -0,0 +1,34 @@
+#include <ft2build.h>
+#include <stdlib.h>
+#include FT_FREETYPE_H
+#include <string.h>
+
+int main()
+{
+ FT_Library library;
+ FT_Error error;
+
+ error = FT_Init_FreeType(&library);
+ if (error) {
+ return EXIT_FAILURE;
+ }
+
+ FT_Int major = 0;
+ FT_Int minor = 0;
+ FT_Int patch = 0;
+ FT_Library_Version(library, &major, &minor, &patch);
+
+ char ft_version_string[16];
+ snprintf(ft_version_string, 16, "%i.%i.%i", major, minor, patch);
+
+ if (strcmp(ft_version_string, CMAKE_EXPECTED_FREETYPE_VERSION) != 0) {
+ return EXIT_FAILURE;
+ }
+
+ error = FT_Done_FreeType(library);
+ if (error) {
+ return EXIT_FAILURE;
+ }
+
+ return EXIT_SUCCESS;
+}
diff --git a/Tests/FindGTest/Test/main.cxx b/Tests/FindGTest/Test/main.cxx
index 0572a5ddc..19d29675b 100644
--- a/Tests/FindGTest/Test/main.cxx
+++ b/Tests/FindGTest/Test/main.cxx
@@ -2,5 +2,7 @@
TEST(FindCMake, LinksAndRuns)
{
+ using namespace testing;
+ EXPECT_FALSE(GTEST_FLAG(list_tests));
ASSERT_TRUE(true);
}
diff --git a/Tests/FindMPI/Test/CMakeLists.txt b/Tests/FindMPI/Test/CMakeLists.txt
index 3910c254f..efe8c6261 100644
--- a/Tests/FindMPI/Test/CMakeLists.txt
+++ b/Tests/FindMPI/Test/CMakeLists.txt
@@ -20,12 +20,17 @@ foreach(c C CXX Fortran)
endif()
endforeach()
+set(MPI_CXX_SKIP_MPICXX TRUE)
+set(MPI_CXX_VALIDATE_SKIP_MPICXX TRUE)
find_package(MPI REQUIRED)
foreach(c C CXX Fortran)
if(NOT "${MPI_TEST_${c}}")
continue()
endif()
+ if(${c} STREQUAL CXX AND MPI_MPICXX_FOUND)
+ message(FATAL_ERROR "Could not suppress MPI-2 C++ bindings for this MPI.")
+ endif()
source_code_mapper_helper(${c})
add_executable(test_tgt_${c} ${MPITEST_SOURCE_FILE})
target_link_libraries(test_tgt_${c} MPI::MPI_${c})
diff --git a/Tests/FindOpenGL/CMakeLists.txt b/Tests/FindOpenGL/CMakeLists.txt
index 9aa3abafb..97c9e6052 100644
--- a/Tests/FindOpenGL/CMakeLists.txt
+++ b/Tests/FindOpenGL/CMakeLists.txt
@@ -1,3 +1,9 @@
+if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMake_TEST_FindOpenGL_VND)
+ set(_vnd_testing TRUE)
+else()
+ set(_vnd_testing FALSE)
+endif()
+
add_test(NAME FindOpenGL.Test COMMAND
${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
--build-and-test
@@ -6,5 +12,6 @@ add_test(NAME FindOpenGL.Test COMMAND
${build_generator_args}
--build-project TestFindOpenGL
--build-options ${build_options}
+ -DOpenGL_TEST_VND=${_vnd_testing}
--test-command ${CMAKE_CTEST_COMMAND} -V -C $<CONFIGURATION>
)
diff --git a/Tests/FindOpenGL/Test/CMakeLists.txt b/Tests/FindOpenGL/Test/CMakeLists.txt
index cac342488..3b5ffeecd 100644
--- a/Tests/FindOpenGL/Test/CMakeLists.txt
+++ b/Tests/FindOpenGL/Test/CMakeLists.txt
@@ -1,14 +1,70 @@
-cmake_minimum_required(VERSION 3.7)
+cmake_minimum_required(VERSION 3.9)
project(TestFindOpenGL C)
include(CTest)
find_package(OpenGL REQUIRED)
+# import target for GLU
add_executable(test_tgt main.c)
target_link_libraries(test_tgt OpenGL::GLU)
add_test(NAME test_tgt COMMAND test_tgt)
+# OPENGL_LIBRARIES should be whatever libraries are needed to link.
add_executable(test_var main.c)
target_include_directories(test_var PRIVATE ${OPENGL_INGLUDE_DIRS})
target_link_libraries(test_var PRIVATE ${OPENGL_LIBRARIES})
add_test(NAME test_var COMMAND test_var)
+
+# VND support adds an ::OpenGL import target. This can be used for OpenGL-only
+# code (code that does not manipulate contexts, like our 'main.c'). Without
+# VND, ::GL can be used for both context and non-context OpenGL code.
+if(OpenGL_TEST_VND)
+ add_executable(test_comp_none main.c)
+ target_link_libraries(test_comp_none PRIVATE OpenGL::OpenGL)
+ add_test(NAME test_comp_none COMMAND test_comp_none)
+else()
+ add_executable(test_comp_none main.c)
+ target_link_libraries(test_comp_none PRIVATE OpenGL::GL)
+ add_test(NAME test_comp_none COMMAND test_comp_none)
+endif()
+
+# GLX
+if(OpenGL_TEST_VND)
+ find_package(OpenGL REQUIRED COMPONENTS OpenGL GLX)
+ add_executable(test_comp_glx main.c)
+ target_link_libraries(test_comp_glx PRIVATE OpenGL::OpenGL OpenGL::GLX)
+ add_test(NAME test_comp_glx COMMAND test_comp_glx)
+else()
+ # non-VND systems won't have it, but an optional search for GLX should still
+ # be okay.
+ find_package(OpenGL COMPONENTS GLX)
+ add_executable(test_comp_glx_novnd main.c)
+ target_link_libraries(test_comp_glx_novnd PRIVATE OpenGL::GL)
+ add_test(NAME test_comp_glx_novnd COMMAND test_comp_glx_novnd)
+endif()
+
+# EGL is only available on Linux+GLVND at present.
+if(OpenGL_TEST_VND)
+ find_package(OpenGL COMPONENTS OpenGL EGL)
+ if(OpenGL_EGL_FOUND)
+ add_executable(test_comp_egl main.c)
+ target_link_libraries(test_comp_egl PRIVATE OpenGL::OpenGL OpenGL::EGL)
+ add_test(NAME test_comp_egl COMMAND test_comp_egl)
+ # EGL-only code should not link to GLX.
+ execute_process(COMMAND ldd test_comp_egl
+ OUTPUT_VARIABLE LDD_OUT
+ ERROR_VARIABLE LDD_ERR)
+ if("${LDD_OUT}" MATCHES "GLX")
+ message(FATAL_ERROR "EGL-only code links to GLX!")
+ endif()
+ endif()
+
+ # all three COMPONENTS together.
+ find_package(OpenGL COMPONENTS OpenGL EGL GLX)
+ if(OpenGL_EGL_FOUND AND OpenGL_GLX_FOUND)
+ add_executable(test_comp_both main.c)
+ target_link_libraries(test_comp_both PRIVATE OpenGL::OpenGL OpenGL::EGL
+ OpenGL::GLX)
+ add_test(NAME test_comp_both COMMAND test_comp_both)
+ endif()
+endif()
diff --git a/Tests/FindPatch/CMakeLists.txt b/Tests/FindPatch/CMakeLists.txt
new file mode 100644
index 000000000..541f5bd15
--- /dev/null
+++ b/Tests/FindPatch/CMakeLists.txt
@@ -0,0 +1,8 @@
+add_test(NAME FindPatch.Test COMMAND
+ ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION>
+ --build-and-test
+ "${CMake_SOURCE_DIR}/Tests/FindPatch/Test"
+ "${CMake_BINARY_DIR}/Tests/FindPatch/Test"
+ ${build_generator_args}
+ --build-options ${build_options}
+)
diff --git a/Tests/FindPatch/Test/CMakeLists.txt b/Tests/FindPatch/Test/CMakeLists.txt
new file mode 100644
index 000000000..f4cd621d1
--- /dev/null
+++ b/Tests/FindPatch/Test/CMakeLists.txt
@@ -0,0 +1,77 @@
+cmake_minimum_required(VERSION 3.8)
+project(TestFindPatch VERSION 1.0 LANGUAGES NONE)
+
+macro(_check)
+ if(NOT EXISTS "${Patch_EXECUTABLE}")
+ message(FATAL_ERROR "Failed to lookup Patch_EXECUTABLE [${Patch_EXECUTABLE}]")
+ endif()
+
+ if(NOT DEFINED PATCH_FOUND)
+ message(FATAL_ERROR "Variable PATCH_FOUND is not defined")
+ endif()
+
+ # Is import target available ?
+ if(NOT TARGET Patch::patch)
+ message(FATAL_ERROR "Target Patch::patch is not defined")
+ endif()
+
+ # Check Patch::patch imported location
+ get_property(_imported_location TARGET Patch::patch PROPERTY IMPORTED_LOCATION)
+ if(NOT "${Patch_EXECUTABLE}" STREQUAL "${_imported_location}")
+ message(FATAL_ERROR "\
+Patch_EXECUTABLE is expected to be equal to Patch::patch IMPORTED_LOCATION
+ Patch_EXECUTABLE [${Patch_EXECUTABLE}]
+ Patch::patch IMPORTED_LOCATION [${_imported_location}]
+")
+ endif()
+
+endmacro()
+
+find_package(Patch REQUIRED)
+_check()
+
+# Calling twice should not fail
+find_package(Patch REQUIRED)
+_check()
+
+add_custom_target(TestPatchVersion ALL
+ COMMAND ${Patch_EXECUTABLE} -v
+ )
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/QUOTE.txt.baseline"
+[=[Because it's there.
+- George Mallory, 1923
+]=]
+)
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/QUOTE.txt" "Because it's there.\n")
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/quote-add-author.patch"
+[=[diff --git a/QUOTE.txt b/QUOTE.txt
+index b36681d..68059b3 100644
+--- a/QUOTE.txt
++++ b/QUOTE.txt
+@@ -1 +1,2 @@
+ Because it's there.
++- George Mallory
+]=]
+)
+
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/quote-add-date.patch"
+[=[diff --git a/QUOTE.txt b/QUOTE.txt
+index 68059b3..c6f30c2 100644
+--- a/QUOTE.txt
++++ b/QUOTE.txt
+@@ -1,2 +1,2 @@
+ Because it's there.
+-- George Mallory
++- George Mallory, 1923
+]=]
+)
+
+add_custom_target(TestPatch ALL
+ COMMAND ${Patch_EXECUTABLE} -p1 -i quote-add-author.patch
+ COMMAND Patch::patch -p1 -i quote-add-date.patch
+ COMMAND ${CMAKE_COMMAND} -E compare_files QUOTE.txt QUOTE.txt.baseline
+ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
+ )
diff --git a/Tests/FindProtobuf/Test/CMakeLists.txt b/Tests/FindProtobuf/Test/CMakeLists.txt
index 8b6e38a8e..bc89190b3 100644
--- a/Tests/FindProtobuf/Test/CMakeLists.txt
+++ b/Tests/FindProtobuf/Test/CMakeLists.txt
@@ -1,4 +1,4 @@
-cmake_minimum_required(VERSION 3.4)
+cmake_minimum_required(VERSION 3.8)
project(TestFindProtobuf CXX)
include(CTest)
@@ -30,3 +30,21 @@ add_executable(test_var_protoc main-protoc.cxx)
target_include_directories(test_var_protoc PRIVATE ${Protobuf_INCLUDE_DIRS})
target_link_libraries(test_var_protoc PRIVATE ${Protobuf_PROTOC_LIBRARIES})
add_test(NAME test_var_protoc COMMAND test_var_protoc)
+
+add_test(NAME test_tgt_protoc_version COMMAND protobuf::protoc --version)
+
+set(Protobuf_IMPORT_DIRS ${Protobuf_INCLUDE_DIRS})
+PROTOBUF_GENERATE_CPP(PROTO_SRC PROTO_HEADER msgs/example.proto)
+PROTOBUF_GENERATE_CPP(DESC_PROTO_SRC DESC_PROTO_HEADER DESCRIPTORS DESC_PROTO_DESC msgs/example_desc.proto)
+add_library(msgs ${PROTO_SRC} ${PROTO_HEADER})
+
+add_executable(test_generate main-generate.cxx ${PROTO_SRC})
+target_include_directories(test_generate PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
+target_link_libraries(test_generate msgs ${Protobuf_LIBRARIES})
+add_test(NAME test_generate COMMAND test_generate)
+
+add_executable(test_desc main-desc.cxx ${DESC_PROTO_SRC})
+target_compile_features(test_desc PRIVATE cxx_std_11)
+target_include_directories(test_desc PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
+target_link_libraries(test_desc msgs ${Protobuf_LIBRARIES})
+add_test(NAME test_desc COMMAND test_desc ${DESC_PROTO_DESC})
diff --git a/Tests/FindProtobuf/Test/main-desc.cxx b/Tests/FindProtobuf/Test/main-desc.cxx
new file mode 100644
index 000000000..a26e562d5
--- /dev/null
+++ b/Tests/FindProtobuf/Test/main-desc.cxx
@@ -0,0 +1,57 @@
+#include <fstream>
+#include <google/protobuf/descriptor.h>
+#include <google/protobuf/descriptor.pb.h>
+#include <google/protobuf/dynamic_message.h>
+#include <google/protobuf/text_format.h>
+#include <iostream>
+#include <string>
+
+int main(int argc, char* argv[])
+{
+ std::ifstream fs;
+ fs.open(argv[1], std::ifstream::in);
+ google::protobuf::FileDescriptorSet file_descriptor_set;
+ file_descriptor_set.ParseFromIstream(&fs);
+
+ const google::protobuf::DescriptorPool* compiled_pool =
+ google::protobuf::DescriptorPool::generated_pool();
+
+ if (compiled_pool == NULL) {
+ std::cerr << "compiled pool is NULL." << std::endl;
+ return 1;
+ }
+
+ google::protobuf::DescriptorPool pool(compiled_pool);
+ google::protobuf::DynamicMessageFactory dynamic_message_factory(&pool);
+
+ for (const google::protobuf::FileDescriptorProto& file_descriptor_proto :
+ file_descriptor_set.file()) {
+ const google::protobuf::FileDescriptor* file_descriptor =
+ pool.BuildFile(file_descriptor_proto);
+ if (file_descriptor == NULL) {
+ continue;
+ }
+
+ const google::protobuf::Descriptor* descriptor =
+ pool.FindMessageTypeByName("example.msgs.ExampleDesc");
+
+ if (descriptor == NULL) {
+ continue;
+ }
+
+ google::protobuf::Message* msg =
+ dynamic_message_factory.GetPrototype(descriptor)->New();
+ std::string data = "data: 1";
+ bool success = google::protobuf::TextFormat::ParseFromString(data, msg);
+
+ if (success) {
+ return 0;
+ } else {
+ std::cerr << "Failed to parse message." << std::endl;
+ return 2;
+ }
+ }
+
+ std::cerr << "No matching message found." << std::endl;
+ return 3;
+}
diff --git a/Tests/FindProtobuf/Test/main-generate.cxx b/Tests/FindProtobuf/Test/main-generate.cxx
new file mode 100644
index 000000000..ca33a6856
--- /dev/null
+++ b/Tests/FindProtobuf/Test/main-generate.cxx
@@ -0,0 +1,8 @@
+#include <example.pb.h>
+
+int main()
+{
+ example::msgs::Example msg;
+
+ return 0;
+}
diff --git a/Tests/FindProtobuf/Test/msgs/example.proto b/Tests/FindProtobuf/Test/msgs/example.proto
new file mode 100644
index 000000000..d27262e1d
--- /dev/null
+++ b/Tests/FindProtobuf/Test/msgs/example.proto
@@ -0,0 +1,6 @@
+syntax = "proto2";
+package example.msgs;
+
+message Example {
+ required int32 data = 1;
+}
diff --git a/Tests/FindProtobuf/Test/msgs/example_desc.proto b/Tests/FindProtobuf/Test/msgs/example_desc.proto
new file mode 100644
index 000000000..44544736d
--- /dev/null
+++ b/Tests/FindProtobuf/Test/msgs/example_desc.proto
@@ -0,0 +1,10 @@
+syntax = "proto2";
+package example.msgs;
+
+import "google/protobuf/descriptor.proto";
+
+message ExampleDesc {
+ required int32 data = 1;
+
+ optional google.protobuf.FileDescriptorSet desc = 2;
+}
diff --git a/Tests/GeneratorExpression/CMakeLists.txt b/Tests/GeneratorExpression/CMakeLists.txt
index 8ac341912..83fd11d65 100644
--- a/Tests/GeneratorExpression/CMakeLists.txt
+++ b/Tests/GeneratorExpression/CMakeLists.txt
@@ -258,11 +258,13 @@ add_custom_target(check-part4 ALL
VERBATIM
)
+add_executable(srcgenex srcgenex.c)
+set_property(SOURCE srcgenex.c PROPERTY COMPILE_FLAGS "-DNAME=$<TARGET_PROPERTY:NAME>")
+
#-----------------------------------------------------------------------------
# Cover test properties with generator expressions.
add_executable(echo echo.c)
add_executable(pwd pwd.c)
-set_property(SOURCE echo.c PROPERTY COMPILE_FLAGS $<1:-DSRC_GENEX_WORKS>)
add_test(NAME echo-configuration COMMAND echo $<CONFIGURATION>)
set_property(TEST echo-configuration PROPERTY
diff --git a/Tests/GeneratorExpression/echo.c b/Tests/GeneratorExpression/echo.c
index 41596a21d..06b0844b3 100644
--- a/Tests/GeneratorExpression/echo.c
+++ b/Tests/GeneratorExpression/echo.c
@@ -3,9 +3,6 @@
int main(int argc, char* argv[])
{
-#ifndef SRC_GENEX_WORKS
-#error SRC_GENEX_WORKS not defined
-#endif
printf("%s\n", argv[1]);
return EXIT_SUCCESS;
}
diff --git a/Tests/GeneratorExpression/srcgenex.c b/Tests/GeneratorExpression/srcgenex.c
new file mode 100644
index 000000000..56d3c3f95
--- /dev/null
+++ b/Tests/GeneratorExpression/srcgenex.c
@@ -0,0 +1,12 @@
+int srcgenex(void)
+{
+ return 0;
+}
+
+int main(int argc, char* argv[])
+{
+#ifndef NAME
+#error NAME not defined
+#endif
+ return NAME();
+}
diff --git a/Tests/InterfaceLibrary/CMakeLists.txt b/Tests/InterfaceLibrary/CMakeLists.txt
index 33c4b9073..3db210a5d 100644
--- a/Tests/InterfaceLibrary/CMakeLists.txt
+++ b/Tests/InterfaceLibrary/CMakeLists.txt
@@ -64,7 +64,6 @@ target_link_libraries(iface_whitelist INTERFACE $<$<BOOL:$<TARGET_PROPERTY:CUSTO
add_executable(exec_whitelist dummy.cpp)
target_link_libraries(exec_whitelist iface_whitelist)
-set(CMAKE_NO_SYSTEM_FROM_IMPORTED 1)
add_library(iface_imported INTERFACE IMPORTED)
set_property(TARGET iface_imported PROPERTY
INTERFACE_COMPILE_DEFINITIONS
diff --git a/Tests/LoadCommand/CMakeLists.txt b/Tests/LoadCommand/CMakeLists.txt
index 03a3b4942..cfaebade4 100644
--- a/Tests/LoadCommand/CMakeLists.txt
+++ b/Tests/LoadCommand/CMakeLists.txt
@@ -22,13 +22,6 @@ else()
${LoadCommand_SOURCE_DIR}/CMakeCommands
CMAKE_LOADED_COMMANDS CMAKE_FLAGS -DMUDSLIDE_TYPE:STRING=MUCHO
OUTPUT_VARIABLE OUTPUT )
-# do another TRY_COMPILE to get around make
-# problem on hp
- try_compile(COMPILE_OK
- ${LoadCommand_BINARY_DIR}/CMakeCommands
- ${LoadCommand_SOURCE_DIR}/CMakeCommands
- CMAKE_LOADED_COMMANDS CMAKE_FLAGS -DMUDSLIDE_TYPE:STRING=MUCHO
- OUTPUT_VARIABLE OUTPUT )
endif()
message("Output from try compile: ${OUTPUT}")
diff --git a/Tests/LoadCommandOneConfig/CMakeLists.txt b/Tests/LoadCommandOneConfig/CMakeLists.txt
index 6affd343f..65de04230 100644
--- a/Tests/LoadCommandOneConfig/CMakeLists.txt
+++ b/Tests/LoadCommandOneConfig/CMakeLists.txt
@@ -28,13 +28,6 @@ else()
${LoadCommand_SOURCE_DIR}/CMakeCommands
CMAKE_LOADED_COMMANDS CMAKE_FLAGS -DMUDSLIDE_TYPE:STRING=MUCHO
OUTPUT_VARIABLE OUTPUT )
-# do another TRY_COMPILE to get around make
-# problem on hp
- try_compile(COMPILE_OK
- ${LoadCommand_BINARY_DIR}/CMakeCommands
- ${LoadCommand_SOURCE_DIR}/CMakeCommands
- CMAKE_LOADED_COMMANDS CMAKE_FLAGS -DMUDSLIDE_TYPE:STRING=MUCHO
- OUTPUT_VARIABLE OUTPUT )
endif()
message("Output from try compile: ${OUTPUT}")
diff --git a/Tests/MFC/CMakeLists.txt.in b/Tests/MFC/CMakeLists.txt.in
index e6bfabd33..bf98e918c 100644
--- a/Tests/MFC/CMakeLists.txt.in
+++ b/Tests/MFC/CMakeLists.txt.in
@@ -45,6 +45,11 @@ set(files
set(CMAKE_MFC_FLAG "@CMAKE_MFC_FLAG_VALUE@")
+FIND_PACKAGE(MFC)
+IF (NOT MFC_FOUND)
+ MESSAGE(FATAL_ERROR "MFC Could not be found during the MFC test")
+ENDIF()
+
if("${CMAKE_MFC_FLAG}" STREQUAL "1")
msvc_link_to_static_crt()
else()
diff --git a/Tests/MFC/mfc1/.gitattributes b/Tests/MFC/mfc1/.gitattributes
deleted file mode 100644
index 59be5dcfb..000000000
--- a/Tests/MFC/mfc1/.gitattributes
+++ /dev/null
@@ -1,6 +0,0 @@
-.gitattributes export-ignore
-
-*.sln -crlf
-*.vcproj -crlf
-
-* -whitespace
diff --git a/Tests/Module/CheckIPOSupported-C/CMakeLists.txt b/Tests/Module/CheckIPOSupported-C/CMakeLists.txt
index 607dcd33a..4a41a988d 100644
--- a/Tests/Module/CheckIPOSupported-C/CMakeLists.txt
+++ b/Tests/Module/CheckIPOSupported-C/CMakeLists.txt
@@ -4,11 +4,12 @@ project(CheckIPOSupported-C LANGUAGES C)
cmake_policy(SET CMP0069 NEW)
include(CheckIPOSupported)
-check_ipo_supported(RESULT ipo_supported)
+check_ipo_supported(RESULT ipo_supported OUTPUT ipo_output)
if(ipo_supported)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
elseif(CMake_TEST_IPO_WORKS_C)
- message(FATAL_ERROR "IPO expected to work")
+ string(REPLACE "\n" "\n " ipo_output "${ipo_output}")
+ message(FATAL_ERROR "IPO expected to work, but the check failed:\n ${ipo_output}")
endif()
add_library(foo foo.c)
diff --git a/Tests/Module/CheckIPOSupported-CXX/CMakeLists.txt b/Tests/Module/CheckIPOSupported-CXX/CMakeLists.txt
index 2dede930b..1bb2b8496 100644
--- a/Tests/Module/CheckIPOSupported-CXX/CMakeLists.txt
+++ b/Tests/Module/CheckIPOSupported-CXX/CMakeLists.txt
@@ -4,11 +4,12 @@ project(CheckIPOSupported-CXX LANGUAGES CXX)
cmake_policy(SET CMP0069 NEW)
include(CheckIPOSupported)
-check_ipo_supported(RESULT ipo_supported)
+check_ipo_supported(RESULT ipo_supported OUTPUT ipo_output)
if(ipo_supported)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
elseif(CMake_TEST_IPO_WORKS_CXX)
- message(FATAL_ERROR "IPO expected to work")
+ string(REPLACE "\n" "\n " ipo_output "${ipo_output}")
+ message(FATAL_ERROR "IPO expected to work, but the check failed:\n ${ipo_output}")
endif()
add_library(foo foo.cpp)
diff --git a/Tests/Module/CheckIPOSupported-Fortran/CMakeLists.txt b/Tests/Module/CheckIPOSupported-Fortran/CMakeLists.txt
index dee5c25bd..3872b567b 100644
--- a/Tests/Module/CheckIPOSupported-Fortran/CMakeLists.txt
+++ b/Tests/Module/CheckIPOSupported-Fortran/CMakeLists.txt
@@ -4,11 +4,12 @@ project(CheckIPOSupported-Fortran LANGUAGES Fortran)
cmake_policy(SET CMP0069 NEW)
include(CheckIPOSupported)
-check_ipo_supported(RESULT ipo_supported)
+check_ipo_supported(RESULT ipo_supported OUTPUT ipo_output)
if(ipo_supported)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
elseif(CMake_TEST_IPO_WORKS_Fortran)
- message(FATAL_ERROR "IPO expected to work")
+ string(REPLACE "\n" "\n " ipo_output "${ipo_output}")
+ message(FATAL_ERROR "IPO expected to work, but the check failed:\n ${ipo_output}")
endif()
add_library(foo foo.f)
diff --git a/Tests/Module/ExternalData/MD5/.gitattributes b/Tests/Module/ExternalData/MD5/.gitattributes
deleted file mode 100644
index 3e51d39db..000000000
--- a/Tests/Module/ExternalData/MD5/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -crlf
diff --git a/Tests/Module/ExternalData/SHA1/.gitattributes b/Tests/Module/ExternalData/SHA1/.gitattributes
deleted file mode 100644
index 3e51d39db..000000000
--- a/Tests/Module/ExternalData/SHA1/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -crlf
diff --git a/Tests/Module/ExternalData/SHA224/.gitattributes b/Tests/Module/ExternalData/SHA224/.gitattributes
deleted file mode 100644
index 3e51d39db..000000000
--- a/Tests/Module/ExternalData/SHA224/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -crlf
diff --git a/Tests/Module/ExternalData/SHA256/.gitattributes b/Tests/Module/ExternalData/SHA256/.gitattributes
deleted file mode 100644
index 3e51d39db..000000000
--- a/Tests/Module/ExternalData/SHA256/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -crlf
diff --git a/Tests/Module/ExternalData/SHA3_256/.gitattributes b/Tests/Module/ExternalData/SHA3_256/.gitattributes
deleted file mode 100644
index 3e51d39db..000000000
--- a/Tests/Module/ExternalData/SHA3_256/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -crlf
diff --git a/Tests/MumpsCoverage/.gitattributes b/Tests/MumpsCoverage/.gitattributes
deleted file mode 100644
index b6806125d..000000000
--- a/Tests/MumpsCoverage/.gitattributes
+++ /dev/null
@@ -1,2 +0,0 @@
-*.cmcov -crlf -whitespace
-*.mcov -crlf -whitespace
diff --git a/Tests/MumpsCoverage/ZZCOVTST.cmcov b/Tests/MumpsCoverage/ZZCOVTST.cmcov
index 7a5df6105..41c0ff398 100644
--- a/Tests/MumpsCoverage/ZZCOVTST.cmcov
+++ b/Tests/MumpsCoverage/ZZCOVTST.cmcov
@@ -42,4 +42,4 @@ ZZCOVTST,1,1,"ZZCOVTST;OSEHRA/JPS -- Test routine for Coverage Parsing;4/28/2014
,41,1," . S ZZBLAH=""blah"""
,42,1," W ""Ending T6"",!"
,43,0," ;"
-Totals for ZZCOVTST,,25, \ No newline at end of file
+Totals for ZZCOVTST,,25,
diff --git a/Tests/Plugin/CMakeLists.txt b/Tests/Plugin/CMakeLists.txt
index 9e2b4abd9..227d990af 100644
--- a/Tests/Plugin/CMakeLists.txt
+++ b/Tests/Plugin/CMakeLists.txt
@@ -28,13 +28,6 @@ include_directories(
${Plugin_SOURCE_DIR}/include
)
-# Those versions of the HP compiler that need a flag to get proper C++98
-# template support also need a flag to use the newer C++ library.
-if (CMAKE_CXX_COMPILER_ID STREQUAL HP AND
- CMAKE_CXX98_STANDARD_COMPILE_OPTION STREQUAL "+hpxstd98")
- string(APPEND CMAKE_CXX_FLAGS " -AA")
-endif ()
-
# Clang/C2 in C++98 mode cannot properly handle some of MSVC headers
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND
CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
diff --git a/Tests/PositionIndependentTargets/.gitattributes b/Tests/PositionIndependentTargets/.gitattributes
deleted file mode 100644
index ed36631f4..000000000
--- a/Tests/PositionIndependentTargets/.gitattributes
+++ /dev/null
@@ -1,2 +0,0 @@
-# Do not format a source where we want a long line preserved.
-pic_test.h -format.clang-format
diff --git a/Tests/Qt4Targets/CMakeLists.txt b/Tests/Qt4Targets/CMakeLists.txt
index ae0a02bb6..2ca11e40b 100644
--- a/Tests/Qt4Targets/CMakeLists.txt
+++ b/Tests/Qt4Targets/CMakeLists.txt
@@ -20,6 +20,16 @@ if (WIN32)
endif()
endif()
+# Qt4 moc does not support utf8 paths in _parameter files generated by
+# qt4_wrap_cpp and qt4_generate_moc
+# https://bugreports.qt.io/browse/QTBUG-35480
+# Do a simple check if there is are non ASCII character in the build path
+string(REGEX MATCH "[^ -~]+" NON_ASCII_BDIR ${CMAKE_CURRENT_BINARY_DIR})
+if(NON_ASCII_BDIR)
+ message(WARNING "Build path contains non ASCII characters. Skipping Qt4 test.")
+ return()
+endif()
+
qt4_generate_moc(main_gen_test.cpp
"${CMAKE_CURRENT_BINARY_DIR}/main_gen_test.moc"
TARGET Qt4GenerateMacroTest
diff --git a/Tests/QtAutoUicInterface/CMakeLists.txt b/Tests/QtAutoUicInterface/CMakeLists.txt
index 3ea12943a..a5c2d99b2 100644
--- a/Tests/QtAutoUicInterface/CMakeLists.txt
+++ b/Tests/QtAutoUicInterface/CMakeLists.txt
@@ -53,8 +53,9 @@ set_property(TARGET KI18n APPEND PROPERTY
# END upstream
-if(${CMAKE_GENERATOR} MATCHES "Visual Studio")
-set(INC_DIR "include_${CMAKE_BUILD_TYPE}" )
+get_property(_GENERATOR_IS_MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
+if(_GENERATOR_IS_MULTI_CONFIG)
+set(INC_DIR "include_$<CONFIG>" )
else()
set(INC_DIR "include" )
endif()
diff --git a/Tests/QtAutogen/CMakeLists.txt b/Tests/QtAutogen/CMakeLists.txt
index 073c5fdef..32c2950cb 100644
--- a/Tests/QtAutogen/CMakeLists.txt
+++ b/Tests/QtAutogen/CMakeLists.txt
@@ -1,14 +1,7 @@
-cmake_minimum_required(VERSION 3.7)
-
+cmake_minimum_required(VERSION 3.9)
+cmake_policy(SET CMP0071 NEW)
project(QtAutogen)
-# Tell find_package(Qt5) where to find Qt.
-if(QT_QMAKE_EXECUTABLE)
- get_filename_component(Qt_BIN_DIR "${QT_QMAKE_EXECUTABLE}" PATH)
- get_filename_component(Qt_PREFIX_DIR "${Qt_BIN_DIR}" PATH)
- set(CMAKE_PREFIX_PATH ${Qt_PREFIX_DIR})
-endif()
-
if (QT_TEST_VERSION STREQUAL 4)
find_package(Qt4 REQUIRED)
@@ -22,6 +15,9 @@ if (QT_TEST_VERSION STREQUAL 4)
macro(qtx_wrap_cpp)
qt4_wrap_cpp(${ARGN})
endmacro()
+ macro(qtx_generate_moc)
+ qt4_generate_moc(${ARGN})
+ endmacro()
else()
if (NOT QT_TEST_VERSION STREQUAL 5)
@@ -41,11 +37,48 @@ else()
macro(qtx_wrap_cpp)
qt5_wrap_cpp(${ARGN})
endmacro()
+ macro(qtx_generate_moc)
+ qt5_generate_moc(${ARGN})
+ endmacro()
endif()
get_property(QT_COMPILE_FEATURES TARGET ${QT_QTCORE_TARGET} PROPERTY INTERFACE_COMPILE_FEATURES)
+# Qt4 moc does not support utf8 paths in _parameter files generated by
+# qtx_wrap_cpp
+# https://bugreports.qt.io/browse/QTBUG-35480
+# Do a simple check if there is are non ASCII character in the build path
+string(REGEX MATCH "[^ -~]+" NON_ASCII_BDIR ${CMAKE_CURRENT_BINARY_DIR})
+if((NOT NON_ASCII_BDIR) OR (NOT QT_TEST_VERSION STREQUAL 4))
+ set(ALLOW_WRAP_CPP TRUE)
+endif()
+# On windows qtx_wrap_cpp also fails in Qt5 when used on a path that
+# contains non ASCII characters
+if(NON_ASCII_BDIR AND WIN32)
+ set(ALLOW_WRAP_CPP FALSE)
+endif()
+
+# -- Test
+# MOC only
+add_executable(mocOnly mocOnlySource/main.cpp mocOnlySource/StyleA.cpp mocOnlySource/StyleB.cpp)
+set_property(TARGET mocOnly PROPERTY AUTOMOC ON)
+target_link_libraries(mocOnly ${QT_LIBRARIES})
+
+add_executable(mocOnlyOpts mocOnlySource/main.cpp mocOnlySource/StyleA.cpp mocOnlySource/StyleB.cpp)
+set_property(TARGET mocOnlyOpts PROPERTY AUTOMOC ON)
+set_property(TARGET mocOnlyOpts PROPERTY AUTOMOC_MOC_OPTIONS "-nw")
+target_link_libraries(mocOnlyOpts ${QT_LIBRARIES})
+
+# -- Test
+# UIC only
+if(ALLOW_WRAP_CPP)
+ qtx_wrap_cpp(uicOnlyMoc uicOnlySource/uiconly.h)
+ add_executable(uicOnly uicOnlySource/uiconly.cpp ${uicOnlyMoc})
+ set_property(TARGET uicOnly PROPERTY AUTOUIC ON)
+ target_link_libraries(uicOnly ${QT_LIBRARIES})
+endif()
+
# -- Test
# RCC only
add_executable(rccOnly rccOnly.cpp rccOnlyRes.qrc)
@@ -59,13 +92,6 @@ set_property(TARGET rccEmpty PROPERTY AUTORCC ON)
target_link_libraries(rccEmpty ${QT_QTCORE_TARGET})
# -- Test
-# UIC only
-qtx_wrap_cpp(uicOnlyMoc uicOnlySource/uiconly.h)
-add_executable(uicOnly uicOnlySource/uiconly.cpp ${uicOnlyMoc})
-set_property(TARGET uicOnly PROPERTY AUTOUIC ON)
-target_link_libraries(uicOnly ${QT_LIBRARIES})
-
-# -- Test
# Add not_generated_file.qrc to the source list to get the file-level
# dependency, but don't generate a c++ file from it. Disable the AUTORCC
# feature for this target. This tests that qrc files in the sources don't
@@ -80,154 +106,41 @@ set_target_properties(no_link_language PROPERTIES AUTOMOC TRUE)
target_compile_features(no_link_language PRIVATE ${QT_COMPILE_FEATURES})
target_compile_features(empty PRIVATE ${QT_COMPILE_FEATURES})
-# -- Test
-# When a file listed in a .qrc file changes the target must be rebuilt
-set(timeformat "%Y%j%H%M%S")
-set(RCC_DEPENDS_SRC "${CMAKE_CURRENT_SOURCE_DIR}/rccDepends")
-set(RCC_DEPENDS_BIN "${CMAKE_CURRENT_BINARY_DIR}/rccDepends")
-configure_file(${RCC_DEPENDS_SRC}/res1a.qrc.in ${RCC_DEPENDS_BIN}/res1.qrc COPYONLY)
-configure_file(${RCC_DEPENDS_SRC}/res2a.qrc.in ${RCC_DEPENDS_BIN}/res2.qrc.in COPYONLY)
-try_compile(RCC_DEPENDS
- "${RCC_DEPENDS_BIN}"
- "${RCC_DEPENDS_SRC}"
- rccDepends
- CMAKE_FLAGS "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}"
- "-DQT_TEST_VERSION=${QT_TEST_VERSION}"
- "-DCMAKE_PREFIX_PATH=${Qt_PREFIX_DIR}"
- OUTPUT_VARIABLE output
-)
-if (NOT RCC_DEPENDS)
- message(SEND_ERROR "Initial build of rccDepends failed. Output: ${output}")
-endif()
-# Get name and timestamp of the output binary
-file(STRINGS "${RCC_DEPENDS_BIN}/target.txt" targetList)
-list(GET targetList 0 rccDependsBin)
-file(TIMESTAMP "${rccDependsBin}" timeBegin "${timeformat}")
-# Sleep, touch regular qrc input file, rebuild and compare timestamp
-execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) # Ensure that the timestamp will change.
-execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${RCC_DEPENDS_BIN}/res1/input.txt")
-execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${RCC_DEPENDS_BIN}" RESULT_VARIABLE result)
-if (result)
- message(SEND_ERROR "Second build of rccDepends failed.")
-endif()
-file(TIMESTAMP "${rccDependsBin}" timeStep1 "${timeformat}")
-if (NOT timeStep1 GREATER timeBegin)
- message(SEND_ERROR "File (${rccDependsBin}) should have changed in the first step!")
-endif()
-# Sleep, update regular qrc file, rebuild and compare timestamp
-execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) # Ensure that the timestamp will change.
-configure_file(${RCC_DEPENDS_SRC}/res1b.qrc.in ${RCC_DEPENDS_BIN}/res1.qrc COPYONLY)
-execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${RCC_DEPENDS_BIN}" RESULT_VARIABLE result)
-if (result)
- message(SEND_ERROR "Third build of rccDepends failed.")
-endif()
-file(TIMESTAMP "${rccDependsBin}" timeStep2 "${timeformat}")
-if (NOT timeStep2 GREATER timeStep1)
- message(SEND_ERROR "File (${rccDependsBin}) should have changed in the second step!")
-endif()
-# Sleep, touch regular qrc newly added input file, rebuild and compare timestamp
-execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) # Ensure that the timestamp will change.
-execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${RCC_DEPENDS_BIN}/res1/inputAdded.txt")
-execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${RCC_DEPENDS_BIN}" RESULT_VARIABLE result)
-if (result)
- message(SEND_ERROR "Fourth build of rccDepends failed.")
-endif()
-file(TIMESTAMP "${rccDependsBin}" timeStep3 "${timeformat}")
-if (NOT timeStep3 GREATER timeStep2)
- message(SEND_ERROR "File (${rccDependsBin}) should have changed in the third step!")
-endif()
-# Sleep, touch generated qrc input file, rebuild and compare timestamp
-execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) # Ensure that the timestamp will change.
-execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${RCC_DEPENDS_BIN}/res2/input.txt")
-execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${RCC_DEPENDS_BIN}" RESULT_VARIABLE result)
-if (result)
- message(SEND_ERROR "Fifth build of rccDepends failed.")
-endif()
-file(TIMESTAMP "${rccDependsBin}" timeStep4 "${timeformat}")
-if (NOT timeStep4 GREATER timeStep3)
- message(SEND_ERROR "File (${rccDependsBin}) should have changed in the fourth step!")
-endif()
-# Sleep, update generated qrc file, rebuild and compare timestamp
-execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) # Ensure that the timestamp will change.
-configure_file(${RCC_DEPENDS_SRC}/res2b.qrc.in ${RCC_DEPENDS_BIN}/res2.qrc.in COPYONLY)
-execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${RCC_DEPENDS_BIN}" RESULT_VARIABLE result)
-if (result)
- message(SEND_ERROR "Sixth build of rccDepends failed.")
-endif()
-file(TIMESTAMP "${rccDependsBin}" timeStep5 "${timeformat}")
-if (NOT timeStep5 GREATER timeStep4)
- message(SEND_ERROR "File (${rccDependsBin}) should have changed in the fitfh step!")
-endif()
-# Sleep, touch generated qrc newly added input file, rebuild and compare timestamp
-execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1) # Ensure that the timestamp will change.
-execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${RCC_DEPENDS_BIN}/res2/inputAdded.txt")
-execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${RCC_DEPENDS_BIN}" RESULT_VARIABLE result)
-if (result)
- message(SEND_ERROR "Seventh build of rccDepends failed.")
-endif()
-file(TIMESTAMP "${rccDependsBin}" timeStep6 "${timeformat}")
-if (NOT timeStep6 GREATER timeStep5)
- message(SEND_ERROR "File (${rccDependsBin}) should have changed in the sixth step!")
-endif()
-
-
-# -- Test
-# Ensure a repeated build succeeds when a header containing a QObject changes
-set(timeformat "%Y%j%H%M%S")
-configure_file(mocRerun/test1a.h.in mocRerun/test1.h COPYONLY)
-try_compile(MOC_RERUN
- "${CMAKE_CURRENT_BINARY_DIR}/mocRerun"
- "${CMAKE_CURRENT_SOURCE_DIR}/mocRerun"
- mocRerun
- CMAKE_FLAGS "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}"
- "-DQT_TEST_VERSION=${QT_TEST_VERSION}"
- "-DCMAKE_PREFIX_PATH=${Qt_PREFIX_DIR}"
- OUTPUT_VARIABLE output
-)
-if (NOT MOC_RERUN)
- message(SEND_ERROR "Initial build of mocRerun failed. Output: ${output}")
-endif()
-# Get name and timestamp of the output binary
-file(STRINGS "${CMAKE_CURRENT_BINARY_DIR}/mocRerun/target1.txt" target1List)
-list(GET target1List 0 binFile)
-file(TIMESTAMP "${binFile}" timeBegin "${timeformat}")
-# Change file content and rebuild
-execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
-configure_file(mocRerun/test1b.h.in mocRerun/test1.h COPYONLY)
-execute_process(COMMAND "${CMAKE_COMMAND}" --build .
- WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/mocRerun"
- RESULT_VARIABLE mocRerun_result
- )
-if (mocRerun_result)
- message(SEND_ERROR "Second build of mocRerun failed.")
-endif()
-# Compare timestamps
-file(TIMESTAMP "${binFile}" timeStep1 "${timeformat}")
-if (NOT timeStep1 GREATER timeBegin)
- message(SEND_ERROR "File (${binFile}) should have changed in the first step!")
-endif()
# -- Test
# Test for SKIP_AUTOMOC and SKIP_AUTOGEN on an AUTOMOC enabled target
-qtx_wrap_cpp(skipMocWrapMoc
- skipSource/qItemA.hpp
- skipSource/qItemB.hpp)
-set(skipMocSources
- skipMoc.cpp
- skipSource/qItemA.cpp
- skipSource/qItemB.cpp
- skipSource/qItemC.cpp)
-set_property(SOURCE skipSource/qItemA.cpp PROPERTY SKIP_AUTOMOC ON)
-set_property(SOURCE skipSource/qItemB.cpp PROPERTY SKIP_AUTOGEN ON)
-# AUTOMOC enabled only
-add_executable(skipMocA ${skipMocSources} ${skipMocWrapMoc})
-set_property(TARGET skipMocA PROPERTY AUTOMOC ON)
-target_link_libraries(skipMocA ${QT_LIBRARIES})
-# AUTOMOC and AUTOUIC enabled
-add_executable(skipMocB ${skipMocSources} ${skipMocWrapMoc})
-set_property(TARGET skipMocB PROPERTY AUTOMOC ON)
-set_property(TARGET skipMocB PROPERTY AUTOUIC ON)
-target_link_libraries(skipMocB ${QT_LIBRARIES})
+if(ALLOW_WRAP_CPP)
+ # Generate header mocs manually
+ qtx_wrap_cpp(skipMocWrapMoc
+ skipSource/qItemA.hpp
+ skipSource/qItemB.hpp
+ skipSource/qItemC.hpp
+ skipSource/qItemD.hpp
+ )
+ set(skipMocSources
+ skipMoc.cpp
+ skipSource/qItemA.cpp
+ skipSource/qItemB.cpp
+ skipSource/qItemC.cpp
+ skipSource/qItemD.cpp
+ )
+ # When cpp files are skipped, the hpp won't be processed either,
+ # unless they are mentioned in the sources - which they aren't.
+ set_property(SOURCE skipSource/qItemA.cpp PROPERTY SKIP_AUTOMOC ON)
+ set_property(SOURCE skipSource/qItemB.cpp PROPERTY SKIP_AUTOGEN ON)
+ # When hpp files are skipped, the cpp still get processed.
+ set_property(SOURCE skipSource/qItemC.hpp PROPERTY SKIP_AUTOMOC ON)
+ set_property(SOURCE skipSource/qItemD.hpp PROPERTY SKIP_AUTOGEN ON)
+ # AUTOMOC enabled only
+ add_executable(skipMocA ${skipMocSources} ${skipMocWrapMoc})
+ set_property(TARGET skipMocA PROPERTY AUTOMOC ON)
+ target_link_libraries(skipMocA ${QT_LIBRARIES})
+ # AUTOMOC and AUTOUIC enabled
+ add_executable(skipMocB ${skipMocSources} ${skipMocWrapMoc})
+ set_property(TARGET skipMocB PROPERTY AUTOMOC ON)
+ set_property(TARGET skipMocB PROPERTY AUTOUIC ON)
+ target_link_libraries(skipMocB ${QT_LIBRARIES})
+endif()
# -- Test
# Test for SKIP_AUTOUIC and SKIP_AUTOGEN on an AUTOUIC enabled target
@@ -271,8 +184,10 @@ set_property(TARGET skipRccB PROPERTY AUTOMOC ON)
target_link_libraries(skipRccB ${QT_LIBRARIES})
# -- Test
-# Source files with the same basename in different subdirectories
-add_subdirectory(sameName)
+# MOC AUTOMOC_MACRO_NAMES
+if (NOT QT_TEST_VERSION STREQUAL 4)
+ add_subdirectory(mocMacroName)
+endif()
# -- Test
# Tests AUTOMOC with generated sources
@@ -280,85 +195,32 @@ add_subdirectory(mocDepends)
# -- Test
# Tests various include moc patterns
-add_subdirectory(mocIncludeStrict)
+if(ALLOW_WRAP_CPP)
+ add_subdirectory(mocIncludeStrict)
+ add_subdirectory(mocIncludeRelaxed)
+endif()
# -- Test
-# Tests various include moc patterns
-add_subdirectory(mocIncludeRelaxed)
+# Tests policy 0071
+if(ALLOW_WRAP_CPP)
+ add_subdirectory(mocCMP0071)
+endif()
# -- Test
-# Tests Q_PLUGIN_METADATA json file change detection
-if (NOT QT_TEST_VERSION STREQUAL 4)
- try_compile(MOC_PLUGIN
- "${CMAKE_CURRENT_BINARY_DIR}/mocPlugin"
- "${CMAKE_CURRENT_SOURCE_DIR}/mocPlugin"
- mocPlugin
- CMAKE_FLAGS "-DQT_TEST_VERSION=${QT_TEST_VERSION}"
- "-DCMAKE_PREFIX_PATH=${Qt_PREFIX_DIR}"
- OUTPUT_VARIABLE output
- )
- if (NOT MOC_PLUGIN)
- message(SEND_ERROR "Initial build of mocPlugin failed. Output: ${output}")
- endif()
-
- set(timeformat "%Y%j%H%M%S")
- set(mocPlugSrcDir "${CMAKE_CURRENT_SOURCE_DIR}/mocPlugin")
- set(mocPlugBinDir "${CMAKE_CURRENT_BINARY_DIR}/mocPlugin")
- find_library(plAFile "PlugA" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH)
- find_library(plBFile "PlugB" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH)
- find_library(plCFile "PlugC" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH)
- find_library(plDFile "PlugD" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH)
-
- file(TIMESTAMP "${plAFile}" plABefore "${timeformat}")
- file(TIMESTAMP "${plBFile}" plBBefore "${timeformat}")
- file(TIMESTAMP "${plCFile}" plCBefore "${timeformat}")
- file(TIMESTAMP "${plDFile}" plDBefore "${timeformat}")
-
- # Ensure that the timestamp will change and change the json files
- execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
- configure_file("${mocPlugSrcDir}/jsonIn/StyleD.json" "${mocPlugBinDir}/jsonFiles/StyleC.json")
- configure_file("${mocPlugSrcDir}/jsonIn/StyleC.json" "${mocPlugBinDir}/jsonFiles/sub/StyleD.json")
- execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocPlugBinDir}")
-
- file(TIMESTAMP "${plAFile}" plAAfter "${timeformat}")
- file(TIMESTAMP "${plBFile}" plBAfter "${timeformat}")
- file(TIMESTAMP "${plCFile}" plCAfter "${timeformat}")
- file(TIMESTAMP "${plDFile}" plDAfter "${timeformat}")
-
- if (plAAfter GREATER plABefore)
- message(SEND_ERROR "file (${plAFile}) should not have changed!")
- endif()
- if (plBAfter GREATER plBBefore)
- message(SEND_ERROR "file (${plBFile}) should not have changed!")
- endif()
- if (NOT plCAfter GREATER plCBefore)
- message(SEND_ERROR "file (${plCFile}) should have changed!")
- endif()
- if (NOT plDAfter GREATER plDBefore)
- message(SEND_ERROR "file (${plDFile}) should have changed!")
- endif()
+# Tests various .ui include directories
+add_subdirectory(uicInclude)
- # Test custom macro
- file(TIMESTAMP "${plCFile}" plCBefore "${timeformat}")
- file(TIMESTAMP "${plDFile}" plDBefore "${timeformat}")
- execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
- configure_file("${mocPlugSrcDir}/jsonIn/StyleD.json" "${mocPlugBinDir}/jsonFiles/StyleC_Custom.json")
- configure_file("${mocPlugSrcDir}/jsonIn/StyleC.json" "${mocPlugBinDir}/jsonFiles/sub/StyleD_Custom.json")
- execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocPlugBinDir}")
- file(TIMESTAMP "${plCFile}" plCAfter "${timeformat}")
- file(TIMESTAMP "${plDFile}" plDAfter "${timeformat}")
- if (NOT plCAfter GREATER plCBefore)
- message(SEND_ERROR "file (${plCFile}) should have changed!")
- endif()
- if (NOT plDAfter GREATER plDBefore)
- message(SEND_ERROR "file (${plDFile}) should have changed!")
- endif()
+# -- Test
+# OBJECT libraries
+add_subdirectory(objectLibrary)
-endif()
+# -- Test
+# Source files with the same basename in different subdirectories
+add_subdirectory(sameName)
# -- Test
-# Tests various .ui include directories
-add_subdirectory(uicInclude)
+# Tests static library cycles
+add_subdirectory(staticLibraryCycle)
# -- Test
# Complex test case
diff --git a/Tests/QtAutogen/complex/CMakeLists.txt b/Tests/QtAutogen/complex/CMakeLists.txt
index d48f6cc54..2043ccf58 100644
--- a/Tests/QtAutogen/complex/CMakeLists.txt
+++ b/Tests/QtAutogen/complex/CMakeLists.txt
@@ -1,4 +1,4 @@
-cmake_minimum_required(VERSION 3.7)
+cmake_minimum_required(VERSION 3.9)
# -- Test: AUTOMOC AUTORCC AUTOUIC
add_definitions(-DFOO -DSomeDefine="Barx")
diff --git a/Tests/QtAutogen/mocCMP0071/CMakeLists.txt b/Tests/QtAutogen/mocCMP0071/CMakeLists.txt
new file mode 100644
index 000000000..003fa088f
--- /dev/null
+++ b/Tests/QtAutogen/mocCMP0071/CMakeLists.txt
@@ -0,0 +1,4 @@
+cmake_minimum_required(VERSION 3.9)
+project(mocCMP0071 CXX)
+add_subdirectory(OLD)
+add_subdirectory(NEW)
diff --git a/Tests/QtAutogen/mocCMP0071/NEW/CMakeLists.txt b/Tests/QtAutogen/mocCMP0071/NEW/CMakeLists.txt
new file mode 100644
index 000000000..0237afc39
--- /dev/null
+++ b/Tests/QtAutogen/mocCMP0071/NEW/CMakeLists.txt
@@ -0,0 +1,16 @@
+cmake_minimum_required(VERSION 3.9)
+cmake_policy(SET CMP0071 NEW)
+
+# *Generate* files
+set(CSD ${CMAKE_CURRENT_SOURCE_DIR})
+set(CBD ${CMAKE_CURRENT_BINARY_DIR})
+add_custom_command(
+ OUTPUT ${CBD}/Obj_p.h ${CBD}/Obj.hpp ${CBD}/Obj.cpp ${CBD}/main.cpp
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/../Obj_p.h ${CBD}/Obj_p.h
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/../Obj.hpp ${CBD}/Obj.hpp
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/../Obj.cpp ${CBD}/Obj.cpp
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/../main.cpp ${CBD}/main.cpp)
+
+add_executable(mocCMP0071New ${CBD}/Obj.cpp ${CBD}/main.cpp)
+target_link_libraries(mocCMP0071New ${QT_LIBRARIES})
+set_target_properties(mocCMP0071New PROPERTIES AUTOMOC ON)
diff --git a/Tests/QtAutogen/mocCMP0071/OLD/CMakeLists.txt b/Tests/QtAutogen/mocCMP0071/OLD/CMakeLists.txt
new file mode 100644
index 000000000..569943336
--- /dev/null
+++ b/Tests/QtAutogen/mocCMP0071/OLD/CMakeLists.txt
@@ -0,0 +1,18 @@
+cmake_minimum_required(VERSION 3.9)
+cmake_policy(SET CMP0071 OLD)
+
+# *Generate* files
+set(CSD ${CMAKE_CURRENT_SOURCE_DIR})
+set(CBD ${CMAKE_CURRENT_BINARY_DIR})
+add_custom_command(
+ OUTPUT ${CBD}/Obj_p.h ${CBD}/Obj.hpp ${CBD}/Obj.cpp ${CBD}/main.cpp
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/../Obj_p.h ${CBD}/Obj_p.h
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/../Obj.hpp ${CBD}/Obj.hpp
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/../Obj.cpp ${CBD}/Obj.cpp
+ COMMAND ${CMAKE_COMMAND} -E copy ${CSD}/../main.cpp ${CBD}/main.cpp)
+
+# Generate moc files externally
+qtx_wrap_cpp(mocCMP0071OldMoc ${CBD}/Obj.hpp ${CBD}/Obj_p.h)
+add_executable(mocCMP0071Old ${CBD}/Obj.cpp ${CBD}/main.cpp ${mocCMP0071OldMoc})
+target_link_libraries(mocCMP0071Old ${QT_LIBRARIES})
+set_target_properties(mocCMP0071Old PROPERTIES AUTOMOC ON)
diff --git a/Tests/QtAutogen/mocCMP0071/Obj.cpp b/Tests/QtAutogen/mocCMP0071/Obj.cpp
new file mode 100644
index 000000000..1ae50edc9
--- /dev/null
+++ b/Tests/QtAutogen/mocCMP0071/Obj.cpp
@@ -0,0 +1,20 @@
+#include "Obj.hpp"
+#include "Obj_p.h"
+
+ObjPrivate::ObjPrivate()
+{
+}
+
+ObjPrivate::~ObjPrivate()
+{
+}
+
+Obj::Obj()
+ : d(new ObjPrivate)
+{
+}
+
+Obj::~Obj()
+{
+ delete d;
+}
diff --git a/Tests/QtAutogen/mocCMP0071/Obj.hpp b/Tests/QtAutogen/mocCMP0071/Obj.hpp
new file mode 100644
index 000000000..f064e4793
--- /dev/null
+++ b/Tests/QtAutogen/mocCMP0071/Obj.hpp
@@ -0,0 +1,19 @@
+#ifndef OBJ_HPP
+#define OBJ_HPP
+
+#include <QObject>
+
+// Object source comes without any _moc/.moc includes
+class ObjPrivate;
+class Obj : public QObject
+{
+ Q_OBJECT
+public:
+ Obj();
+ ~Obj();
+
+private:
+ ObjPrivate* const d;
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocCMP0071/Obj_p.h b/Tests/QtAutogen/mocCMP0071/Obj_p.h
new file mode 100644
index 000000000..cb1e5df71
--- /dev/null
+++ b/Tests/QtAutogen/mocCMP0071/Obj_p.h
@@ -0,0 +1,14 @@
+#ifndef OBJ_P_HPP
+#define OBJ_P_HPP
+
+#include <QObject>
+
+class ObjPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ ObjPrivate();
+ ~ObjPrivate();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocCMP0071/main.cpp b/Tests/QtAutogen/mocCMP0071/main.cpp
new file mode 100644
index 000000000..3887840ba
--- /dev/null
+++ b/Tests/QtAutogen/mocCMP0071/main.cpp
@@ -0,0 +1,7 @@
+#include "Obj.hpp"
+
+int main(int argv, char** args)
+{
+ Obj obj;
+ return 0;
+}
diff --git a/Tests/QtAutogen/mocDepends/CMakeLists.txt b/Tests/QtAutogen/mocDepends/CMakeLists.txt
index 6241ef93d..8217b8dbf 100644
--- a/Tests/QtAutogen/mocDepends/CMakeLists.txt
+++ b/Tests/QtAutogen/mocDepends/CMakeLists.txt
@@ -1,4 +1,5 @@
cmake_minimum_required(VERSION 3.9)
+cmake_policy(SET CMP0071 NEW)
project(mocDepends CXX)
if (QT_TEST_VERSION STREQUAL 4)
@@ -43,7 +44,6 @@ add_custom_command(
add_executable(mocDepGenFile testGenFile.cpp ${CBD}/GenFile.hpp)
target_link_libraries(mocDepGenFile ${QT_CORE_TARGET})
set_target_properties(mocDepGenFile PROPERTIES AUTOMOC TRUE)
-set_property(TARGET mocDepGenFile PROPERTY __UNDOCUMENTED_AUTOGEN_GENERATED_FILES 1)
# -- Test dependency on header generating custom target
diff --git a/Tests/QtAutogen/mocInclude/EObjA.cpp b/Tests/QtAutogen/mocInclude/EObjA.cpp
new file mode 100644
index 000000000..ca713b261
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/EObjA.cpp
@@ -0,0 +1,43 @@
+#include "EObjA.hpp"
+#include "EObjAExtra.hpp"
+#include "EObjA_p.hpp"
+
+class EObjALocal : public QObject
+{
+ Q_OBJECT
+public:
+ EObjALocal();
+ ~EObjALocal();
+};
+
+EObjALocal::EObjALocal()
+{
+}
+
+EObjALocal::~EObjALocal()
+{
+}
+
+EObjAPrivate::EObjAPrivate()
+{
+ EObjALocal localObj;
+ EObjAExtra extraObj;
+}
+
+EObjAPrivate::~EObjAPrivate()
+{
+}
+
+EObjA::EObjA()
+ : d(new EObjAPrivate)
+{
+}
+
+EObjA::~EObjA()
+{
+}
+
+// For EObjALocal
+#include "EObjA.moc"
+// - Not the own header
+#include "moc_EObjAExtra.cpp"
diff --git a/Tests/QtAutogen/mocInclude/EObjA.hpp b/Tests/QtAutogen/mocInclude/EObjA.hpp
new file mode 100644
index 000000000..0939ab66d
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/EObjA.hpp
@@ -0,0 +1,19 @@
+#ifndef EOBJA_HPP
+#define EOBJA_HPP
+
+#include <QObject>
+
+// Sources includes a moc_ includes of an extra object
+class EObjAPrivate;
+class EObjA : public QObject
+{
+ Q_OBJECT
+public:
+ EObjA();
+ ~EObjA();
+
+private:
+ EObjAPrivate* const d;
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/EObjAExtra.cpp b/Tests/QtAutogen/mocInclude/EObjAExtra.cpp
new file mode 100644
index 000000000..369ca8f77
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/EObjAExtra.cpp
@@ -0,0 +1,20 @@
+#include "EObjAExtra.hpp"
+#include "EObjAExtra_p.hpp"
+
+EObjAExtraPrivate::EObjAExtraPrivate()
+{
+}
+
+EObjAExtraPrivate::~EObjAExtraPrivate()
+{
+}
+
+EObjAExtra::EObjAExtra()
+ : d(new EObjAExtraPrivate)
+{
+}
+
+EObjAExtra::~EObjAExtra()
+{
+ delete d;
+}
diff --git a/Tests/QtAutogen/mocInclude/EObjAExtra.hpp b/Tests/QtAutogen/mocInclude/EObjAExtra.hpp
new file mode 100644
index 000000000..b10681d59
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/EObjAExtra.hpp
@@ -0,0 +1,18 @@
+#ifndef EOBJAEXTRA_HPP
+#define EOBJAEXTRA_HPP
+
+#include <QObject>
+
+class EObjAExtraPrivate;
+class EObjAExtra : public QObject
+{
+ Q_OBJECT
+public:
+ EObjAExtra();
+ ~EObjAExtra();
+
+private:
+ EObjAExtraPrivate* const d;
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/EObjAExtra_p.hpp b/Tests/QtAutogen/mocInclude/EObjAExtra_p.hpp
new file mode 100644
index 000000000..dea6cb5ab
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/EObjAExtra_p.hpp
@@ -0,0 +1,12 @@
+#ifndef EOBJAEXTRA_P_HPP
+#define EOBJAEXTRA_P_HPP
+
+class EObjAExtraPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ EObjAExtraPrivate();
+ ~EObjAExtraPrivate();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/EObjA_p.hpp b/Tests/QtAutogen/mocInclude/EObjA_p.hpp
new file mode 100644
index 000000000..1e0d7e11d
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/EObjA_p.hpp
@@ -0,0 +1,12 @@
+#ifndef EOBJA_P_HPP
+#define EOBJA_P_HPP
+
+class EObjAPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ EObjAPrivate();
+ ~EObjAPrivate();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/EObjB.cpp b/Tests/QtAutogen/mocInclude/EObjB.cpp
new file mode 100644
index 000000000..d19fbfa6c
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/EObjB.cpp
@@ -0,0 +1,44 @@
+#include "EObjB.hpp"
+#include "EObjB_p.hpp"
+#include "subExtra/EObjBExtra.hpp"
+
+class EObjBLocal : public QObject
+{
+ Q_OBJECT
+public:
+ EObjBLocal();
+ ~EObjBLocal();
+};
+
+EObjBLocal::EObjBLocal()
+{
+}
+
+EObjBLocal::~EObjBLocal()
+{
+}
+
+EObjBPrivate::EObjBPrivate()
+{
+ EObjBLocal localObj;
+ EObjBExtra extraObj;
+}
+
+EObjBPrivate::~EObjBPrivate()
+{
+}
+
+EObjB::EObjB()
+ : d(new EObjBPrivate)
+{
+}
+
+EObjB::~EObjB()
+{
+}
+
+// For EObjBLocal
+#include "EObjB.moc"
+// - Not the own header
+// - in a subdirectory
+#include "subExtra/moc_EObjBExtra.cpp"
diff --git a/Tests/QtAutogen/mocInclude/EObjB.hpp b/Tests/QtAutogen/mocInclude/EObjB.hpp
new file mode 100644
index 000000000..6632bdb07
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/EObjB.hpp
@@ -0,0 +1,19 @@
+#ifndef EOBJB_HPP
+#define EOBJB_HPP
+
+#include <QObject>
+
+// Sources includes a moc_ includes of an extra object in a subdirectory
+class EObjBPrivate;
+class EObjB : public QObject
+{
+ Q_OBJECT
+public:
+ EObjB();
+ ~EObjB();
+
+private:
+ EObjBPrivate* const d;
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/EObjB_p.hpp b/Tests/QtAutogen/mocInclude/EObjB_p.hpp
new file mode 100644
index 000000000..2905f2891
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/EObjB_p.hpp
@@ -0,0 +1,12 @@
+#ifndef EOBJB_P_HPP
+#define EOBJB_P_HPP
+
+class EObjBPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ EObjBPrivate();
+ ~EObjBPrivate();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/LObjA.cpp b/Tests/QtAutogen/mocInclude/LObjA.cpp
new file mode 100644
index 000000000..9aae9917f
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/LObjA.cpp
@@ -0,0 +1,39 @@
+#include "LObjA.hpp"
+#include "LObjA_p.h"
+
+class LObjALocal : public QObject
+{
+ Q_OBJECT
+public:
+ LObjALocal();
+ ~LObjALocal();
+};
+
+LObjALocal::LObjALocal()
+{
+}
+
+LObjALocal::~LObjALocal()
+{
+}
+
+LObjAPrivate::LObjAPrivate()
+{
+ LObjALocal localObj;
+}
+
+LObjAPrivate::~LObjAPrivate()
+{
+}
+
+LObjA::LObjA()
+ : d(new LObjAPrivate)
+{
+}
+
+LObjA::~LObjA()
+{
+ delete d;
+}
+
+#include "LObjA.moc"
diff --git a/Tests/QtAutogen/mocInclude/LObjA.hpp b/Tests/QtAutogen/mocInclude/LObjA.hpp
new file mode 100644
index 000000000..aac670c00
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/LObjA.hpp
@@ -0,0 +1,19 @@
+#ifndef LOBJA_HPP
+#define LOBJA_HPP
+
+#include <QObject>
+
+// Object source comes with a .moc include
+class LObjAPrivate;
+class LObjA : public QObject
+{
+ Q_OBJECT
+public:
+ LObjA();
+ ~LObjA();
+
+private:
+ LObjAPrivate* const d;
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/LObjA_p.h b/Tests/QtAutogen/mocInclude/LObjA_p.h
new file mode 100644
index 000000000..ebe839579
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/LObjA_p.h
@@ -0,0 +1,12 @@
+#ifndef LOBJA_P_HPP
+#define LOBJA_P_HPP
+
+class LObjAPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ LObjAPrivate();
+ ~LObjAPrivate();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/LObjB.cpp b/Tests/QtAutogen/mocInclude/LObjB.cpp
new file mode 100644
index 000000000..7485d8fca
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/LObjB.cpp
@@ -0,0 +1,40 @@
+#include "LObjB.hpp"
+#include "LObjB_p.h"
+
+class LObjBLocal : public QObject
+{
+ Q_OBJECT
+public:
+ LObjBLocal();
+ ~LObjBLocal();
+};
+
+LObjBLocal::LObjBLocal()
+{
+}
+
+LObjBLocal::~LObjBLocal()
+{
+}
+
+LObjBPrivate::LObjBPrivate()
+{
+ LObjBLocal localObj;
+}
+
+LObjBPrivate::~LObjBPrivate()
+{
+}
+
+LObjB::LObjB()
+ : d(new LObjBPrivate)
+{
+}
+
+LObjB::~LObjB()
+{
+ delete d;
+}
+
+#include "LObjB.moc"
+#include "moc_LObjB.cpp"
diff --git a/Tests/QtAutogen/mocInclude/LObjB.hpp b/Tests/QtAutogen/mocInclude/LObjB.hpp
new file mode 100644
index 000000000..eb4e58d79
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/LObjB.hpp
@@ -0,0 +1,19 @@
+#ifndef LLObjB_HPP
+#define LLObjB_HPP
+
+#include <QObject>
+
+// Object source comes with a .moc and a _moc include
+class LObjBPrivate;
+class LObjB : public QObject
+{
+ Q_OBJECT
+public:
+ LObjB();
+ ~LObjB();
+
+private:
+ LObjBPrivate* const d;
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/LObjB_p.h b/Tests/QtAutogen/mocInclude/LObjB_p.h
new file mode 100644
index 000000000..b871f2d2a
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/LObjB_p.h
@@ -0,0 +1,12 @@
+#ifndef LOBJB_P_HPP
+#define LOBJB_P_HPP
+
+class LObjBPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ LObjBPrivate();
+ ~LObjBPrivate();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/ObjA.cpp b/Tests/QtAutogen/mocInclude/ObjA.cpp
index 1b0311d30..6f6b90ef1 100644
--- a/Tests/QtAutogen/mocInclude/ObjA.cpp
+++ b/Tests/QtAutogen/mocInclude/ObjA.cpp
@@ -1,24 +1,20 @@
#include "ObjA.hpp"
+#include "ObjA_p.h"
-class SubObjA : public QObject
+ObjAPrivate::ObjAPrivate()
{
- Q_OBJECT
-
-public:
- SubObjA() {}
- ~SubObjA() {}
-
- Q_SLOT
- void aSlot();
-};
+}
-void SubObjA::aSlot()
+ObjAPrivate::~ObjAPrivate()
{
}
-void ObjA::go()
+ObjA::ObjA()
+ : d(new ObjAPrivate)
{
- SubObjA subObj;
}
-#include "ObjA.moc"
+ObjA::~ObjA()
+{
+ delete d;
+}
diff --git a/Tests/QtAutogen/mocInclude/ObjA.hpp b/Tests/QtAutogen/mocInclude/ObjA.hpp
index 281e90d86..f16c924aa 100644
--- a/Tests/QtAutogen/mocInclude/ObjA.hpp
+++ b/Tests/QtAutogen/mocInclude/ObjA.hpp
@@ -3,11 +3,17 @@
#include <QObject>
+// Object source comes without any _moc/.moc includes
+class ObjAPrivate;
class ObjA : public QObject
{
Q_OBJECT
- Q_SLOT
- void go();
+public:
+ ObjA();
+ ~ObjA();
+
+private:
+ ObjAPrivate* const d;
};
#endif
diff --git a/Tests/QtAutogen/mocInclude/ObjA_p.h b/Tests/QtAutogen/mocInclude/ObjA_p.h
new file mode 100644
index 000000000..eb60c9800
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/ObjA_p.h
@@ -0,0 +1,12 @@
+#ifndef OBJA_P_HPP
+#define OBJA_P_HPP
+
+class ObjAPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ ObjAPrivate();
+ ~ObjAPrivate();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/ObjB.cpp b/Tests/QtAutogen/mocInclude/ObjB.cpp
index 5ff315dc7..a6f2509af 100644
--- a/Tests/QtAutogen/mocInclude/ObjB.cpp
+++ b/Tests/QtAutogen/mocInclude/ObjB.cpp
@@ -1,25 +1,22 @@
#include "ObjB.hpp"
+#include "ObjB_p.h"
-class SubObjB : public QObject
+ObjBPrivate::ObjBPrivate()
{
- Q_OBJECT
-
-public:
- SubObjB() {}
- ~SubObjB() {}
+}
- Q_SLOT
- void aSlot();
-};
+ObjBPrivate::~ObjBPrivate()
+{
+}
-void SubObjB::aSlot()
+ObjB::ObjB()
+ : d(new ObjBPrivate)
{
}
-void ObjB::go()
+ObjB::~ObjB()
{
- SubObjB subObj;
+ delete d;
}
-#include "ObjB.moc"
#include "moc_ObjB.cpp"
diff --git a/Tests/QtAutogen/mocInclude/ObjB.hpp b/Tests/QtAutogen/mocInclude/ObjB.hpp
index 94f3d498c..2ac8d1700 100644
--- a/Tests/QtAutogen/mocInclude/ObjB.hpp
+++ b/Tests/QtAutogen/mocInclude/ObjB.hpp
@@ -1,13 +1,19 @@
-#ifndef OBJB_HPP
-#define OBJB_HPP
+#ifndef ObjB_HPP
+#define ObjB_HPP
#include <QObject>
+// Object source comes with a _moc include
+class ObjBPrivate;
class ObjB : public QObject
{
Q_OBJECT
- Q_SLOT
- void go();
+public:
+ ObjB();
+ ~ObjB();
+
+private:
+ ObjBPrivate* const d;
};
#endif
diff --git a/Tests/QtAutogen/mocInclude/ObjB_p.h b/Tests/QtAutogen/mocInclude/ObjB_p.h
new file mode 100644
index 000000000..418da6578
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/ObjB_p.h
@@ -0,0 +1,12 @@
+#ifndef OBJB_P_HPP
+#define OBJB_P_HPP
+
+class ObjBPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ ObjBPrivate();
+ ~ObjBPrivate();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/ObjC.cpp b/Tests/QtAutogen/mocInclude/ObjC.cpp
deleted file mode 100644
index 8ca34cbb4..000000000
--- a/Tests/QtAutogen/mocInclude/ObjC.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "ObjC.hpp"
-
-class SubObjC : public QObject
-{
- Q_OBJECT
-
-public:
- SubObjC() {}
- ~SubObjC() {}
-
- Q_SLOT
- void aSlot();
-};
-
-void SubObjC::aSlot()
-{
-}
-
-void ObjC::go()
-{
- SubObjC subObj;
-}
-
-#include "ObjC.moc"
-// Not the own header
-#include "moc_ObjD.cpp"
diff --git a/Tests/QtAutogen/mocInclude/ObjC.hpp b/Tests/QtAutogen/mocInclude/ObjC.hpp
deleted file mode 100644
index a8e98eb1e..000000000
--- a/Tests/QtAutogen/mocInclude/ObjC.hpp
+++ /dev/null
@@ -1,13 +0,0 @@
-#ifndef OBJC_HPP
-#define OBJC_HPP
-
-#include <QObject>
-
-class ObjC : public QObject
-{
- Q_OBJECT
- Q_SLOT
- void go();
-};
-
-#endif
diff --git a/Tests/QtAutogen/mocInclude/ObjD.cpp b/Tests/QtAutogen/mocInclude/ObjD.cpp
deleted file mode 100644
index c18aec152..000000000
--- a/Tests/QtAutogen/mocInclude/ObjD.cpp
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "ObjD.hpp"
-
-class SubObjD : public QObject
-{
- Q_OBJECT
-
-public:
- SubObjD() {}
- ~SubObjD() {}
-
- Q_SLOT
- void aSlot();
-};
-
-void SubObjD::aSlot()
-{
-}
-
-void ObjD::go()
-{
- SubObjD subObj;
-}
-
-#include "ObjD.moc"
-// Header in subdirectory
-#include "subA/moc_SubObjA.cpp"
diff --git a/Tests/QtAutogen/mocInclude/ObjD.hpp b/Tests/QtAutogen/mocInclude/ObjD.hpp
deleted file mode 100644
index b6ee09808..000000000
--- a/Tests/QtAutogen/mocInclude/ObjD.hpp
+++ /dev/null
@@ -1,13 +0,0 @@
-#ifndef OBJD_HPP
-#define OBJD_HPP
-
-#include <QObject>
-
-class ObjD : public QObject
-{
- Q_OBJECT
- Q_SLOT
- void go();
-};
-
-#endif
diff --git a/Tests/QtAutogen/mocInclude/SObjA.cpp b/Tests/QtAutogen/mocInclude/SObjA.cpp
new file mode 100644
index 000000000..7e75bf973
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/SObjA.cpp
@@ -0,0 +1,11 @@
+#include "SObjA.hpp"
+
+SObjA::SObjA()
+{
+}
+
+SObjA::~SObjA()
+{
+}
+
+#include "SObjA.moc"
diff --git a/Tests/QtAutogen/mocInclude/SObjA.hpp b/Tests/QtAutogen/mocInclude/SObjA.hpp
new file mode 100644
index 000000000..1436abc6c
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/SObjA.hpp
@@ -0,0 +1,15 @@
+#ifndef SOBJA_HPP
+#define SOBJA_HPP
+
+#include <QObject>
+
+// Object source includes externally generated .moc file
+class SObjA : public QObject
+{
+ Q_OBJECT
+public:
+ SObjA();
+ ~SObjA();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/SObjB.cpp.in b/Tests/QtAutogen/mocInclude/SObjB.cpp.in
new file mode 100644
index 000000000..b1cc12ab2
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/SObjB.cpp.in
@@ -0,0 +1,11 @@
+#include "SObjB.hpp"
+
+SObjB::SObjB()
+{
+}
+
+SObjB::~SObjB()
+{
+}
+
+#include "SObjB.moc"
diff --git a/Tests/QtAutogen/mocInclude/SObjB.hpp.in b/Tests/QtAutogen/mocInclude/SObjB.hpp.in
new file mode 100644
index 000000000..5e396aea8
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/SObjB.hpp.in
@@ -0,0 +1,15 @@
+#ifndef SOBJB_HPP
+#define SOBJB_HPP
+
+#include <QObject>
+
+// Object source includes externally generated .moc file
+class SObjB : public QObject
+{
+ Q_OBJECT
+public:
+ SObjB();
+ ~SObjB();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/SObjC.cpp b/Tests/QtAutogen/mocInclude/SObjC.cpp
new file mode 100644
index 000000000..1e8d397f9
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/SObjC.cpp
@@ -0,0 +1,35 @@
+#include "SObjC.hpp"
+
+void SObjCLocalFunction();
+
+class SObjCLocal : public QObject
+{
+ Q_OBJECT
+
+public:
+ SObjCLocal();
+ ~SObjCLocal();
+};
+
+SObjCLocal::SObjCLocal()
+{
+}
+
+SObjCLocal::~SObjCLocal()
+{
+}
+
+SObjC::SObjC()
+{
+ SObjCLocal localObject;
+ SObjCLocalFunction();
+}
+
+SObjC::~SObjC()
+{
+}
+
+#include "SObjC.moc"
+#include "moc_SObjC.cpp"
+// Include moc_ file for which the header is SKIP_AUTOMOC enabled
+#include "moc_SObjCExtra.cpp"
diff --git a/Tests/QtAutogen/mocInclude/SObjC.hpp b/Tests/QtAutogen/mocInclude/SObjC.hpp
new file mode 100644
index 000000000..def0f9d96
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/SObjC.hpp
@@ -0,0 +1,15 @@
+#ifndef SOBJC_HPP
+#define SOBJC_HPP
+
+#include <QObject>
+
+// Object source includes externally generated .moc file
+class SObjC : public QObject
+{
+ Q_OBJECT
+public:
+ SObjC();
+ ~SObjC();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/SObjCExtra.cpp b/Tests/QtAutogen/mocInclude/SObjCExtra.cpp
new file mode 100644
index 000000000..55dd1c315
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/SObjCExtra.cpp
@@ -0,0 +1,31 @@
+#include "SObjCExtra.hpp"
+
+class SObjCLocalExtra : public QObject
+{
+ Q_OBJECT
+
+public:
+ SObjCLocalExtra();
+ ~SObjCLocalExtra();
+};
+
+SObjCLocalExtra::SObjCLocalExtra()
+{
+}
+
+SObjCLocalExtra::~SObjCLocalExtra()
+{
+}
+
+SObjCExtra::SObjCExtra()
+{
+}
+
+SObjCExtra::~SObjCExtra()
+{
+}
+
+// Externally generated header moc
+#include "SObjCExtra_extMoc.cpp"
+// AUTOMOC generated source moc
+#include "SObjCExtra.moc"
diff --git a/Tests/QtAutogen/mocInclude/SObjCExtra.hpp b/Tests/QtAutogen/mocInclude/SObjCExtra.hpp
new file mode 100644
index 000000000..08545ac29
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/SObjCExtra.hpp
@@ -0,0 +1,15 @@
+#ifndef SOBJCEXTRA_HPP
+#define SOBJCEXTRA_HPP
+
+#include <QObject>
+
+// Object source includes externally generated .moc file
+class SObjCExtra : public QObject
+{
+ Q_OBJECT
+public:
+ SObjCExtra();
+ ~SObjCExtra();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/SObjCExtra.moc.in b/Tests/QtAutogen/mocInclude/SObjCExtra.moc.in
new file mode 100644
index 000000000..00fc4aabe
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/SObjCExtra.moc.in
@@ -0,0 +1,4 @@
+
+void SObjCLocalFunction()
+{
+}
diff --git a/Tests/QtAutogen/mocInclude/shared.cmake b/Tests/QtAutogen/mocInclude/shared.cmake
new file mode 100644
index 000000000..d05f27c27
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/shared.cmake
@@ -0,0 +1,71 @@
+# Test moc include patterns
+include_directories("../mocInclude")
+include_directories(${CMAKE_CURRENT_BINARY_DIR})
+
+# Generate .moc file externally and enabled SKIP_AUTOMOC on the file
+qtx_generate_moc(
+ ${CMAKE_CURRENT_SOURCE_DIR}/../mocInclude/SObjA.hpp
+ ${CMAKE_CURRENT_BINARY_DIR}/SObjA.moc)
+set_property(SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../mocInclude/SObjA.cpp PROPERTY SKIP_AUTOMOC ON)
+
+# Generate .moc file externally from generated source file
+# and enabled SKIP_AUTOMOC on the source file
+add_custom_command(
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/SObjB.hpp
+ COMMAND ${CMAKE_COMMAND} -E copy
+ ${CMAKE_CURRENT_SOURCE_DIR}/../mocInclude/SObjB.hpp.in
+ ${CMAKE_CURRENT_BINARY_DIR}/SObjB.hpp)
+add_custom_command(
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/SObjB.cpp
+ COMMAND ${CMAKE_COMMAND} -E copy
+ ${CMAKE_CURRENT_SOURCE_DIR}/../mocInclude/SObjB.cpp.in
+ ${CMAKE_CURRENT_BINARY_DIR}/SObjB.cpp)
+qtx_generate_moc(
+ ${CMAKE_CURRENT_BINARY_DIR}/SObjB.hpp
+ ${CMAKE_CURRENT_BINARY_DIR}/SObjB.moc)
+set_property(SOURCE ${CMAKE_CURRENT_BINARY_DIR}/SObjB.cpp PROPERTY SKIP_AUTOMOC ON)
+
+# Generate moc file externally and enabled SKIP_AUTOMOC on the header
+qtx_generate_moc(
+ ${CMAKE_CURRENT_SOURCE_DIR}/../mocInclude/SObjCExtra.hpp
+ ${CMAKE_CURRENT_BINARY_DIR}/SObjCExtra_extMoc.cpp)
+set_property(
+ SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../mocInclude/SObjCExtra.hpp
+ PROPERTY SKIP_AUTOMOC ON)
+# Custom target to depend on
+set(SOBJC_MOC ${CMAKE_CURRENT_BINARY_DIR}/moc_SObjCExtra.cpp)
+add_custom_target("${MOC_INCLUDE_NAME}_SOBJC"
+ DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/SObjCExtra_extMoc.cpp
+ BYPRODUCTS ${SOBJC_MOC}
+ COMMAND ${CMAKE_COMMAND} -E copy
+ ${CMAKE_CURRENT_SOURCE_DIR}/../mocInclude/SObjCExtra.moc.in
+ ${SOBJC_MOC})
+
+# MOC_INCLUDE_NAME must be defined by the includer
+add_executable(${MOC_INCLUDE_NAME}
+ # Common sources
+ ../mocInclude/ObjA.cpp
+ ../mocInclude/ObjB.cpp
+
+ ../mocInclude/LObjA.cpp
+ ../mocInclude/LObjB.cpp
+
+ ../mocInclude/EObjA.cpp
+ ../mocInclude/EObjAExtra.cpp
+ ../mocInclude/EObjB.cpp
+ ../mocInclude/subExtra/EObjBExtra.cpp
+
+ ../mocInclude/SObjA.cpp
+ ${CMAKE_CURRENT_BINARY_DIR}/SObjA.moc
+ ${CMAKE_CURRENT_BINARY_DIR}/SObjB.cpp
+ ${CMAKE_CURRENT_BINARY_DIR}/SObjB.moc
+ ../mocInclude/SObjC.cpp
+ ../mocInclude/SObjCExtra.hpp
+ ../mocInclude/SObjCExtra.cpp
+
+ ../mocInclude/subGlobal/GObj.cpp
+ main.cpp
+)
+add_dependencies(${MOC_INCLUDE_NAME} "${MOC_INCLUDE_NAME}_SOBJC")
+target_link_libraries(${MOC_INCLUDE_NAME} ${QT_LIBRARIES})
+set_target_properties(${MOC_INCLUDE_NAME} PROPERTIES AUTOMOC ON)
diff --git a/Tests/QtAutogen/mocInclude/subA/SubObjA.cpp b/Tests/QtAutogen/mocInclude/subA/SubObjA.cpp
deleted file mode 100644
index a05f6e37e..000000000
--- a/Tests/QtAutogen/mocInclude/subA/SubObjA.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "SubObjA.hpp"
-
-namespace subA {
-
-class SubObjA : public QObject
-{
- Q_OBJECT
-
-public:
- SubObjA() {}
- ~SubObjA() {}
-
- Q_SLOT
- void aSlot();
-};
-
-void SubObjA::aSlot()
-{
-}
-
-void ObjA::go()
-{
- SubObjA subObj;
-}
-}
-
-#include "SubObjA.moc"
diff --git a/Tests/QtAutogen/mocInclude/subA/SubObjA.hpp b/Tests/QtAutogen/mocInclude/subA/SubObjA.hpp
deleted file mode 100644
index 31a18b618..000000000
--- a/Tests/QtAutogen/mocInclude/subA/SubObjA.hpp
+++ /dev/null
@@ -1,16 +0,0 @@
-#ifndef SUBOBJA_HPP
-#define SUBOBJA_HPP
-
-#include <QObject>
-
-namespace subA {
-
-class ObjA : public QObject
-{
- Q_OBJECT
- Q_SLOT
- void go();
-};
-}
-
-#endif
diff --git a/Tests/QtAutogen/mocInclude/subB/SubObjB.cpp b/Tests/QtAutogen/mocInclude/subB/SubObjB.cpp
deleted file mode 100644
index 1e77639b2..000000000
--- a/Tests/QtAutogen/mocInclude/subB/SubObjB.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "SubObjB.hpp"
-
-namespace subB {
-
-class SubObjB : public QObject
-{
- Q_OBJECT
-
-public:
- SubObjB() {}
- ~SubObjB() {}
-
- Q_SLOT
- void aSlot();
-};
-
-void SubObjB::aSlot()
-{
-}
-
-void ObjB::go()
-{
- SubObjB subObj;
-}
-}
-
-#include "SubObjB.moc"
diff --git a/Tests/QtAutogen/mocInclude/subB/SubObjB.hpp b/Tests/QtAutogen/mocInclude/subB/SubObjB.hpp
deleted file mode 100644
index 3f29fa289..000000000
--- a/Tests/QtAutogen/mocInclude/subB/SubObjB.hpp
+++ /dev/null
@@ -1,16 +0,0 @@
-#ifndef SUBOBJB_HPP
-#define SUBOBJB_HPP
-
-#include <QObject>
-
-namespace subB {
-
-class ObjB : public QObject
-{
- Q_OBJECT
- Q_SLOT
- void go();
-};
-}
-
-#endif
diff --git a/Tests/QtAutogen/mocInclude/subC/SubObjC.cpp b/Tests/QtAutogen/mocInclude/subC/SubObjC.cpp
deleted file mode 100644
index c2d94ef26..000000000
--- a/Tests/QtAutogen/mocInclude/subC/SubObjC.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-#include "SubObjC.hpp"
-
-namespace subC {
-
-class SubObjC : public QObject
-{
- Q_OBJECT
-
-public:
- SubObjC() {}
- ~SubObjC() {}
-
- Q_SLOT
- void aSlot();
-};
-
-void SubObjC::aSlot()
-{
-}
-
-void ObjC::go()
-{
- SubObjC subObj;
-}
-}
-
-#include "SubObjC.moc"
diff --git a/Tests/QtAutogen/mocInclude/subC/SubObjC.hpp b/Tests/QtAutogen/mocInclude/subC/SubObjC.hpp
deleted file mode 100644
index dc251fd61..000000000
--- a/Tests/QtAutogen/mocInclude/subC/SubObjC.hpp
+++ /dev/null
@@ -1,16 +0,0 @@
-#ifndef SUBOBJC_HPP
-#define SUBOBJC_HPP
-
-#include <QObject>
-
-namespace subC {
-
-class ObjC : public QObject
-{
- Q_OBJECT
- Q_SLOT
- void go();
-};
-}
-
-#endif
diff --git a/Tests/QtAutogen/mocInclude/subExtra/EObjBExtra.cpp b/Tests/QtAutogen/mocInclude/subExtra/EObjBExtra.cpp
new file mode 100644
index 000000000..c697866e7
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/subExtra/EObjBExtra.cpp
@@ -0,0 +1,20 @@
+#include "EObjBExtra.hpp"
+#include "EObjBExtra_p.hpp"
+
+EObjBExtraPrivate::EObjBExtraPrivate()
+{
+}
+
+EObjBExtraPrivate::~EObjBExtraPrivate()
+{
+}
+
+EObjBExtra::EObjBExtra()
+ : d(new EObjBExtraPrivate)
+{
+}
+
+EObjBExtra::~EObjBExtra()
+{
+ delete d;
+}
diff --git a/Tests/QtAutogen/mocInclude/subExtra/EObjBExtra.hpp b/Tests/QtAutogen/mocInclude/subExtra/EObjBExtra.hpp
new file mode 100644
index 000000000..3798d7f52
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/subExtra/EObjBExtra.hpp
@@ -0,0 +1,18 @@
+#ifndef EOBJBEXTRA_HPP
+#define EOBJBEXTRA_HPP
+
+#include <QObject>
+
+class EObjBExtraPrivate;
+class EObjBExtra : public QObject
+{
+ Q_OBJECT
+public:
+ EObjBExtra();
+ ~EObjBExtra();
+
+private:
+ EObjBExtraPrivate* const d;
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/subExtra/EObjBExtra_p.hpp b/Tests/QtAutogen/mocInclude/subExtra/EObjBExtra_p.hpp
new file mode 100644
index 000000000..db8a0961f
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/subExtra/EObjBExtra_p.hpp
@@ -0,0 +1,12 @@
+#ifndef EOBJBEXTRA_P_HPP
+#define EOBJBEXTRA_P_HPP
+
+class EObjBExtraPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ EObjBExtraPrivate();
+ ~EObjBExtraPrivate();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/subGlobal/GObj.cpp b/Tests/QtAutogen/mocInclude/subGlobal/GObj.cpp
new file mode 100644
index 000000000..6b92f2194
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/subGlobal/GObj.cpp
@@ -0,0 +1,41 @@
+#include "GObj.hpp"
+#include "GObj_p.hpp"
+
+namespace subGlobal {
+
+class GObjLocal : public QObject
+{
+ Q_OBJECT
+public:
+ GObjLocal();
+ ~GObjLocal();
+};
+
+GObjLocal::GObjLocal()
+{
+}
+
+GObjLocal::~GObjLocal()
+{
+}
+
+GObjPrivate::GObjPrivate()
+{
+}
+
+GObjPrivate::~GObjPrivate()
+{
+}
+
+GObj::GObj()
+{
+ GObjLocal localObj;
+}
+
+GObj::~GObj()
+{
+}
+}
+
+// For the local QObject
+#include "GObj.moc"
diff --git a/Tests/QtAutogen/mocInclude/subGlobal/GObj.hpp b/Tests/QtAutogen/mocInclude/subGlobal/GObj.hpp
new file mode 100644
index 000000000..2f9ee8207
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/subGlobal/GObj.hpp
@@ -0,0 +1,17 @@
+#ifndef GOBJ_HPP
+#define GOBJ_HPP
+
+#include <QObject>
+
+namespace subGlobal {
+
+class GObj : public QObject
+{
+ Q_OBJECT
+public:
+ GObj();
+ ~GObj();
+};
+}
+
+#endif
diff --git a/Tests/QtAutogen/mocInclude/subGlobal/GObj_p.hpp b/Tests/QtAutogen/mocInclude/subGlobal/GObj_p.hpp
new file mode 100644
index 000000000..7b37dfd18
--- /dev/null
+++ b/Tests/QtAutogen/mocInclude/subGlobal/GObj_p.hpp
@@ -0,0 +1,15 @@
+#ifndef GOBJ_P_HPP
+#define GOBJ_P_HPP
+
+namespace subGlobal {
+
+class GObjPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ GObjPrivate();
+ ~GObjPrivate();
+};
+}
+
+#endif
diff --git a/Tests/QtAutogen/mocIncludeRelaxed/CMakeLists.txt b/Tests/QtAutogen/mocIncludeRelaxed/CMakeLists.txt
index 6a0829df7..97ba1df51 100644
--- a/Tests/QtAutogen/mocIncludeRelaxed/CMakeLists.txt
+++ b/Tests/QtAutogen/mocIncludeRelaxed/CMakeLists.txt
@@ -2,17 +2,16 @@
set(CMAKE_AUTOMOC_RELAXED_MODE TRUE)
-include_directories("../mocInclude")
+# Shared executable
+set(MOC_INCLUDE_NAME "mocIncludeRelaxed")
+include(${CMAKE_CURRENT_SOURCE_DIR}/../mocInclude/shared.cmake)
-add_executable(mocIncludeRelaxed
- ../mocInclude/ObjA.cpp
- ../mocInclude/ObjB.cpp
- ../mocInclude/ObjC.cpp
- ../mocInclude/ObjD.cpp
- ../mocInclude/subA/SubObjA.cpp
- ../mocInclude/subB/SubObjB.cpp
- ../mocInclude/subC/SubObjC.cpp
- main.cpp
+# Relaxed ony executable
+add_executable(mocIncludeRelaxedOnly
+ RObjA.cpp
+ RObjB.cpp
+ RObjC.cpp
+ RMain.cpp
)
-target_link_libraries(mocIncludeRelaxed ${QT_LIBRARIES})
-set_target_properties(mocIncludeRelaxed PROPERTIES AUTOMOC ON)
+target_link_libraries(mocIncludeRelaxedOnly ${QT_LIBRARIES})
+set_target_properties(mocIncludeRelaxedOnly PROPERTIES AUTOMOC ON)
diff --git a/Tests/QtAutogen/mocIncludeRelaxed/RMain.cpp b/Tests/QtAutogen/mocIncludeRelaxed/RMain.cpp
new file mode 100644
index 000000000..5b2c07032
--- /dev/null
+++ b/Tests/QtAutogen/mocIncludeRelaxed/RMain.cpp
@@ -0,0 +1,12 @@
+// Relaxed AUTOMOC objects
+#include "RObjA.hpp"
+#include "RObjB.hpp"
+#include "RObjC.hpp"
+
+int main(int argv, char** args)
+{
+ RObjA rObjA;
+ RObjB rObjB;
+ RObjC rObjC;
+ return 0;
+}
diff --git a/Tests/QtAutogen/mocIncludeRelaxed/RObjA.cpp b/Tests/QtAutogen/mocIncludeRelaxed/RObjA.cpp
new file mode 100644
index 000000000..2e2cf6a48
--- /dev/null
+++ b/Tests/QtAutogen/mocIncludeRelaxed/RObjA.cpp
@@ -0,0 +1,12 @@
+#include "RObjA.hpp"
+
+RObjA::RObjA()
+{
+}
+
+RObjA::~RObjA()
+{
+}
+
+// Relaxed include should moc the header instead
+#include "RObjA.moc"
diff --git a/Tests/QtAutogen/mocIncludeRelaxed/RObjA.hpp b/Tests/QtAutogen/mocIncludeRelaxed/RObjA.hpp
new file mode 100644
index 000000000..597418773
--- /dev/null
+++ b/Tests/QtAutogen/mocIncludeRelaxed/RObjA.hpp
@@ -0,0 +1,14 @@
+#ifndef ROBJA_HPP
+#define ROBJA_HPP
+
+#include <QObject>
+
+class RObjA : public QObject
+{
+ Q_OBJECT
+public:
+ RObjA();
+ ~RObjA();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocIncludeRelaxed/RObjB.cpp b/Tests/QtAutogen/mocIncludeRelaxed/RObjB.cpp
new file mode 100644
index 000000000..c56d10f04
--- /dev/null
+++ b/Tests/QtAutogen/mocIncludeRelaxed/RObjB.cpp
@@ -0,0 +1,22 @@
+#include "RObjB.hpp"
+#include "RObjBExtra.hpp"
+
+RObjBExtra::RObjBExtra()
+{
+}
+
+RObjBExtra::~RObjBExtra()
+{
+}
+
+RObjB::RObjB()
+{
+ RObjBExtra extraObject;
+}
+
+RObjB::~RObjB()
+{
+}
+
+// Relaxed mode should run moc on RObjBExtra.hpp instead
+#include "RObjBExtra.moc"
diff --git a/Tests/QtAutogen/mocIncludeRelaxed/RObjB.hpp b/Tests/QtAutogen/mocIncludeRelaxed/RObjB.hpp
new file mode 100644
index 000000000..d6d0474ad
--- /dev/null
+++ b/Tests/QtAutogen/mocIncludeRelaxed/RObjB.hpp
@@ -0,0 +1,14 @@
+#ifndef ROBJB_HPP
+#define ROBJB_HPP
+
+#include <QObject>
+
+class RObjB : public QObject
+{
+ Q_OBJECT
+public:
+ RObjB();
+ ~RObjB();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocIncludeRelaxed/RObjBExtra.hpp b/Tests/QtAutogen/mocIncludeRelaxed/RObjBExtra.hpp
new file mode 100644
index 000000000..5d6be752f
--- /dev/null
+++ b/Tests/QtAutogen/mocIncludeRelaxed/RObjBExtra.hpp
@@ -0,0 +1,14 @@
+#ifndef ROBJBEXTRA_HPP
+#define ROBJBEXTRA_HPP
+
+#include <QObject>
+
+class RObjBExtra : public QObject
+{
+ Q_OBJECT
+public:
+ RObjBExtra();
+ ~RObjBExtra();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocIncludeRelaxed/RObjC.cpp b/Tests/QtAutogen/mocIncludeRelaxed/RObjC.cpp
new file mode 100644
index 000000000..4ba32f54b
--- /dev/null
+++ b/Tests/QtAutogen/mocIncludeRelaxed/RObjC.cpp
@@ -0,0 +1,30 @@
+#include "RObjC.hpp"
+#include <QObject>
+
+class RObjCPrivate : public QObject
+{
+ Q_OBJECT
+public:
+ RObjCPrivate();
+ ~RObjCPrivate();
+};
+
+RObjCPrivate::RObjCPrivate()
+{
+}
+
+RObjCPrivate::~RObjCPrivate()
+{
+}
+
+RObjC::RObjC()
+{
+ RObjCPrivate privateObject;
+}
+
+RObjC::~RObjC()
+{
+}
+
+// Relaxed include should moc this source instead of the header
+#include "moc_RObjC.cpp"
diff --git a/Tests/QtAutogen/mocIncludeRelaxed/RObjC.hpp b/Tests/QtAutogen/mocIncludeRelaxed/RObjC.hpp
new file mode 100644
index 000000000..5552ede4a
--- /dev/null
+++ b/Tests/QtAutogen/mocIncludeRelaxed/RObjC.hpp
@@ -0,0 +1,14 @@
+#ifndef ROBJC_HPP
+#define ROBJC_HPP
+
+#include <QObject>
+
+class RObjC : public QObject
+{
+ Q_OBJECT
+public:
+ RObjC();
+ ~RObjC();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocIncludeRelaxed/main.cpp b/Tests/QtAutogen/mocIncludeRelaxed/main.cpp
index 142d59e69..5a3148dda 100644
--- a/Tests/QtAutogen/mocIncludeRelaxed/main.cpp
+++ b/Tests/QtAutogen/mocIncludeRelaxed/main.cpp
@@ -1,14 +1,26 @@
+#include "EObjA.hpp"
+#include "EObjB.hpp"
+#include "LObjA.hpp"
+#include "LObjB.hpp"
#include "ObjA.hpp"
#include "ObjB.hpp"
-#include "ObjC.hpp"
+#include "SObjA.hpp"
+#include "SObjB.hpp"
+#include "subGlobal/GObj.hpp"
int main(int argv, char** args)
{
+ subGlobal::GObj gObj;
ObjA objA;
ObjB objB;
- ObjC objC;
+ LObjA lObjA;
+ LObjB lObjB;
+ EObjA eObjA;
+ EObjB eObjB;
+ SObjA sObjA;
+ SObjB sObjB;
return 0;
}
// Header in global subdirectory
-#include "subB/moc_SubObjB.cpp"
+#include "subGlobal/moc_GObj.cpp"
diff --git a/Tests/QtAutogen/mocIncludeStrict/CMakeLists.txt b/Tests/QtAutogen/mocIncludeStrict/CMakeLists.txt
index 22e93a8ba..789354a22 100644
--- a/Tests/QtAutogen/mocIncludeStrict/CMakeLists.txt
+++ b/Tests/QtAutogen/mocIncludeStrict/CMakeLists.txt
@@ -1,18 +1,6 @@
# Test moc include patterns
set(CMAKE_AUTOMOC_RELAXED_MODE FALSE)
+set(MOC_INCLUDE_NAME "mocIncludeStrict")
-include_directories("../mocInclude")
-
-add_executable(mocIncludeStrict
- ../mocInclude/ObjA.cpp
- ../mocInclude/ObjB.cpp
- ../mocInclude/ObjC.cpp
- ../mocInclude/ObjD.cpp
- ../mocInclude/subA/SubObjA.cpp
- ../mocInclude/subB/SubObjB.cpp
- ../mocInclude/subC/SubObjC.cpp
- main.cpp
-)
-target_link_libraries(mocIncludeStrict ${QT_LIBRARIES})
-set_target_properties(mocIncludeStrict PROPERTIES AUTOMOC ON)
+include(${CMAKE_CURRENT_SOURCE_DIR}/../mocInclude/shared.cmake)
diff --git a/Tests/QtAutogen/mocIncludeStrict/main.cpp b/Tests/QtAutogen/mocIncludeStrict/main.cpp
index 142d59e69..5a3148dda 100644
--- a/Tests/QtAutogen/mocIncludeStrict/main.cpp
+++ b/Tests/QtAutogen/mocIncludeStrict/main.cpp
@@ -1,14 +1,26 @@
+#include "EObjA.hpp"
+#include "EObjB.hpp"
+#include "LObjA.hpp"
+#include "LObjB.hpp"
#include "ObjA.hpp"
#include "ObjB.hpp"
-#include "ObjC.hpp"
+#include "SObjA.hpp"
+#include "SObjB.hpp"
+#include "subGlobal/GObj.hpp"
int main(int argv, char** args)
{
+ subGlobal::GObj gObj;
ObjA objA;
ObjB objB;
- ObjC objC;
+ LObjA lObjA;
+ LObjB lObjB;
+ EObjA eObjA;
+ EObjB eObjB;
+ SObjA sObjA;
+ SObjB sObjB;
return 0;
}
// Header in global subdirectory
-#include "subB/moc_SubObjB.cpp"
+#include "subGlobal/moc_GObj.cpp"
diff --git a/Tests/QtAutogen/mocMacroName/CMakeLists.txt b/Tests/QtAutogen/mocMacroName/CMakeLists.txt
new file mode 100644
index 000000000..08e680314
--- /dev/null
+++ b/Tests/QtAutogen/mocMacroName/CMakeLists.txt
@@ -0,0 +1,8 @@
+cmake_minimum_required(VERSION 3.9)
+
+list(APPEND CMAKE_AUTOMOC_MACRO_NAMES "QO1_ALIAS")
+
+add_executable(mmn main.cpp Gadget.cpp Object.cpp Object1Aliased.cpp Object2Aliased.cpp)
+set_property(TARGET mmn PROPERTY AUTOMOC ON)
+set_property(TARGET mmn APPEND PROPERTY AUTOMOC_MACRO_NAMES "QO2_ALIAS")
+target_link_libraries(mmn ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/mocMacroName/CustomMacros.hpp b/Tests/QtAutogen/mocMacroName/CustomMacros.hpp
new file mode 100644
index 000000000..93e5bfdc1
--- /dev/null
+++ b/Tests/QtAutogen/mocMacroName/CustomMacros.hpp
@@ -0,0 +1,8 @@
+#ifndef CUSTOM_MACROS_HPP
+#define CUSTOM_MACROS_HPP
+
+#include <QObject>
+#define QO1_ALIAS Q_OBJECT
+#define QO2_ALIAS Q_OBJECT
+
+#endif
diff --git a/Tests/QtAutogen/mocMacroName/Gadget.cpp b/Tests/QtAutogen/mocMacroName/Gadget.cpp
new file mode 100644
index 000000000..167faebd3
--- /dev/null
+++ b/Tests/QtAutogen/mocMacroName/Gadget.cpp
@@ -0,0 +1,6 @@
+#include "Gadget.hpp"
+
+Gadget::Gadget()
+ : test(0)
+{
+}
diff --git a/Tests/QtAutogen/mocMacroName/Gadget.hpp b/Tests/QtAutogen/mocMacroName/Gadget.hpp
new file mode 100644
index 000000000..2587ed275
--- /dev/null
+++ b/Tests/QtAutogen/mocMacroName/Gadget.hpp
@@ -0,0 +1,15 @@
+#ifndef GADGET_HPP
+#define GADGET_HPP
+
+#include <QMetaType>
+
+class Gadget
+{
+ Q_GADGET
+ Q_PROPERTY(int test MEMBER test)
+public:
+ Gadget();
+ int test;
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocMacroName/Object.cpp b/Tests/QtAutogen/mocMacroName/Object.cpp
new file mode 100644
index 000000000..c0b4f33fc
--- /dev/null
+++ b/Tests/QtAutogen/mocMacroName/Object.cpp
@@ -0,0 +1,9 @@
+#include "Object.hpp"
+
+Object::Object()
+{
+}
+
+void Object::aSlot()
+{
+}
diff --git a/Tests/QtAutogen/mocMacroName/Object.hpp b/Tests/QtAutogen/mocMacroName/Object.hpp
new file mode 100644
index 000000000..0c40824ad
--- /dev/null
+++ b/Tests/QtAutogen/mocMacroName/Object.hpp
@@ -0,0 +1,19 @@
+#ifndef OBJECT_HPP
+#define OBJECT_HPP
+
+#include <QObject>
+
+class Object : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int test MEMBER test)
+public:
+ Object();
+
+ Q_SLOT
+ void aSlot();
+
+ int test;
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocMacroName/Object1Aliased.cpp b/Tests/QtAutogen/mocMacroName/Object1Aliased.cpp
new file mode 100644
index 000000000..b8b4806c6
--- /dev/null
+++ b/Tests/QtAutogen/mocMacroName/Object1Aliased.cpp
@@ -0,0 +1,9 @@
+#include "Object1Aliased.hpp"
+
+Object1Aliased::Object1Aliased()
+{
+}
+
+void Object1Aliased::aSlot()
+{
+}
diff --git a/Tests/QtAutogen/mocMacroName/Object1Aliased.hpp b/Tests/QtAutogen/mocMacroName/Object1Aliased.hpp
new file mode 100644
index 000000000..6c6bb4088
--- /dev/null
+++ b/Tests/QtAutogen/mocMacroName/Object1Aliased.hpp
@@ -0,0 +1,20 @@
+#ifndef OBJECTALIASED_HPP
+#define OBJECTALIASED_HPP
+
+#include "CustomMacros.hpp"
+
+// Test Qt object macro hidden in a macro (AUTOMOC_MACRO_NAMES)
+class Object1Aliased : public QObject
+{
+ QO1_ALIAS
+public:
+ Object1Aliased();
+
+signals:
+ void aSignal();
+
+public slots:
+ void aSlot();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocMacroName/Object2Aliased.cpp b/Tests/QtAutogen/mocMacroName/Object2Aliased.cpp
new file mode 100644
index 000000000..4b09dd1bc
--- /dev/null
+++ b/Tests/QtAutogen/mocMacroName/Object2Aliased.cpp
@@ -0,0 +1,9 @@
+#include "Object2Aliased.hpp"
+
+Object2Aliased::Object2Aliased()
+{
+}
+
+void Object2Aliased::aSlot()
+{
+}
diff --git a/Tests/QtAutogen/mocMacroName/Object2Aliased.hpp b/Tests/QtAutogen/mocMacroName/Object2Aliased.hpp
new file mode 100644
index 000000000..b9bdc126f
--- /dev/null
+++ b/Tests/QtAutogen/mocMacroName/Object2Aliased.hpp
@@ -0,0 +1,20 @@
+#ifndef OBJECT2ALIASED_HPP
+#define OBJECT2ALIASED_HPP
+
+#include "CustomMacros.hpp"
+
+// Test Qt object macro hidden in a macro (AUTOMOC_MACRO_NAMES)
+class Object2Aliased : public QObject
+{
+ QO2_ALIAS
+public:
+ Object2Aliased();
+
+signals:
+ void aSignal();
+
+public slots:
+ void aSlot();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocMacroName/main.cpp b/Tests/QtAutogen/mocMacroName/main.cpp
new file mode 100644
index 000000000..3b45d042d
--- /dev/null
+++ b/Tests/QtAutogen/mocMacroName/main.cpp
@@ -0,0 +1,13 @@
+#include "Gadget.hpp"
+#include "Object.hpp"
+#include "Object1Aliased.hpp"
+#include "Object2Aliased.hpp"
+
+int main(int argv, char** args)
+{
+ Gadget gadget;
+ Object object;
+ Object1Aliased object1Aliased;
+ Object2Aliased object2Aliased;
+ return 0;
+}
diff --git a/Tests/QtAutogen/mocOnlySource/StyleA.cpp b/Tests/QtAutogen/mocOnlySource/StyleA.cpp
new file mode 100644
index 000000000..ced1dd151
--- /dev/null
+++ b/Tests/QtAutogen/mocOnlySource/StyleA.cpp
@@ -0,0 +1,5 @@
+#include "StyleA.hpp"
+
+StyleA::StyleA()
+{
+}
diff --git a/Tests/QtAutogen/mocOnlySource/StyleA.hpp b/Tests/QtAutogen/mocOnlySource/StyleA.hpp
new file mode 100644
index 000000000..66735b63b
--- /dev/null
+++ b/Tests/QtAutogen/mocOnlySource/StyleA.hpp
@@ -0,0 +1,15 @@
+#ifndef STYLEA_HPP
+#define STYLEA_HPP
+
+#include <QObject>
+
+/// Q_OBJECT on a single new line
+///
+class StyleA : public QObject
+{
+ Q_OBJECT
+public:
+ StyleA();
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocOnlySource/StyleB.cpp b/Tests/QtAutogen/mocOnlySource/StyleB.cpp
new file mode 100644
index 000000000..bec6c1c36
--- /dev/null
+++ b/Tests/QtAutogen/mocOnlySource/StyleB.cpp
@@ -0,0 +1,5 @@
+#include "StyleB.hpp"
+
+StyleB::StyleB()
+{
+}
diff --git a/Tests/QtAutogen/mocOnlySource/StyleB.hpp b/Tests/QtAutogen/mocOnlySource/StyleB.hpp
new file mode 100644
index 000000000..425daf845
--- /dev/null
+++ b/Tests/QtAutogen/mocOnlySource/StyleB.hpp
@@ -0,0 +1,16 @@
+#ifndef STYLEB_HPP
+#define STYLEB_HPP
+
+#include <QObject>
+
+/* clang-format off */
+/// Q_OBJECT behind a brace
+///
+class StyleB : public QObject
+{ Q_OBJECT
+public:
+ StyleB();
+};
+/* clang-format on */
+
+#endif
diff --git a/Tests/QtAutogen/mocOnlySource/main.cpp b/Tests/QtAutogen/mocOnlySource/main.cpp
new file mode 100644
index 000000000..06f8d8106
--- /dev/null
+++ b/Tests/QtAutogen/mocOnlySource/main.cpp
@@ -0,0 +1,9 @@
+#include "StyleA.hpp"
+#include "StyleB.hpp"
+
+int main(int argv, char** args)
+{
+ StyleA styleA;
+ StyleB styleB;
+ return 0;
+}
diff --git a/Tests/QtAutogen/mocPlugin/StyleE.hpp b/Tests/QtAutogen/mocPlugin/StyleE.hpp
deleted file mode 100644
index e7915a8e5..000000000
--- a/Tests/QtAutogen/mocPlugin/StyleE.hpp
+++ /dev/null
@@ -1,17 +0,0 @@
-#ifndef STYLEE_HPP
-#define STYLEE_HPP
-
-#include "StyleCommon.hpp"
-#include <QStylePlugin>
-
-class StyleE : public QStylePlugin
-{
- Q_OBJECT
- // No Json file
- Q_PLUGIN_METADATA(IID "org.styles.E")
- A_CUSTOM_MACRO(SomeArg, InvalidFileArg, AnotherArg)
-public:
- QStyle* create(const QString& key);
-};
-
-#endif
diff --git a/Tests/QtAutogen/mocPlugin/jsonIn/StyleB.json b/Tests/QtAutogen/mocPlugin/jsonIn/StyleB.json
deleted file mode 100644
index 129cac41f..000000000
--- a/Tests/QtAutogen/mocPlugin/jsonIn/StyleB.json
+++ /dev/null
@@ -1 +0,0 @@
-{ "Keys": [ "Rocket", "StarbusterB" ] }
diff --git a/Tests/QtAutogen/objectLibrary/CMakeLists.txt b/Tests/QtAutogen/objectLibrary/CMakeLists.txt
new file mode 100644
index 000000000..9b29a4075
--- /dev/null
+++ b/Tests/QtAutogen/objectLibrary/CMakeLists.txt
@@ -0,0 +1,14 @@
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+set(CMAKE_AUTOMOC ON)
+
+# Object library a defined in a subdirectory
+add_subdirectory(a)
+
+# Object library b defined locally
+include_directories(b)
+add_library(b OBJECT b/classb.cpp)
+target_compile_features(b PRIVATE ${QT_COMPILE_FEATURES})
+
+# Executable with OBJECT library generator expressions
+add_executable(someProgram main.cpp $<TARGET_OBJECTS:a> $<TARGET_OBJECTS:b>)
+target_link_libraries(someProgram ${QT_LIBRARIES})
diff --git a/Tests/QtAutogen/objectLibrary/a/CMakeLists.txt b/Tests/QtAutogen/objectLibrary/a/CMakeLists.txt
new file mode 100644
index 000000000..fe76ac32c
--- /dev/null
+++ b/Tests/QtAutogen/objectLibrary/a/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_library(a OBJECT classa.cpp)
+target_compile_features(a PRIVATE ${QT_COMPILE_FEATURES})
diff --git a/Tests/QtAutogen/objectLibrary/a/classa.cpp b/Tests/QtAutogen/objectLibrary/a/classa.cpp
new file mode 100644
index 000000000..4f08fda84
--- /dev/null
+++ b/Tests/QtAutogen/objectLibrary/a/classa.cpp
@@ -0,0 +1,7 @@
+#include "classa.h"
+#include <QDebug>
+
+void ClassA::slotDoSomething()
+{
+ qDebug() << m_member;
+}
diff --git a/Tests/QtAutogen/objectLibrary/a/classa.h b/Tests/QtAutogen/objectLibrary/a/classa.h
new file mode 100644
index 000000000..fa5fed941
--- /dev/null
+++ b/Tests/QtAutogen/objectLibrary/a/classa.h
@@ -0,0 +1,23 @@
+#ifndef CLASSA_H
+#define CLASSA_H
+
+#include <QObject>
+#include <QString>
+
+class ClassA : public QObject
+{
+ Q_OBJECT
+public:
+ ClassA()
+ : m_member("Hello A")
+ {
+ }
+
+public slots:
+ void slotDoSomething();
+
+private:
+ QString m_member;
+};
+
+#endif
diff --git a/Tests/QtAutogen/objectLibrary/b/classb.cpp b/Tests/QtAutogen/objectLibrary/b/classb.cpp
new file mode 100644
index 000000000..26e09261c
--- /dev/null
+++ b/Tests/QtAutogen/objectLibrary/b/classb.cpp
@@ -0,0 +1,7 @@
+#include "classb.h"
+#include <QDebug>
+
+void ClassB::slotDoSomething()
+{
+ qDebug() << m_member;
+}
diff --git a/Tests/QtAutogen/objectLibrary/b/classb.h b/Tests/QtAutogen/objectLibrary/b/classb.h
new file mode 100644
index 000000000..783bb48ce
--- /dev/null
+++ b/Tests/QtAutogen/objectLibrary/b/classb.h
@@ -0,0 +1,23 @@
+#ifndef CLASSB_H
+#define CLASSB_H
+
+#include <QObject>
+#include <QString>
+
+class ClassB : public QObject
+{
+ Q_OBJECT
+public:
+ ClassB()
+ : m_member("Hello B")
+ {
+ }
+
+public slots:
+ void slotDoSomething();
+
+private:
+ QString m_member;
+};
+
+#endif
diff --git a/Tests/QtAutogen/objectLibrary/main.cpp b/Tests/QtAutogen/objectLibrary/main.cpp
new file mode 100644
index 000000000..cacf0fdae
--- /dev/null
+++ b/Tests/QtAutogen/objectLibrary/main.cpp
@@ -0,0 +1,13 @@
+#include "a/classa.h"
+#include "b/classb.h"
+
+int main(int argc, char** argv)
+{
+ ClassA a;
+ a.slotDoSomething();
+
+ ClassB b;
+ b.slotDoSomething();
+
+ return 0;
+}
diff --git a/Tests/QtAutogen/rccDepends/CMakeLists.txt b/Tests/QtAutogen/rccDepends/CMakeLists.txt
deleted file mode 100644
index 878ae5d35..000000000
--- a/Tests/QtAutogen/rccDepends/CMakeLists.txt
+++ /dev/null
@@ -1,35 +0,0 @@
-cmake_minimum_required(VERSION 3.7)
-project(rccDepends)
-
-set(CMAKE_AUTORCC ON)
-
-if (QT_TEST_VERSION STREQUAL 4)
- find_package(Qt4 REQUIRED)
- set(QT_CORE_TARGET Qt4::QtCore)
-else()
- if (NOT QT_TEST_VERSION STREQUAL 5)
- message(SEND_ERROR "Invalid Qt version specified.")
- endif()
-
- find_package(Qt5Core REQUIRED)
- set(QT_CORE_TARGET Qt5::Core)
-endif()
-
-configure_file(res/input1.txt.in res1/input.txt COPYONLY)
-configure_file(res/input1.txt.in res1/inputAdded.txt COPYONLY)
-configure_file(res/input2.txt.in res2/input.txt COPYONLY)
-configure_file(res/input2.txt.in res2/inputAdded.txt COPYONLY)
-# Dependency generated qrc file
-add_custom_command(OUTPUT res2.qrc
- DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/res2.qrc.in
- COMMAND ${CMAKE_COMMAND} -E sleep 2
- COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/res2.qrc.in ${CMAKE_CURRENT_BINARY_DIR}/res2.qrc
- )
-
-add_executable(rccDepends
- main.cpp
- ${CMAKE_CURRENT_BINARY_DIR}/res1.qrc
- ${CMAKE_CURRENT_BINARY_DIR}/res2.qrc )
-target_link_libraries(rccDepends ${QT_CORE_TARGET})
-add_custom_command(TARGET rccDepends POST_BUILD COMMAND
- ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:rccDepends>" > target.txt)
diff --git a/Tests/QtAutogen/rccDepends/res/input1.txt.in b/Tests/QtAutogen/rccDepends/res/input1.txt.in
deleted file mode 100644
index da627624b..000000000
--- a/Tests/QtAutogen/rccDepends/res/input1.txt.in
+++ /dev/null
@@ -1 +0,0 @@
-Res1 input.
diff --git a/Tests/QtAutogen/rccDepends/res/input2.txt.in b/Tests/QtAutogen/rccDepends/res/input2.txt.in
deleted file mode 100644
index 08e14b7bd..000000000
--- a/Tests/QtAutogen/rccDepends/res/input2.txt.in
+++ /dev/null
@@ -1 +0,0 @@
-Res2 input.
diff --git a/Tests/QtAutogen/rccDepends/res1a.qrc.in b/Tests/QtAutogen/rccDepends/res1a.qrc.in
deleted file mode 100644
index d111ffbc7..000000000
--- a/Tests/QtAutogen/rccDepends/res1a.qrc.in
+++ /dev/null
@@ -1,5 +0,0 @@
-<RCC>
- <qresource prefix="/Texts1">
- <file>res1/input.txt</file>
- </qresource>
-</RCC>
diff --git a/Tests/QtAutogen/rccDepends/res1b.qrc.in b/Tests/QtAutogen/rccDepends/res1b.qrc.in
deleted file mode 100644
index 4cb3f047c..000000000
--- a/Tests/QtAutogen/rccDepends/res1b.qrc.in
+++ /dev/null
@@ -1,6 +0,0 @@
-<RCC>
- <qresource prefix="/Texts1">
- <file>res1/input.txt</file>
- <file alias="Added">res1/inputAdded.txt</file>
- </qresource>
-</RCC>
diff --git a/Tests/QtAutogen/rccDepends/res2a.qrc.in b/Tests/QtAutogen/rccDepends/res2a.qrc.in
deleted file mode 100644
index 19f34ac90..000000000
--- a/Tests/QtAutogen/rccDepends/res2a.qrc.in
+++ /dev/null
@@ -1,5 +0,0 @@
-<RCC>
- <qresource prefix="/Texts2">
- <file>res2/input.txt</file>
- </qresource>
-</RCC>
diff --git a/Tests/QtAutogen/rccDepends/res2b.qrc.in b/Tests/QtAutogen/rccDepends/res2b.qrc.in
deleted file mode 100644
index 19e8ba10c..000000000
--- a/Tests/QtAutogen/rccDepends/res2b.qrc.in
+++ /dev/null
@@ -1,6 +0,0 @@
-<RCC>
- <qresource prefix="/Texts2">
- <file>res2/input.txt</file>
- <file alias="Added">res2/inputAdded.txt</file>
- </qresource>
-</RCC>
diff --git a/Tests/QtAutogen/sameName/CMakeLists.txt b/Tests/QtAutogen/sameName/CMakeLists.txt
index 4d2dcd9d2..f695875cb 100644
--- a/Tests/QtAutogen/sameName/CMakeLists.txt
+++ b/Tests/QtAutogen/sameName/CMakeLists.txt
@@ -17,7 +17,10 @@ add_executable(sameName
main.cpp
)
target_link_libraries(sameName ${QT_LIBRARIES})
-set_target_properties(sameName PROPERTIES AUTOMOC TRUE AUTORCC TRUE)
+set_target_properties(sameName PROPERTIES
+ AUTOMOC TRUE
+ AUTOUIC TRUE
+ AUTORCC TRUE)
# Set different compression levels
if (QT_TEST_VERSION STREQUAL 4)
diff --git a/Tests/QtAutogen/sameName/aaa/bbb/item.cpp b/Tests/QtAutogen/sameName/aaa/bbb/item.cpp
index 20d00445e..850206f6b 100644
--- a/Tests/QtAutogen/sameName/aaa/bbb/item.cpp
+++ b/Tests/QtAutogen/sameName/aaa/bbb/item.cpp
@@ -3,8 +3,20 @@
namespace aaa {
namespace bbb {
+class MocLocal : public QObject
+{
+ Q_OBJECT;
+
+public:
+ MocLocal() = default;
+ ~MocLocal() = default;
+};
+
void Item::go()
{
+ MocLocal obj;
}
}
}
+
+#include "aaa/bbb/item.moc"
diff --git a/Tests/QtAutogen/sameName/aaa/item.cpp b/Tests/QtAutogen/sameName/aaa/item.cpp
index 95dd3b674..e35d3d128 100644
--- a/Tests/QtAutogen/sameName/aaa/item.cpp
+++ b/Tests/QtAutogen/sameName/aaa/item.cpp
@@ -1,8 +1,22 @@
#include "item.hpp"
+// Include ui_view.h only in header
namespace aaa {
+class MocLocal : public QObject
+{
+ Q_OBJECT;
+
+public:
+ MocLocal() = default;
+ ~MocLocal() = default;
+};
+
void Item::go()
{
+ Ui_ViewAAA ui;
+ MocLocal obj;
}
}
+
+#include "aaa/item.moc"
diff --git a/Tests/QtAutogen/sameName/aaa/item.hpp b/Tests/QtAutogen/sameName/aaa/item.hpp
index b63466f6d..875f72fdb 100644
--- a/Tests/QtAutogen/sameName/aaa/item.hpp
+++ b/Tests/QtAutogen/sameName/aaa/item.hpp
@@ -2,6 +2,8 @@
#define AAA_ITEM_HPP
#include <QObject>
+// Include ui_view.h only in header
+#include <aaa/ui_view.h>
namespace aaa {
diff --git a/Tests/QtAutogen/sameName/aaa/view.ui b/Tests/QtAutogen/sameName/aaa/view.ui
new file mode 100644
index 000000000..0f0998006
--- /dev/null
+++ b/Tests/QtAutogen/sameName/aaa/view.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>ViewAAA</class>
+ <widget class="QWidget" name="Base">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>400</width>
+ <height>300</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QTreeView" name="treeView"/>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/sameName/bbb/aaa/item.cpp b/Tests/QtAutogen/sameName/bbb/aaa/item.cpp
index ac4b2c27b..7ad01c3ef 100644
--- a/Tests/QtAutogen/sameName/bbb/aaa/item.cpp
+++ b/Tests/QtAutogen/sameName/bbb/aaa/item.cpp
@@ -3,8 +3,20 @@
namespace bbb {
namespace aaa {
+class MocLocal : public QObject
+{
+ Q_OBJECT;
+
+public:
+ MocLocal() = default;
+ ~MocLocal() = default;
+};
+
void Item::go()
{
+ MocLocal obj;
}
}
}
+
+#include "bbb/aaa/item.moc"
diff --git a/Tests/QtAutogen/sameName/bbb/item.cpp b/Tests/QtAutogen/sameName/bbb/item.cpp
index f97a1431e..9ef128ed0 100644
--- a/Tests/QtAutogen/sameName/bbb/item.cpp
+++ b/Tests/QtAutogen/sameName/bbb/item.cpp
@@ -1,8 +1,23 @@
#include "item.hpp"
+// Include ui_view.h only in source
+#include <bbb/ui_view.h>
namespace bbb {
+class MocLocal : public QObject
+{
+ Q_OBJECT;
+
+public:
+ MocLocal() = default;
+ ~MocLocal() = default;
+};
+
void Item::go()
{
+ Ui_ViewBBB ui;
+ MocLocal obj;
}
}
+
+#include "bbb/item.moc"
diff --git a/Tests/QtAutogen/sameName/bbb/item.hpp b/Tests/QtAutogen/sameName/bbb/item.hpp
index 5b7f9850b..d39a9d711 100644
--- a/Tests/QtAutogen/sameName/bbb/item.hpp
+++ b/Tests/QtAutogen/sameName/bbb/item.hpp
@@ -2,6 +2,7 @@
#define BBB_ITEM_HPP
#include <QObject>
+// Include ui_view.h only in source
namespace bbb {
diff --git a/Tests/QtAutogen/sameName/bbb/view.ui b/Tests/QtAutogen/sameName/bbb/view.ui
new file mode 100644
index 000000000..a8f506e88
--- /dev/null
+++ b/Tests/QtAutogen/sameName/bbb/view.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>ViewBBB</class>
+ <widget class="QWidget" name="Base">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>400</width>
+ <height>300</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QTreeView" name="treeView"/>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/sameName/ccc/item.cpp b/Tests/QtAutogen/sameName/ccc/item.cpp
index d90b2b8c7..ab8a2817b 100644
--- a/Tests/QtAutogen/sameName/ccc/item.cpp
+++ b/Tests/QtAutogen/sameName/ccc/item.cpp
@@ -1,23 +1,25 @@
#include "item.hpp"
+// Include ui_view.h in source and header
+#include <ccc/ui_view.h>
namespace ccc {
-void Item::go()
-{
-}
-
-class MocTest : public QObject
+class MocLocal : public QObject
{
Q_OBJECT;
- Q_SLOT
- void go();
+
+public:
+ MocLocal() = default;
+ ~MocLocal() = default;
};
-void MocTest::go()
+void Item::go()
{
+ Ui_ViewCCC ui;
+ MocLocal obj;
}
}
// Include own moc files
-#include "item.moc"
+#include "ccc/item.moc"
#include "moc_item.cpp"
diff --git a/Tests/QtAutogen/sameName/ccc/item.hpp b/Tests/QtAutogen/sameName/ccc/item.hpp
index 96fcc245c..20d9dd978 100644
--- a/Tests/QtAutogen/sameName/ccc/item.hpp
+++ b/Tests/QtAutogen/sameName/ccc/item.hpp
@@ -2,6 +2,8 @@
#define CCC_ITEM_HPP
#include <QObject>
+// Include ui_view.h in source and header
+#include <ccc/ui_view.h>
namespace ccc {
diff --git a/Tests/QtAutogen/sameName/ccc/view.ui b/Tests/QtAutogen/sameName/ccc/view.ui
new file mode 100644
index 000000000..7989c6973
--- /dev/null
+++ b/Tests/QtAutogen/sameName/ccc/view.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>ViewCCC</class>
+ <widget class="QWidget" name="Base">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>400</width>
+ <height>300</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QTreeView" name="treeView"/>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/sameName/item.cpp b/Tests/QtAutogen/sameName/item.cpp
index e013cf392..3d1fbe7cf 100644
--- a/Tests/QtAutogen/sameName/item.cpp
+++ b/Tests/QtAutogen/sameName/item.cpp
@@ -1,5 +1,20 @@
#include "item.hpp"
+// Include ui_view.h in source and header
+#include <ui_view.h>
+
+class MocLocal : public QObject
+{
+ Q_OBJECT;
+
+public:
+ MocLocal() = default;
+ ~MocLocal() = default;
+};
void Item::go()
{
+ Ui_View ui;
+ MocLocal obj;
}
+
+#include "item.moc"
diff --git a/Tests/QtAutogen/sameName/item.hpp b/Tests/QtAutogen/sameName/item.hpp
index 91bba3b4d..75e83f483 100644
--- a/Tests/QtAutogen/sameName/item.hpp
+++ b/Tests/QtAutogen/sameName/item.hpp
@@ -2,6 +2,8 @@
#define ITEM_HPP
#include <QObject>
+// Include ui_view.h in source and header
+#include <ui_view.h>
class Item : public QObject
{
diff --git a/Tests/QtAutogen/sameName/view.ui b/Tests/QtAutogen/sameName/view.ui
new file mode 100644
index 000000000..2ffe7344c
--- /dev/null
+++ b/Tests/QtAutogen/sameName/view.ui
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>View</class>
+ <widget class="QWidget" name="Base">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>400</width>
+ <height>300</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QTreeView" name="treeView"/>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/Tests/QtAutogen/skipMoc.cpp b/Tests/QtAutogen/skipMoc.cpp
index 85305f590..d6b292ff3 100644
--- a/Tests/QtAutogen/skipMoc.cpp
+++ b/Tests/QtAutogen/skipMoc.cpp
@@ -2,12 +2,14 @@
#include "skipSource/qItemA.hpp"
#include "skipSource/qItemB.hpp"
#include "skipSource/qItemC.hpp"
+#include "skipSource/qItemD.hpp"
int main(int, char**)
{
QItemA itemA;
- QItemA itemB;
- QItemA itemC;
+ QItemB itemB;
+ QItemC itemC;
+ QItemD itemD;
// Fails to link if the symbol is not present.
return 0;
diff --git a/Tests/QtAutogen/skipSource/qItemC.cpp b/Tests/QtAutogen/skipSource/qItemC.cpp
index 700abd6db..622f2829e 100644
--- a/Tests/QtAutogen/skipSource/qItemC.cpp
+++ b/Tests/QtAutogen/skipSource/qItemC.cpp
@@ -1,5 +1,17 @@
#include "qItemC.hpp"
+class QItemC_Local : public QObject
+{
+ Q_OBJECT
+public:
+ QItemC_Local(){};
+ ~QItemC_Local(){};
+};
+
void QItemC::go()
{
+ QItemC_Local localObject;
}
+
+// We need AUTOMOC processing
+#include "qItemC.moc"
diff --git a/Tests/QtAutogen/skipSource/qItemD.cpp b/Tests/QtAutogen/skipSource/qItemD.cpp
new file mode 100644
index 000000000..fe0f4e4da
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/qItemD.cpp
@@ -0,0 +1,17 @@
+#include "qItemD.hpp"
+
+class QItemD_Local : public QObject
+{
+ Q_OBJECT
+public:
+ QItemD_Local(){};
+ ~QItemD_Local(){};
+};
+
+void QItemD::go()
+{
+ QItemD_Local localObject;
+}
+
+// We need AUTOMOC processing
+#include "qItemD.moc"
diff --git a/Tests/QtAutogen/skipSource/qItemD.hpp b/Tests/QtAutogen/skipSource/qItemD.hpp
new file mode 100644
index 000000000..99e0acbed
--- /dev/null
+++ b/Tests/QtAutogen/skipSource/qItemD.hpp
@@ -0,0 +1,13 @@
+#ifndef QITEMD_HPP
+#define QITEMD_HPP
+
+#include <QObject>
+
+class QItemD : public QObject
+{
+ Q_OBJECT
+ Q_SLOT
+ void go();
+};
+
+#endif
diff --git a/Tests/QtAutogen/staticLibraryCycle/CMakeLists.txt b/Tests/QtAutogen/staticLibraryCycle/CMakeLists.txt
new file mode 100644
index 000000000..144a435f4
--- /dev/null
+++ b/Tests/QtAutogen/staticLibraryCycle/CMakeLists.txt
@@ -0,0 +1,17 @@
+# Test AUTOMOC and AUTORCC on source files with the same name
+# but in different subdirectories
+
+set(CMAKE_AUTOMOC ON)
+
+# Cyclic static libraries
+add_library(slc_a STATIC a.cpp)
+target_link_libraries(slc_a ${QT_LIBRARIES} slc_b)
+
+add_library(slc_b STATIC b.cpp)
+target_link_libraries(slc_b ${QT_LIBRARIES} slc_c)
+
+add_library(slc_c STATIC c.cpp)
+target_link_libraries(slc_c ${QT_LIBRARIES} slc_a)
+
+add_executable(slc main.cpp)
+target_link_libraries(slc ${QT_LIBRARIES} slc_a)
diff --git a/Tests/QtAutogen/staticLibraryCycle/a.cpp b/Tests/QtAutogen/staticLibraryCycle/a.cpp
new file mode 100644
index 000000000..97cc66e2d
--- /dev/null
+++ b/Tests/QtAutogen/staticLibraryCycle/a.cpp
@@ -0,0 +1,7 @@
+#include "a.h"
+#include "b.h"
+
+A::A()
+{
+ B b;
+}
diff --git a/Tests/QtAutogen/staticLibraryCycle/a.h b/Tests/QtAutogen/staticLibraryCycle/a.h
new file mode 100644
index 000000000..71761708b
--- /dev/null
+++ b/Tests/QtAutogen/staticLibraryCycle/a.h
@@ -0,0 +1,13 @@
+#ifndef CLASSA_HPP
+#define CLASSA_HPP
+
+#include <QObject>
+
+class A : public QObject
+{
+ Q_OBJECT
+public:
+ A();
+};
+
+#endif
diff --git a/Tests/QtAutogen/staticLibraryCycle/b.cpp b/Tests/QtAutogen/staticLibraryCycle/b.cpp
new file mode 100644
index 000000000..a807d89cf
--- /dev/null
+++ b/Tests/QtAutogen/staticLibraryCycle/b.cpp
@@ -0,0 +1,7 @@
+#include "b.h"
+#include "c.h"
+
+B::B()
+{
+ C c;
+}
diff --git a/Tests/QtAutogen/staticLibraryCycle/b.h b/Tests/QtAutogen/staticLibraryCycle/b.h
new file mode 100644
index 000000000..ededbd803
--- /dev/null
+++ b/Tests/QtAutogen/staticLibraryCycle/b.h
@@ -0,0 +1,13 @@
+#ifndef CLASSB_HPP
+#define CLASSB_HPP
+
+#include <QObject>
+
+class B : public QObject
+{
+ Q_OBJECT
+public:
+ B();
+};
+
+#endif
diff --git a/Tests/QtAutogen/staticLibraryCycle/c.cpp b/Tests/QtAutogen/staticLibraryCycle/c.cpp
new file mode 100644
index 000000000..7d427c234
--- /dev/null
+++ b/Tests/QtAutogen/staticLibraryCycle/c.cpp
@@ -0,0 +1,7 @@
+#include "c.h"
+#include "a.h"
+
+C::C()
+{
+ A a;
+}
diff --git a/Tests/QtAutogen/staticLibraryCycle/c.h b/Tests/QtAutogen/staticLibraryCycle/c.h
new file mode 100644
index 000000000..20f3725e9
--- /dev/null
+++ b/Tests/QtAutogen/staticLibraryCycle/c.h
@@ -0,0 +1,13 @@
+#ifndef CLASSC_HPP
+#define CLASSC_HPP
+
+#include <QObject>
+
+class C : public QObject
+{
+ Q_OBJECT
+public:
+ C();
+};
+
+#endif
diff --git a/Tests/QtAutogen/staticLibraryCycle/main.cpp b/Tests/QtAutogen/staticLibraryCycle/main.cpp
new file mode 100644
index 000000000..f5b7fd227
--- /dev/null
+++ b/Tests/QtAutogen/staticLibraryCycle/main.cpp
@@ -0,0 +1,8 @@
+#include "a.h"
+
+int main(int argv, char** args)
+{
+ // Object instances
+ A a;
+ return 0;
+}
diff --git a/Tests/QtAutogenRerun/CMakeLists.txt b/Tests/QtAutogenRerun/CMakeLists.txt
new file mode 100644
index 000000000..e72c1912e
--- /dev/null
+++ b/Tests/QtAutogenRerun/CMakeLists.txt
@@ -0,0 +1,52 @@
+cmake_minimum_required(VERSION 3.9)
+cmake_policy(SET CMP0071 NEW)
+project(QtAutogenRerun)
+
+# Tell find_package(Qt5) where to find Qt.
+if(QT_QMAKE_EXECUTABLE)
+ get_filename_component(Qt_BIN_DIR "${QT_QMAKE_EXECUTABLE}" PATH)
+ get_filename_component(Qt_PREFIX_DIR "${Qt_BIN_DIR}" PATH)
+ set(CMAKE_PREFIX_PATH ${Qt_PREFIX_DIR})
+endif()
+
+if (QT_TEST_VERSION STREQUAL 4)
+ find_package(Qt4 REQUIRED)
+
+ # Include this directory before using the UseQt4 file.
+ add_subdirectory(defines_test)
+
+ include(UseQt4)
+
+ set(QT_QTCORE_TARGET Qt4::QtCore)
+
+else()
+ if (NOT QT_TEST_VERSION STREQUAL 5)
+ message(SEND_ERROR "Invalid Qt version specified.")
+ endif()
+ find_package(Qt5Widgets REQUIRED)
+
+ set(QT_QTCORE_TARGET Qt5::Core)
+
+ include_directories(${Qt5Widgets_INCLUDE_DIRS})
+ set(QT_LIBRARIES Qt5::Widgets)
+
+ if(Qt5_POSITION_INDEPENDENT_CODE AND CMAKE_CXX_COMPILE_OPTIONS_PIC)
+ add_definitions(${CMAKE_CXX_COMPILE_OPTIONS_PIC})
+ endif()
+
+endif()
+
+# Dummy executable to generate clean target
+add_executable(dummy dummy.cpp)
+
+# -- Test
+include("mocRerun.cmake")
+
+# -- Test
+# Tests Q_PLUGIN_METADATA json file change detection
+if (NOT QT_TEST_VERSION STREQUAL 4)
+ include("mocPlugin.cmake")
+endif()
+
+# -- Test
+include("rccDepends.cmake")
diff --git a/Tests/QtAutogenRerun/defines_test/CMakeLists.txt b/Tests/QtAutogenRerun/defines_test/CMakeLists.txt
new file mode 100644
index 000000000..9ee9a228a
--- /dev/null
+++ b/Tests/QtAutogenRerun/defines_test/CMakeLists.txt
@@ -0,0 +1,4 @@
+
+add_executable(defines_test defines_test.cpp)
+set_target_properties(defines_test PROPERTIES AUTOMOC TRUE)
+target_link_libraries(defines_test Qt4::QtGui)
diff --git a/Tests/QtAutogenRerun/defines_test/defines_test.cpp b/Tests/QtAutogenRerun/defines_test/defines_test.cpp
new file mode 100644
index 000000000..cf4e9cb5b
--- /dev/null
+++ b/Tests/QtAutogenRerun/defines_test/defines_test.cpp
@@ -0,0 +1,38 @@
+
+#include <QObject>
+
+#ifdef QT_GUI_LIB
+#include <QTextDocument>
+
+class SomeDocument : public QTextDocument
+{
+ Q_OBJECT
+
+Q_SIGNALS:
+ void someSig();
+};
+#endif
+
+#ifdef QT_CORE_LIB
+class SomeObject : public QObject
+{
+ Q_OBJECT
+
+Q_SIGNALS:
+ void someSig();
+};
+#endif
+
+int main(int argc, char** argv)
+{
+#ifdef QT_CORE_LIB
+ QMetaObject sosmo = SomeObject::staticMetaObject;
+#endif
+#ifdef QT_GUI_LIB
+ QMetaObject sdsmo = SomeDocument::staticMetaObject;
+#endif
+
+ return 0;
+}
+
+#include "defines_test.moc"
diff --git a/Tests/QtAutogenRerun/dummy.cpp b/Tests/QtAutogenRerun/dummy.cpp
new file mode 100644
index 000000000..4837a76b8
--- /dev/null
+++ b/Tests/QtAutogenRerun/dummy.cpp
@@ -0,0 +1,5 @@
+
+int main(int argv, char** args)
+{
+ return 0;
+}
diff --git a/Tests/QtAutogenRerun/mocPlugin.cmake b/Tests/QtAutogenRerun/mocPlugin.cmake
new file mode 100644
index 000000000..7ad5ccb18
--- /dev/null
+++ b/Tests/QtAutogenRerun/mocPlugin.cmake
@@ -0,0 +1,96 @@
+
+# Utility variables
+set(timeformat "%Y%j%H%M%S")
+set(mocPlugSrcDir "${CMAKE_CURRENT_SOURCE_DIR}/mocPlugin")
+set(mocPlugBinDir "${CMAKE_CURRENT_BINARY_DIR}/mocPlugin")
+
+# Initial buid
+try_compile(MOC_PLUGIN
+ "${mocPlugBinDir}"
+ "${mocPlugSrcDir}"
+ mocPlugin
+ CMAKE_FLAGS "-DQT_TEST_VERSION=${QT_TEST_VERSION}"
+ "-DCMAKE_PREFIX_PATH=${Qt_PREFIX_DIR}"
+ OUTPUT_VARIABLE output
+)
+if (NOT MOC_PLUGIN)
+ message(SEND_ERROR "Initial build of mocPlugin failed. Output: ${output}")
+endif()
+
+find_library(plAFile "PlugA" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH)
+find_library(plBFile "PlugB" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH)
+find_library(plCFile "PlugC" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH)
+find_library(plDFile "PlugD" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH)
+find_library(plEFile "PlugE" PATHS "${mocPlugBinDir}/Debug" "${mocPlugBinDir}" NO_DEFAULT_PATH)
+
+# - Ensure that the timestamp will change.
+# - Change the json files referenced by Q_PLUGIN_METADATA
+# - Rebuild
+file(TIMESTAMP "${plAFile}" plABefore "${timeformat}")
+file(TIMESTAMP "${plBFile}" plBBefore "${timeformat}")
+file(TIMESTAMP "${plCFile}" plCBefore "${timeformat}")
+file(TIMESTAMP "${plDFile}" plDBefore "${timeformat}")
+file(TIMESTAMP "${plEFile}" plEBefore "${timeformat}")
+
+execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
+configure_file("${mocPlugSrcDir}/jsonIn/StyleD.json" "${mocPlugBinDir}/jsonFiles/StyleC.json")
+configure_file("${mocPlugSrcDir}/jsonIn/StyleE.json" "${mocPlugBinDir}/jsonFiles/sub/StyleD.json")
+configure_file("${mocPlugSrcDir}/jsonIn/StyleC.json" "${mocPlugBinDir}/jsonFiles/StyleE.json")
+execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocPlugBinDir}")
+
+file(TIMESTAMP "${plAFile}" plAAfter "${timeformat}")
+file(TIMESTAMP "${plBFile}" plBAfter "${timeformat}")
+file(TIMESTAMP "${plCFile}" plCAfter "${timeformat}")
+file(TIMESTAMP "${plDFile}" plDAfter "${timeformat}")
+file(TIMESTAMP "${plEFile}" plEAfter "${timeformat}")
+
+if (plAAfter GREATER plABefore)
+ message(SEND_ERROR "file (${plAFile}) should not have changed!")
+endif()
+if (plBAfter GREATER plBBefore)
+ message(SEND_ERROR "file (${plBFile}) should not have changed!")
+endif()
+if (NOT plCAfter GREATER plCBefore)
+ message(SEND_ERROR "file (${plCFile}) should have changed!")
+endif()
+if (NOT plDAfter GREATER plDBefore)
+ message(SEND_ERROR "file (${plDFile}) should have changed!")
+endif()
+if (NOT plEAfter GREATER plEBefore)
+ # There's a bug in Ninja on Windows
+ # https://gitlab.kitware.com/cmake/cmake/issues/16776
+ if(NOT ("${CMAKE_GENERATOR}" MATCHES "Ninja"))
+ message(SEND_ERROR "file (${plEFile}) should have changed!")
+ endif()
+endif()
+
+# - Ensure that the timestamp will change.
+# - Change the json files referenced by A_CUSTOM_MACRO
+# - Rebuild
+file(TIMESTAMP "${plCFile}" plCBefore "${timeformat}")
+file(TIMESTAMP "${plDFile}" plDBefore "${timeformat}")
+file(TIMESTAMP "${plEFile}" plEBefore "${timeformat}")
+
+execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
+configure_file("${mocPlugSrcDir}/jsonIn/StyleE.json" "${mocPlugBinDir}/jsonFiles/StyleC_Custom.json")
+configure_file("${mocPlugSrcDir}/jsonIn/StyleC.json" "${mocPlugBinDir}/jsonFiles/sub/StyleD_Custom.json")
+configure_file("${mocPlugSrcDir}/jsonIn/StyleD.json" "${mocPlugBinDir}/jsonFiles/StyleE_Custom.json")
+execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocPlugBinDir}")
+
+file(TIMESTAMP "${plCFile}" plCAfter "${timeformat}")
+file(TIMESTAMP "${plDFile}" plDAfter "${timeformat}")
+file(TIMESTAMP "${plEFile}" plEAfter "${timeformat}")
+
+if (NOT plCAfter GREATER plCBefore)
+ message(SEND_ERROR "file (${plCFile}) should have changed!")
+endif()
+if (NOT plDAfter GREATER plDBefore)
+ message(SEND_ERROR "file (${plDFile}) should have changed!")
+endif()
+if (NOT plEAfter GREATER plEBefore)
+ # There's a bug in Ninja on Windows
+ # https://gitlab.kitware.com/cmake/cmake/issues/16776
+ if(NOT ("${CMAKE_GENERATOR}" MATCHES "Ninja"))
+ message(SEND_ERROR "file (${plEFile}) should have changed!")
+ endif()
+endif()
diff --git a/Tests/QtAutogen/mocPlugin/CMakeLists.txt b/Tests/QtAutogenRerun/mocPlugin/CMakeLists.txt
index f80aa2934..b7cc5e9ff 100644
--- a/Tests/QtAutogen/mocPlugin/CMakeLists.txt
+++ b/Tests/QtAutogenRerun/mocPlugin/CMakeLists.txt
@@ -1,4 +1,4 @@
-cmake_minimum_required(VERSION 3.8)
+cmake_minimum_required(VERSION 3.9)
project(mocPlugin CXX)
set(CMAKE_AUTOMOC_DEPEND_FILTERS
@@ -16,9 +16,11 @@ if(Qt5_POSITION_INDEPENDENT_CODE AND CMAKE_CXX_COMPILE_OPTIONS_PIC)
endif()
configure_file(jsonIn/StyleC.json jsonFiles/StyleC.json)
-configure_file(jsonIn/StyleD.json jsonFiles/sub/StyleD.json)
configure_file(jsonIn/StyleC.json jsonFiles/StyleC_Custom.json)
+configure_file(jsonIn/StyleD.json jsonFiles/sub/StyleD.json)
configure_file(jsonIn/StyleD.json jsonFiles/sub/StyleD_Custom.json)
+configure_file(jsonIn/StyleE.json jsonFiles/StyleE.json)
+configure_file(jsonIn/StyleE.json jsonFiles/StyleE_Custom.json)
# Enable automoc
set(CMAKE_AUTOMOC TRUE)
diff --git a/Tests/QtAutogen/mocPlugin/StyleA.cpp b/Tests/QtAutogenRerun/mocPlugin/StyleA.cpp
index b5e87533c..b5e87533c 100644
--- a/Tests/QtAutogen/mocPlugin/StyleA.cpp
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleA.cpp
diff --git a/Tests/QtAutogen/mocPlugin/StyleA.hpp b/Tests/QtAutogenRerun/mocPlugin/StyleA.hpp
index 1b6154d16..35158a4b0 100644
--- a/Tests/QtAutogen/mocPlugin/StyleA.hpp
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleA.hpp
@@ -1,13 +1,13 @@
#ifndef STYLEA_HPP
#define STYLEA_HPP
-#include "StyleCommon.hpp"
+#include "UtilityMacros.hpp"
#include <QStylePlugin>
class StyleA : public QStylePlugin
{
Q_OBJECT
- // Json file in local directory
+ // Json file in source local directory
Q_PLUGIN_METADATA(IID "org.styles.A" FILE "StyleA.json")
A_CUSTOM_MACRO(SomeArg, "StyleA_Custom.json", AnotherArg)
public:
diff --git a/Tests/QtAutogen/mocPlugin/StyleA.json b/Tests/QtAutogenRerun/mocPlugin/StyleA.json
index cc3395369..cc3395369 100644
--- a/Tests/QtAutogen/mocPlugin/StyleA.json
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleA.json
diff --git a/Tests/QtAutogen/mocPlugin/StyleA_Custom.json b/Tests/QtAutogenRerun/mocPlugin/StyleA_Custom.json
index cc3395369..cc3395369 100644
--- a/Tests/QtAutogen/mocPlugin/StyleA_Custom.json
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleA_Custom.json
diff --git a/Tests/QtAutogen/mocPlugin/StyleB.cpp b/Tests/QtAutogenRerun/mocPlugin/StyleB.cpp
index 17d440035..17d440035 100644
--- a/Tests/QtAutogen/mocPlugin/StyleB.cpp
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleB.cpp
diff --git a/Tests/QtAutogen/mocPlugin/StyleB.hpp b/Tests/QtAutogenRerun/mocPlugin/StyleB.hpp
index 163c9b20a..15b79c598 100644
--- a/Tests/QtAutogen/mocPlugin/StyleB.hpp
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleB.hpp
@@ -1,13 +1,13 @@
#ifndef STYLEB_HPP
#define STYLEB_HPP
-#include "StyleCommon.hpp"
+#include "UtilityMacros.hpp"
#include <QStylePlugin>
class StyleB : public QStylePlugin
{
Q_OBJECT
- // Json file in local subdirectory
+ // Json file in source local subdirectory
Q_PLUGIN_METADATA(IID "org.styles.B" FILE "jsonIn/StyleB.json")
A_CUSTOM_MACRO(SomeArg, "jsonIn/StyleB_Custom.json", AnotherArg)
public:
diff --git a/Tests/QtAutogen/mocPlugin/StyleC.cpp b/Tests/QtAutogenRerun/mocPlugin/StyleC.cpp
index 37e756487..37e756487 100644
--- a/Tests/QtAutogen/mocPlugin/StyleC.cpp
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleC.cpp
diff --git a/Tests/QtAutogen/mocPlugin/StyleC.hpp b/Tests/QtAutogenRerun/mocPlugin/StyleC.hpp
index 52a887acf..b0a41150b 100644
--- a/Tests/QtAutogen/mocPlugin/StyleC.hpp
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleC.hpp
@@ -1,7 +1,7 @@
#ifndef STYLEC_HPP
#define STYLEC_HPP
-#include "StyleCommon.hpp"
+#include "UtilityMacros.hpp"
#include <QStylePlugin>
class StyleC : public QStylePlugin
diff --git a/Tests/QtAutogen/mocPlugin/StyleD.cpp b/Tests/QtAutogenRerun/mocPlugin/StyleD.cpp
index 7e4b121fc..7e4b121fc 100644
--- a/Tests/QtAutogen/mocPlugin/StyleD.cpp
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleD.cpp
diff --git a/Tests/QtAutogen/mocPlugin/StyleD.hpp b/Tests/QtAutogenRerun/mocPlugin/StyleD.hpp
index df8a4399d..9696aaa26 100644
--- a/Tests/QtAutogen/mocPlugin/StyleD.hpp
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleD.hpp
@@ -1,7 +1,7 @@
#ifndef STYLED_HPP
#define STYLED_HPP
-#include "StyleCommon.hpp"
+#include "UtilityMacros.hpp"
#include <QStylePlugin>
class StyleD : public QStylePlugin
diff --git a/Tests/QtAutogen/mocPlugin/StyleE.cpp b/Tests/QtAutogenRerun/mocPlugin/StyleE.cpp
index 8fc9a7f68..344831969 100644
--- a/Tests/QtAutogen/mocPlugin/StyleE.cpp
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleE.cpp
@@ -4,3 +4,6 @@ QStyle* StyleE::create(const QString& key)
{
return 0;
}
+
+// AUTOMOC the StyleEInclude.hpp header
+#include "moc_StyleEInclude.cpp"
diff --git a/Tests/QtAutogenRerun/mocPlugin/StyleE.hpp b/Tests/QtAutogenRerun/mocPlugin/StyleE.hpp
new file mode 100644
index 000000000..a0690343d
--- /dev/null
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleE.hpp
@@ -0,0 +1,10 @@
+#ifndef STYLEE_HPP
+#define STYLEE_HPP
+
+// The included file is not in the sources list and won't be detected by
+// AUTOMOC source file with the same base name.
+// It is registered to AUTOMOCed via a moc_<NAME>.cpp include in StyleE.cpp
+// though.
+#include "StyleEInclude.hpp"
+
+#endif
diff --git a/Tests/QtAutogenRerun/mocPlugin/StyleEInclude.hpp b/Tests/QtAutogenRerun/mocPlugin/StyleEInclude.hpp
new file mode 100644
index 000000000..f9734db4d
--- /dev/null
+++ b/Tests/QtAutogenRerun/mocPlugin/StyleEInclude.hpp
@@ -0,0 +1,17 @@
+#ifndef STYLEE_INCLUDE_HPP
+#define STYLEE_INCLUDE_HPP
+
+#include "UtilityMacros.hpp"
+#include <QStylePlugin>
+
+class StyleE : public QStylePlugin
+{
+ Q_OBJECT
+ // Json files in global root directory
+ Q_PLUGIN_METADATA(IID "org.styles.E" FILE "StyleE.json")
+ A_CUSTOM_MACRO(SomeArg, "StyleE_Custom.json", AnotherArg)
+public:
+ QStyle* create(const QString& key);
+};
+
+#endif
diff --git a/Tests/QtAutogen/mocPlugin/StyleCommon.hpp b/Tests/QtAutogenRerun/mocPlugin/UtilityMacros.hpp
index f1a7ec60d..53a4284ee 100644
--- a/Tests/QtAutogen/mocPlugin/StyleCommon.hpp
+++ b/Tests/QtAutogenRerun/mocPlugin/UtilityMacros.hpp
@@ -1,5 +1,5 @@
-#ifndef STYLECOMMON_HPP
-#define STYLECOMMON_HPP
+#ifndef UTILITYMACROS_HPP
+#define UTILITYMACROS_HPP
// Empty test macro definition
#define A_CUSTOM_MACRO(name, jsonFile, pluginRegistrations)
diff --git a/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleB.json b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleB.json
new file mode 100644
index 000000000..cd155dc0e
--- /dev/null
+++ b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleB.json
@@ -0,0 +1 @@
+{ "Keys": [ "Red", "Green" ] }
diff --git a/Tests/QtAutogen/mocPlugin/jsonIn/StyleB_Custom.json b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleB_Custom.json
index 129cac41f..129cac41f 100644
--- a/Tests/QtAutogen/mocPlugin/jsonIn/StyleB_Custom.json
+++ b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleB_Custom.json
diff --git a/Tests/QtAutogen/mocPlugin/jsonIn/StyleC.json b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleC.json
index 119aaa4b7..119aaa4b7 100644
--- a/Tests/QtAutogen/mocPlugin/jsonIn/StyleC.json
+++ b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleC.json
diff --git a/Tests/QtAutogen/mocPlugin/jsonIn/StyleD.json b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleD.json
index 732c547ab..732c547ab 100644
--- a/Tests/QtAutogen/mocPlugin/jsonIn/StyleD.json
+++ b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleD.json
diff --git a/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleE.json b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleE.json
new file mode 100644
index 000000000..5412c94f6
--- /dev/null
+++ b/Tests/QtAutogenRerun/mocPlugin/jsonIn/StyleE.json
@@ -0,0 +1 @@
+{ "Keys": [ "Floor", "Ceiling" ] }
diff --git a/Tests/QtAutogen/mocPlugin/main.cpp b/Tests/QtAutogenRerun/mocPlugin/main.cpp
index 3ba2ddc6d..3ba2ddc6d 100644
--- a/Tests/QtAutogen/mocPlugin/main.cpp
+++ b/Tests/QtAutogenRerun/mocPlugin/main.cpp
diff --git a/Tests/QtAutogenRerun/mocRerun.cmake b/Tests/QtAutogenRerun/mocRerun.cmake
new file mode 100644
index 000000000..a92912b3c
--- /dev/null
+++ b/Tests/QtAutogenRerun/mocRerun.cmake
@@ -0,0 +1,60 @@
+
+set(timeformat "%Y%j%H%M%S")
+set(mocRerunSrcDir "${CMAKE_CURRENT_SOURCE_DIR}/mocRerun")
+set(mocRerunBinDir "${CMAKE_CURRENT_BINARY_DIR}/mocRerun")
+
+# Initial build
+configure_file("${mocRerunSrcDir}/test1a.h.in" "${mocRerunBinDir}/test1.h" COPYONLY)
+try_compile(MOC_RERUN
+ "${mocRerunBinDir}"
+ "${mocRerunSrcDir}"
+ mocRerun
+ CMAKE_FLAGS "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}"
+ "-DQT_TEST_VERSION=${QT_TEST_VERSION}"
+ "-DCMAKE_PREFIX_PATH=${Qt_PREFIX_DIR}"
+ OUTPUT_VARIABLE output
+)
+if (NOT MOC_RERUN)
+ message(SEND_ERROR "Initial build of mocRerun failed. Output: ${output}")
+endif()
+# Get name of the output binary
+file(STRINGS "${mocRerunBinDir}/mocRerun.txt" mocRerunList ENCODING UTF-8)
+list(GET mocRerunList 0 mocRerunBin)
+
+message("Changing the header content for a MOC rerun")
+# - Acquire binary timestamps before the build
+file(TIMESTAMP "${mocRerunBin}" timeBefore "${timeformat}")
+# - Ensure that the timestamp will change
+# - Change header file content and rebuild
+# - Rebuild
+execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
+configure_file("${mocRerunSrcDir}/test1b.h.in" "${mocRerunBinDir}/test1.h" COPYONLY)
+execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocRerunBinDir}" RESULT_VARIABLE result )
+if (result)
+ message(SEND_ERROR "Second build of mocRerun failed.")
+endif()
+# - Acquire binary timestamps after the build
+file(TIMESTAMP "${mocRerunBin}" timeAfter "${timeformat}")
+# - Test if timestamps changed
+if (NOT timeAfter GREATER timeBefore)
+ message(SEND_ERROR "File (${mocRerunBin}) should have changed!")
+endif()
+
+
+message("Changing nothing for a MOC rerun")
+# - Acquire binary timestamps before the build
+file(TIMESTAMP "${mocRerunBin}" timeBefore "${timeformat}")
+# - Ensure that the timestamp would change
+# - Change nothing
+# - Rebuild
+execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
+execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${mocRerunBinDir}" RESULT_VARIABLE result )
+if (result)
+ message(SEND_ERROR "Third build of mocRerun failed.")
+endif()
+# - Acquire binary timestamps after the build
+file(TIMESTAMP "${mocRerunBin}" timeAfter "${timeformat}")
+# - Test if timestamps changed
+if (timeAfter GREATER timeBefore)
+ message(SEND_ERROR "File (${mocRerunBin}) should not have changed!")
+endif()
diff --git a/Tests/QtAutogen/mocRerun/CMakeLists.txt b/Tests/QtAutogenRerun/mocRerun/CMakeLists.txt
index 14b077b38..bafd9cf48 100644
--- a/Tests/QtAutogen/mocRerun/CMakeLists.txt
+++ b/Tests/QtAutogenRerun/mocRerun/CMakeLists.txt
@@ -1,4 +1,5 @@
-cmake_minimum_required(VERSION 3.7)
+cmake_minimum_required(VERSION 3.9)
+cmake_policy(SET CMP0071 NEW)
project(mocRerun CXX)
if (QT_TEST_VERSION STREQUAL 4)
@@ -18,18 +19,15 @@ set(CMAKE_AUTORCC ON)
# Generated source file
add_custom_command(OUTPUT main.cpp
- COMMAND ${CMAKE_COMMAND} -E sleep 2
- COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp.in ${CMAKE_CURRENT_BINARY_DIR}/main.cpp
- )
+ COMMAND ${CMAKE_COMMAND} -E sleep 2
+ COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp.in ${CMAKE_CURRENT_BINARY_DIR}/main.cpp)
add_executable(mocRerun
${CMAKE_CURRENT_BINARY_DIR}/test1.h
${CMAKE_CURRENT_BINARY_DIR}/main.cpp
- res1.qrc
- )
-set_property(TARGET mocRerun PROPERTY __UNDOCUMENTED_AUTOGEN_GENERATED_FILES 1)
+ res1.qrc)
target_include_directories(mocRerun PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
target_link_libraries(mocRerun ${QT_CORE_TARGET})
# Write target name to text file
add_custom_command(TARGET mocRerun POST_BUILD COMMAND
- ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:mocRerun>" > target1.txt)
+ ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:mocRerun>" > mocRerun.txt)
diff --git a/Tests/QtAutogen/mocRerun/input.txt b/Tests/QtAutogenRerun/mocRerun/input.txt
index da627624b..da627624b 100644
--- a/Tests/QtAutogen/mocRerun/input.txt
+++ b/Tests/QtAutogenRerun/mocRerun/input.txt
diff --git a/Tests/QtAutogen/mocRerun/main.cpp.in b/Tests/QtAutogenRerun/mocRerun/main.cpp.in
index b37ff61e2..b37ff61e2 100644
--- a/Tests/QtAutogen/mocRerun/main.cpp.in
+++ b/Tests/QtAutogenRerun/mocRerun/main.cpp.in
diff --git a/Tests/QtAutogen/mocRerun/res1.qrc b/Tests/QtAutogenRerun/mocRerun/res1.qrc
index fb804b5ec..fb804b5ec 100644
--- a/Tests/QtAutogen/mocRerun/res1.qrc
+++ b/Tests/QtAutogenRerun/mocRerun/res1.qrc
diff --git a/Tests/QtAutogen/mocRerun/test1a.h.in b/Tests/QtAutogenRerun/mocRerun/test1a.h.in
index a335046ba..a335046ba 100644
--- a/Tests/QtAutogen/mocRerun/test1a.h.in
+++ b/Tests/QtAutogenRerun/mocRerun/test1a.h.in
diff --git a/Tests/QtAutogen/mocRerun/test1b.h.in b/Tests/QtAutogenRerun/mocRerun/test1b.h.in
index 6128eeba1..6128eeba1 100644
--- a/Tests/QtAutogen/mocRerun/test1b.h.in
+++ b/Tests/QtAutogenRerun/mocRerun/test1b.h.in
diff --git a/Tests/QtAutogenRerun/rccDepends.cmake b/Tests/QtAutogenRerun/rccDepends.cmake
new file mode 100644
index 000000000..68e148251
--- /dev/null
+++ b/Tests/QtAutogenRerun/rccDepends.cmake
@@ -0,0 +1,131 @@
+# When a .qrc or a file listed in a .qrc file changes,
+# the target must be rebuilt
+set(timeformat "%Y%j%H%M%S")
+set(rccDepSD "${CMAKE_CURRENT_SOURCE_DIR}/rccDepends")
+set(rccDepBD "${CMAKE_CURRENT_BINARY_DIR}/rccDepends")
+
+# Initial build
+configure_file(${rccDepSD}/resPlainA.qrc.in ${rccDepBD}/resPlain.qrc COPYONLY)
+configure_file(${rccDepSD}/resGenA.qrc.in ${rccDepBD}/resGen.qrc.in COPYONLY)
+try_compile(RCC_DEPENDS
+ "${rccDepBD}"
+ "${rccDepSD}"
+ rccDepends
+ CMAKE_FLAGS "-DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}"
+ "-DQT_TEST_VERSION=${QT_TEST_VERSION}"
+ "-DCMAKE_PREFIX_PATH=${Qt_PREFIX_DIR}"
+ OUTPUT_VARIABLE output
+)
+if (NOT RCC_DEPENDS)
+ message(SEND_ERROR "Initial build of rccDepends failed. Output: ${output}")
+endif()
+
+# Get name of the output binaries
+file(STRINGS "${rccDepBD}/targetPlain.txt" targetListPlain ENCODING UTF-8)
+file(STRINGS "${rccDepBD}/targetGen.txt" targetListGen ENCODING UTF-8)
+list(GET targetListPlain 0 rccDepBinPlain)
+list(GET targetListGen 0 rccDepBinGen)
+message("Target that uses a plain .qrc file is:\n ${rccDepBinPlain}")
+message("Target that uses a GENERATED .qrc file is:\n ${rccDepBinGen}")
+
+
+message("Changing a resource files listed in the .qrc file")
+# - Acquire binary timestamps before the build
+file(TIMESTAMP "${rccDepBinPlain}" rdPlainBefore "${timeformat}")
+file(TIMESTAMP "${rccDepBinGen}" rdGenBefore "${timeformat}")
+# - Ensure that the timestamp will change
+# - Change a resource files listed in the .qrc file
+# - Rebuild
+execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
+execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${rccDepBD}/resPlain/input.txt")
+execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${rccDepBD}/resGen/input.txt")
+execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${rccDepBD}" RESULT_VARIABLE result)
+if (result)
+ message(SEND_ERROR "Second build of rccDepends failed.")
+endif()
+# - Acquire binary timestamps after the build
+file(TIMESTAMP "${rccDepBinPlain}" rdPlainAfter "${timeformat}")
+file(TIMESTAMP "${rccDepBinGen}" rdGenAfter "${timeformat}")
+# - Test if timestamps changed
+if (NOT rdPlainAfter GREATER rdPlainBefore)
+ message(SEND_ERROR "Plain .qrc binary ${rccDepBinPlain}) should have changed!")
+endif()
+if (NOT rdGenAfter GREATER rdGenBefore)
+ message(SEND_ERROR "GENERATED .qrc binary ${rccDepBinGen} should have changed!")
+endif()
+
+
+message("Changing a the .qrc file")
+# - Acquire binary timestamps before the build
+file(TIMESTAMP "${rccDepBinPlain}" rdPlainBefore "${timeformat}")
+file(TIMESTAMP "${rccDepBinGen}" rdGenBefore "${timeformat}")
+# - Ensure that the timestamp will change
+# - Change the .qrc file
+# - Rebuild
+execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
+configure_file(${rccDepSD}/resPlainB.qrc.in ${rccDepBD}/resPlain.qrc COPYONLY)
+configure_file(${rccDepSD}/resGenB.qrc.in ${rccDepBD}/resGen.qrc.in COPYONLY)
+execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${rccDepBD}" RESULT_VARIABLE result)
+if (result)
+ message(SEND_ERROR "Third build of rccDepends failed.")
+endif()
+# - Acquire binary timestamps after the build
+file(TIMESTAMP "${rccDepBinPlain}" rdPlainAfter "${timeformat}")
+file(TIMESTAMP "${rccDepBinGen}" rdGenAfter "${timeformat}")
+# - Test if timestamps changed
+if (NOT rdPlainAfter GREATER rdPlainBefore)
+ message(SEND_ERROR "Plain .qrc binary ${rccDepBinPlain}) should have changed!")
+endif()
+if (NOT rdGenAfter GREATER rdGenBefore)
+ message(SEND_ERROR "GENERATED .qrc binary ${rccDepBinGen} should have changed!")
+endif()
+
+
+message("Changing a newly added resource files listed in the .qrc file")
+# - Acquire binary timestamps before the build
+file(TIMESTAMP "${rccDepBinPlain}" rdPlainBefore "${timeformat}")
+file(TIMESTAMP "${rccDepBinGen}" rdGenBefore "${timeformat}")
+# - Ensure that the timestamp will change
+# - Change a newly added resource files listed in the .qrc file
+# - Rebuild
+execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
+execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${rccDepBD}/resPlain/inputAdded.txt")
+execute_process(COMMAND "${CMAKE_COMMAND}" -E touch "${rccDepBD}/resGen/inputAdded.txt")
+execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${rccDepBD}" RESULT_VARIABLE result)
+if (result)
+ message(SEND_ERROR "Fourth build of rccDepends failed.")
+endif()
+# - Acquire binary timestamps after the build
+file(TIMESTAMP "${rccDepBinPlain}" rdPlainAfter "${timeformat}")
+file(TIMESTAMP "${rccDepBinGen}" rdGenAfter "${timeformat}")
+# - Test if timestamps changed
+if (NOT rdPlainAfter GREATER rdPlainBefore)
+ message(SEND_ERROR "Plain .qrc binary ${rccDepBinPlain}) should have changed!")
+endif()
+if (NOT rdGenAfter GREATER rdGenBefore)
+ message(SEND_ERROR "GENERATED .qrc binary ${rccDepBinGen} should have changed!")
+endif()
+
+
+message("Changing nothing in the .qrc file")
+# - Acquire binary timestamps before the build
+file(TIMESTAMP "${rccDepBinPlain}" rdPlainBefore "${timeformat}")
+file(TIMESTAMP "${rccDepBinGen}" rdGenBefore "${timeformat}")
+# - Ensure that the timestamp will change
+# - Change nothing
+# - Rebuild
+execute_process(COMMAND "${CMAKE_COMMAND}" -E sleep 1)
+execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${rccDepBD}" RESULT_VARIABLE result)
+if (result)
+ message(SEND_ERROR "Fifth build of rccDepends failed.")
+endif()
+# - Acquire binary timestamps after the build
+file(TIMESTAMP "${rccDepBinPlain}" rdPlainAfter "${timeformat}")
+file(TIMESTAMP "${rccDepBinGen}" rdGenAfter "${timeformat}")
+# - Test if timestamps changed
+if (rdPlainAfter GREATER rdPlainBefore)
+ message(SEND_ERROR "Plain .qrc binary ${rccDepBinPlain}) should NOT have changed!")
+endif()
+if (rdGenAfter GREATER rdGenBefore)
+ message(SEND_ERROR "GENERATED .qrc binary ${rccDepBinGen} should NOT have changed!")
+endif()
diff --git a/Tests/QtAutogenRerun/rccDepends/CMakeLists.txt b/Tests/QtAutogenRerun/rccDepends/CMakeLists.txt
new file mode 100644
index 000000000..291592e7d
--- /dev/null
+++ b/Tests/QtAutogenRerun/rccDepends/CMakeLists.txt
@@ -0,0 +1,41 @@
+cmake_minimum_required(VERSION 3.9)
+project(rccDepends CXX)
+
+if (QT_TEST_VERSION STREQUAL 4)
+ find_package(Qt4 REQUIRED)
+ set(QT_CORE_TARGET Qt4::QtCore)
+else()
+ if (NOT QT_TEST_VERSION STREQUAL 5)
+ message(SEND_ERROR "Invalid Qt version specified.")
+ endif()
+
+ find_package(Qt5Core REQUIRED)
+ set(QT_CORE_TARGET Qt5::Core)
+endif()
+
+# Enable AUTORCC for all targets
+set(CMAKE_AUTORCC ON)
+
+# Initial resource files setup
+configure_file(resPlain/input.txt.in resPlain/input.txt COPYONLY)
+configure_file(resPlain/input.txt.in resPlain/inputAdded.txt COPYONLY)
+configure_file(resGen/input.txt.in resGen/input.txt COPYONLY)
+configure_file(resGen/input.txt.in resGen/inputAdded.txt COPYONLY)
+
+# Generated qrc file with dependency
+add_custom_command(OUTPUT resGen.qrc
+ DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/resGen.qrc.in
+ COMMAND ${CMAKE_COMMAND} -E sleep 2
+ COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/resGen.qrc.in ${CMAKE_CURRENT_BINARY_DIR}/resGen.qrc)
+
+# Target that uses a plain .qrc file
+add_executable(rccDependsPlain main.cpp ${CMAKE_CURRENT_BINARY_DIR}/resPlain.qrc)
+target_link_libraries(rccDependsPlain ${QT_CORE_TARGET})
+add_custom_command(TARGET rccDependsPlain POST_BUILD COMMAND
+ ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:rccDependsPlain>" > targetPlain.txt)
+
+# Target that uses a GENERATED .qrc file
+add_executable(rccDependsGen main.cpp ${CMAKE_CURRENT_BINARY_DIR}/resGen.qrc )
+target_link_libraries(rccDependsGen ${QT_CORE_TARGET})
+add_custom_command(TARGET rccDependsGen POST_BUILD COMMAND
+ ${CMAKE_COMMAND} -E echo "$<TARGET_FILE:rccDependsGen>" > targetGen.txt)
diff --git a/Tests/QtAutogen/rccDepends/main.cpp b/Tests/QtAutogenRerun/rccDepends/main.cpp
index 766b7751b..766b7751b 100644
--- a/Tests/QtAutogen/rccDepends/main.cpp
+++ b/Tests/QtAutogenRerun/rccDepends/main.cpp
diff --git a/Tests/QtAutogenRerun/rccDepends/resGen/input.txt.in b/Tests/QtAutogenRerun/rccDepends/resGen/input.txt.in
new file mode 100644
index 000000000..4f24589b0
--- /dev/null
+++ b/Tests/QtAutogenRerun/rccDepends/resGen/input.txt.in
@@ -0,0 +1 @@
+Generated resource input.
diff --git a/Tests/QtAutogenRerun/rccDepends/resGen/inputAdded.txt.in b/Tests/QtAutogenRerun/rccDepends/resGen/inputAdded.txt.in
new file mode 100644
index 000000000..4f24589b0
--- /dev/null
+++ b/Tests/QtAutogenRerun/rccDepends/resGen/inputAdded.txt.in
@@ -0,0 +1 @@
+Generated resource input.
diff --git a/Tests/QtAutogenRerun/rccDepends/resGenA.qrc.in b/Tests/QtAutogenRerun/rccDepends/resGenA.qrc.in
new file mode 100644
index 000000000..c131a3460
--- /dev/null
+++ b/Tests/QtAutogenRerun/rccDepends/resGenA.qrc.in
@@ -0,0 +1,5 @@
+<RCC>
+ <qresource prefix="/TextsGenerated">
+ <file>resGen/input.txt</file>
+ </qresource>
+</RCC>
diff --git a/Tests/QtAutogenRerun/rccDepends/resGenB.qrc.in b/Tests/QtAutogenRerun/rccDepends/resGenB.qrc.in
new file mode 100644
index 000000000..8c7e64311
--- /dev/null
+++ b/Tests/QtAutogenRerun/rccDepends/resGenB.qrc.in
@@ -0,0 +1,6 @@
+<RCC>
+ <qresource prefix="/TextsGenerated">
+ <file>resGen/input.txt</file>
+ <file alias="Added">resGen/inputAdded.txt</file>
+ </qresource>
+</RCC>
diff --git a/Tests/QtAutogenRerun/rccDepends/resPlain/input.txt.in b/Tests/QtAutogenRerun/rccDepends/resPlain/input.txt.in
new file mode 100644
index 000000000..a5e407a17
--- /dev/null
+++ b/Tests/QtAutogenRerun/rccDepends/resPlain/input.txt.in
@@ -0,0 +1 @@
+Plaint resource input.
diff --git a/Tests/QtAutogenRerun/rccDepends/resPlain/inputAdded.txt.in b/Tests/QtAutogenRerun/rccDepends/resPlain/inputAdded.txt.in
new file mode 100644
index 000000000..a5e407a17
--- /dev/null
+++ b/Tests/QtAutogenRerun/rccDepends/resPlain/inputAdded.txt.in
@@ -0,0 +1 @@
+Plaint resource input.
diff --git a/Tests/QtAutogenRerun/rccDepends/resPlainA.qrc.in b/Tests/QtAutogenRerun/rccDepends/resPlainA.qrc.in
new file mode 100644
index 000000000..c135d85b5
--- /dev/null
+++ b/Tests/QtAutogenRerun/rccDepends/resPlainA.qrc.in
@@ -0,0 +1,5 @@
+<RCC>
+ <qresource prefix="/TextsPlain">
+ <file>resPlain/input.txt</file>
+ </qresource>
+</RCC>
diff --git a/Tests/QtAutogenRerun/rccDepends/resPlainB.qrc.in b/Tests/QtAutogenRerun/rccDepends/resPlainB.qrc.in
new file mode 100644
index 000000000..186b6535a
--- /dev/null
+++ b/Tests/QtAutogenRerun/rccDepends/resPlainB.qrc.in
@@ -0,0 +1,6 @@
+<RCC>
+ <qresource prefix="/TextsPlain">
+ <file>resPlain/input.txt</file>
+ <file alias="Added">resPlain/inputAdded.txt</file>
+ </qresource>
+</RCC>
diff --git a/Tests/README b/Tests/README
deleted file mode 100644
index 8b2fda845..000000000
--- a/Tests/README
+++ /dev/null
@@ -1,39 +0,0 @@
-If you think about adding a new testcase then here is a small checklist you
-can run through to find a proper place for it. Go through the list from the
-beginning and stop once you find something that matches your tests needs,
-i.e. if you will test a module and only need the configure mode use the
-instructions from section 2, not 3.
-
-1. Your testcase can run in CMake script mode, i.e. "cmake -P something"
-
-Put your test in Tests/CMakeTests/ directory as a .cmake.in file. It will be
-put into the test binary directory by configure_file(... @ONLY) and run from
-there. Use the AddCMakeTest() macro in Tests/CMakeTests/CMakeLists.txt to add
-your test to the test runs.
-
-2. Your test needs CMake to run in configure mode, but will not build anything
-
-This includes tests that will build something using try_compile() and friends,
-but nothing that expects add_executable(), add_library(), or add_test() to run.
-
-If the test configures the project only once and it must succeed then put it
-into the Tests/CMakeOnly/ directory. Create a subdirectory named like your
-test and write the CMakeLists.txt you need into that subdirectory. Use the
-add_CMakeOnly_test() macro from Tests/CMakeOnly/CMakeLists.txt to add your
-test to the test runs.
-
-If the test configures the project with multiple variations and verifies
-success or failure each time then put it into the Tests/RunCMake/ directory.
-Read the instructions in Tests/RunCMake/CMakeLists.txt to add a test.
-
-3. If you are testing something from the Modules directory
-
-Put your test in the Tests/Modules/ directory. Create a subdirectory there
-named after your test. Use the ADD_TEST_MACRO macro from Tests/CMakeLists.txt
-to add your test to the test run. If you have put your stuff in
-Tests/Modules/Foo then you call it using ADD_TEST_MACRO(Module.Foo Foo).
-
-4. You are doing other stuff.
-
-Find a good place ;) In doubt mail to cmake-developers@cmake.org and ask for
-advise.
diff --git a/Tests/README.rst b/Tests/README.rst
new file mode 100644
index 000000000..3e989382b
--- /dev/null
+++ b/Tests/README.rst
@@ -0,0 +1,31 @@
+CMake Tests Directory
+*********************
+
+This directory contains the CMake test suite.
+See also the `CMake Source Code Guide`_.
+
+.. _`CMake Source Code Guide`: ../Help/dev/source.rst
+
+Many tests exist as immediate subdirectories, but some tests
+are organized as follows.
+
+* ``CMakeLib/``:
+ Source code, used for tests, that links to the ``CMakeLib`` library
+ defined over in ``Source/``.
+
+* ``CMakeOnly/``:
+ Deprecated. Tests that run CMake to generate a project but not build it.
+ Superseded by ``Tests/RunCMake/``.
+
+* ``Find*/``:
+ Tests for specific find modules that can only be run on machines with
+ the corresponding packages installed. They are enabled in
+ ``CMakeLists.txt`` by undocumented options used on CI builds.
+
+* ``Module/``:
+ Tests for specific CMake modules.
+
+* ``RunCMake/``:
+ Tests that run CMake and/or other tools while precisely checking
+ their return code and stdout/stderr content. Useful for testing
+ error cases and diagnostic output.
diff --git a/Tests/RunCMake/BuildDepends/C-Exe-Manifest.cmake b/Tests/RunCMake/BuildDepends/C-Exe-Manifest.cmake
index ef3301216..87b0de010 100644
--- a/Tests/RunCMake/BuildDepends/C-Exe-Manifest.cmake
+++ b/Tests/RunCMake/BuildDepends/C-Exe-Manifest.cmake
@@ -11,7 +11,7 @@ endif()
]])
endif()
-file(GENERATE OUTPUT check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
set(check_pairs
\"$<TARGET_FILE:main>|${CMAKE_CURRENT_BINARY_DIR}/test.manifest\"
)
diff --git a/Tests/RunCMake/BuildDepends/C-Exe.cmake b/Tests/RunCMake/BuildDepends/C-Exe.cmake
index 5057ca91d..ad5cd4d47 100644
--- a/Tests/RunCMake/BuildDepends/C-Exe.cmake
+++ b/Tests/RunCMake/BuildDepends/C-Exe.cmake
@@ -2,7 +2,7 @@ enable_language(C)
add_executable(main ${CMAKE_CURRENT_BINARY_DIR}/main.c)
-file(GENERATE OUTPUT check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
set(check_pairs
\"$<TARGET_FILE:main>|${CMAKE_CURRENT_BINARY_DIR}/main.c\"
)
diff --git a/Tests/RunCMake/BuildDepends/Custom-Always.cmake b/Tests/RunCMake/BuildDepends/Custom-Always.cmake
index d412708a1..c7e7fb0bc 100644
--- a/Tests/RunCMake/BuildDepends/Custom-Always.cmake
+++ b/Tests/RunCMake/BuildDepends/Custom-Always.cmake
@@ -16,7 +16,7 @@ add_custom_command(
add_custom_target(drive ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/after-always)
-file(GENERATE OUTPUT check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
set(check_pairs
\"${CMAKE_CURRENT_BINARY_DIR}/always-updated|${CMAKE_CURRENT_BINARY_DIR}/before-always\"
\"${CMAKE_CURRENT_BINARY_DIR}/after-always|${CMAKE_CURRENT_BINARY_DIR}/always-updated\"
diff --git a/Tests/RunCMake/BuildDepends/Custom-Symbolic-and-Byproduct.cmake b/Tests/RunCMake/BuildDepends/Custom-Symbolic-and-Byproduct.cmake
index 687c8271f..1e1f22ad0 100644
--- a/Tests/RunCMake/BuildDepends/Custom-Symbolic-and-Byproduct.cmake
+++ b/Tests/RunCMake/BuildDepends/Custom-Symbolic-and-Byproduct.cmake
@@ -16,7 +16,7 @@ add_custom_command(
add_custom_target(drive ALL DEPENDS use-byproduct)
add_dependencies(drive produce)
-file(GENERATE OUTPUT check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
if (check_step EQUAL 1)
set(check_pairs
\"${CMAKE_CURRENT_BINARY_DIR}/use-byproduct|${CMAKE_CURRENT_BINARY_DIR}/gen-byproduct-stamp\"
diff --git a/Tests/RunCMake/BuildDepends/MakeCustomIncludes.cmake b/Tests/RunCMake/BuildDepends/MakeCustomIncludes.cmake
index 0f92e0edb..8b2ae78cf 100644
--- a/Tests/RunCMake/BuildDepends/MakeCustomIncludes.cmake
+++ b/Tests/RunCMake/BuildDepends/MakeCustomIncludes.cmake
@@ -6,7 +6,7 @@ add_custom_command(
add_custom_target(generate ALL DEPENDS output.cxx)
set_property(TARGET generate PROPERTY INCLUDE_DIRECTORIES ${CMAKE_CURRENT_BINARY_DIR})
-file(GENERATE OUTPUT check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
set(check_pairs
\"${CMAKE_CURRENT_BINARY_DIR}/output.cxx|${CMAKE_CURRENT_BINARY_DIR}/MakeCustomIncludes.h\"
)
diff --git a/Tests/RunCMake/BuildDepends/MakeInProjectOnly.cmake b/Tests/RunCMake/BuildDepends/MakeInProjectOnly.cmake
index add9aeb69..af6ad86ba 100644
--- a/Tests/RunCMake/BuildDepends/MakeInProjectOnly.cmake
+++ b/Tests/RunCMake/BuildDepends/MakeInProjectOnly.cmake
@@ -3,7 +3,7 @@ get_filename_component(include_dir "${CMAKE_BINARY_DIR}" PATH)
include_directories("${include_dir}")
add_executable(MakeInProjectOnly MakeInProjectOnly.c)
set(CMAKE_DEPENDS_IN_PROJECT_ONLY 1)
-file(GENERATE OUTPUT check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/check-$<LOWER_CASE:$<CONFIG>>.cmake CONTENT "
if (check_step EQUAL 1)
set(check_pairs
\"$<TARGET_FILE:MakeInProjectOnly>|${include_dir}/MakeInProjectOnly.h\"
diff --git a/Tests/RunCMake/BuildDepends/RunCMakeTest.cmake b/Tests/RunCMake/BuildDepends/RunCMakeTest.cmake
index 9941c70df..1bf8fbc49 100644
--- a/Tests/RunCMake/BuildDepends/RunCMakeTest.cmake
+++ b/Tests/RunCMake/BuildDepends/RunCMakeTest.cmake
@@ -32,7 +32,8 @@ endfunction()
run_BuildDepends(C-Exe)
if(NOT RunCMake_GENERATOR STREQUAL "Xcode")
- if(RunCMake_GENERATOR MATCHES "Visual Studio 10")
+ if(RunCMake_GENERATOR MATCHES "Visual Studio 10" OR
+ RunCMake_GENERATOR_TOOLSET MATCHES "^(v80|v90|v100)$")
# VS 10 forgets to re-link when a manifest changes
set(run_BuildDepends_skip_step_2 1)
endif()
diff --git a/Tests/RunCMake/CMP0040/CMP0040-WARN-missing-target-stderr.txt b/Tests/RunCMake/CMP0040/CMP0040-WARN-missing-target-stderr.txt
index e3e3ff468..70ed05ba1 100644
--- a/Tests/RunCMake/CMP0040/CMP0040-WARN-missing-target-stderr.txt
+++ b/Tests/RunCMake/CMP0040/CMP0040-WARN-missing-target-stderr.txt
@@ -1,8 +1,8 @@
CMake Warning \(dev\) at CMP0040-WARN-missing-target.cmake:2 \(add_custom_command\):
Policy CMP0040 is not set: The target in the TARGET signature of
- add_custom_command\(\) must exist. Run "cmake --help-policy CMP0040" for
- policy details. Use the cmake_policy command to set the policy and
- suppress this warning.
+ add_custom_command\(\) must exist and must be defined in the current
+ directory. Run "cmake --help-policy CMP0040" for policy details. Use the
+ cmake_policy command to set the policy and suppress this warning.
+
No TARGET 'foobar' has been created in this directory.
Call Stack \(most recent call first\):
diff --git a/Tests/RunCMake/CMakeLists.txt b/Tests/RunCMake/CMakeLists.txt
index 79f487d41..29325ff0a 100644
--- a/Tests/RunCMake/CMakeLists.txt
+++ b/Tests/RunCMake/CMakeLists.txt
@@ -141,13 +141,16 @@ add_RunCMake_test(DisallowedCommands)
add_RunCMake_test(ExternalData)
add_RunCMake_test(FeatureSummary)
add_RunCMake_test(FPHSA)
+add_RunCMake_test(FindBoost)
if(NOT CMAKE_C_COMPILER_ID MATCHES "Watcom")
add_RunCMake_test(GenerateExportHeader)
endif()
add_RunCMake_test(GeneratorExpression)
add_RunCMake_test(GeneratorPlatform)
add_RunCMake_test(GeneratorToolset)
+add_RunCMake_test(GetPrerequisites)
add_RunCMake_test(GNUInstallDirs -DSYSTEM_NAME=${CMAKE_SYSTEM_NAME})
+add_RunCMake_test(GoogleTest) # Note: does not actually depend on Google Test
add_RunCMake_test(TargetPropertyGeneratorExpressions)
add_RunCMake_test(Languages)
add_RunCMake_test(LinkStatic)
@@ -179,10 +182,14 @@ add_RunCMake_test(Syntax)
add_RunCMake_test(add_custom_command)
add_RunCMake_test(add_custom_target)
add_RunCMake_test(add_dependencies)
+add_RunCMake_test(add_executable)
+add_RunCMake_test(add_library)
add_RunCMake_test(add_subdirectory)
add_RunCMake_test(build_command)
+add_executable(exit_code exit_code.c)
+set(execute_process_ARGS -DEXIT_CODE_EXE=$<TARGET_FILE:exit_code>)
if(NOT CMake_TEST_EXTERNAL_CMAKE)
- set(execute_process_ARGS -DTEST_ENCODING_EXE=$<TARGET_FILE:testEncoding>)
+ list(APPEND execute_process_ARGS -DTEST_ENCODING_EXE=$<TARGET_FILE:testEncoding>)
endif()
add_RunCMake_test(execute_process)
add_RunCMake_test(export)
@@ -213,6 +220,7 @@ add_RunCMake_test(get_property)
add_RunCMake_test(if)
add_RunCMake_test(include)
add_RunCMake_test(include_directories)
+add_RunCMake_test(include_guard)
add_RunCMake_test(list)
add_RunCMake_test(message)
add_RunCMake_test(project -DCMake_TEST_RESOURCES=${CMake_TEST_RESOURCES})
@@ -220,20 +228,39 @@ add_RunCMake_test(return)
add_RunCMake_test(separate_arguments)
add_RunCMake_test(set_property)
add_RunCMake_test(string)
-foreach(var
- CMAKE_C_COMPILER_ID
- CMAKE_C_COMPILER_VERSION
- CMAKE_C_STANDARD_DEFAULT
- CMAKE_CXX_COMPILER_ID
- CMAKE_CXX_COMPILER_VERSION
- CMAKE_CXX_STANDARD_DEFAULT
- CMake_TEST_CUDA
- )
- if(DEFINED ${var})
- list(APPEND try_compile_ARGS -D${var}=${${var}})
+add_RunCMake_test(test_include_dirs)
+
+function(add_RunCMake_test_try_compile)
+ if(CMAKE_VERSION VERSION_LESS 3.9.20170907 AND "x${CMAKE_CXX_COMPILER_ID}" STREQUAL "xMSVC")
+ # Older CMake versions do not know about MSVC language standards.
+ # Approximate our logic from MSVC-CXX.cmake.
+ if ((CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.0.24215.1 AND
+ CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10) OR
+ CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.10.25017)
+ set(CMAKE_CXX_STANDARD_DEFAULT 14)
+ elseif (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16.0)
+ set(CMAKE_CXX_STANDARD_DEFAULT "")
+ else()
+ unset(CMAKE_CXX_STANDARD_DEFAULT)
+ endif()
endif()
-endforeach()
-add_RunCMake_test(try_compile)
+ foreach(var
+ CMAKE_C_COMPILER_ID
+ CMAKE_C_COMPILER_VERSION
+ CMAKE_C_STANDARD_DEFAULT
+ CMAKE_CXX_COMPILER_ID
+ CMAKE_CXX_COMPILER_VERSION
+ CMAKE_CXX_STANDARD_DEFAULT
+ CMake_TEST_CUDA
+ )
+ if(DEFINED ${var})
+ list(APPEND try_compile_ARGS -D${var}=${${var}})
+ endif()
+ endforeach()
+ add_RunCMake_test(try_compile)
+endfunction()
+add_RunCMake_test_try_compile()
+
add_RunCMake_test(try_run)
add_RunCMake_test(set)
add_RunCMake_test(variable_watch)
@@ -338,10 +365,22 @@ if("${CMAKE_GENERATOR}" MATCHES "Make|Ninja")
add_executable(pseudo_tidy pseudo_tidy.c)
add_executable(pseudo_iwyu pseudo_iwyu.c)
add_executable(pseudo_cpplint pseudo_cpplint.c)
+ add_executable(pseudo_cppcheck pseudo_cppcheck.c)
add_RunCMake_test(ClangTidy -DPSEUDO_TIDY=$<TARGET_FILE:pseudo_tidy>)
add_RunCMake_test(IncludeWhatYouUse -DPSEUDO_IWYU=$<TARGET_FILE:pseudo_iwyu>)
add_RunCMake_test(Cpplint -DPSEUDO_CPPLINT=$<TARGET_FILE:pseudo_cpplint>)
+ add_RunCMake_test(Cppcheck -DPSEUDO_CPPCHECK=$<TARGET_FILE:pseudo_cppcheck>)
+ add_RunCMake_test(MultiLint
+ -DPSEUDO_TIDY=$<TARGET_FILE:pseudo_tidy>
+ -DPSEUDO_IWYU=$<TARGET_FILE:pseudo_iwyu>
+ -DPSEUDO_CPPLINT=$<TARGET_FILE:pseudo_cpplint>
+ -DPSEUDO_CPPCHECK=$<TARGET_FILE:pseudo_cppcheck>
+ )
+ if(DEFINED CMake_TEST_CUDA)
+ list(APPEND CompilerLauncher_ARGS -DCMake_TEST_CUDA=${CMake_TEST_CUDA})
+ endif()
add_RunCMake_test(CompilerLauncher)
+ add_RunCMake_test(ctest_labels_for_subprojects)
endif()
add_RunCMake_test_group(CPack "DEB;RPM;7Z;TBZ2;TGZ;TXZ;TZ;ZIP;STGZ")
@@ -371,3 +410,7 @@ if(CMake_TEST_ANDROID_NDK OR CMake_TEST_ANDROID_STANDALONE_TOOLCHAIN)
endif()
set_property(TEST RunCMake.Android PROPERTY TIMEOUT ${CMake_TEST_ANDROID_TIMEOUT})
endif()
+
+if(${CMAKE_GENERATOR} MATCHES "Visual Studio ([^89]|[89][0-9])")
+ add_RunCMake_test(CSharpCustomCommand)
+endif()
diff --git a/Tests/RunCMake/CPack/CMakeLists.txt b/Tests/RunCMake/CPack/CMakeLists.txt
index c361af065..1b3dbb228 100644
--- a/Tests/RunCMake/CPack/CMakeLists.txt
+++ b/Tests/RunCMake/CPack/CMakeLists.txt
@@ -15,3 +15,7 @@ include(tests/${RunCMake_TEST_FILE_PREFIX}/test.cmake)
set(CPACK_GENERATOR "${GENERATOR_TYPE}")
include(CPack)
+
+if(COMMAND run_after_include_cpack)
+ run_after_include_cpack()
+endif()
diff --git a/Tests/RunCMake/CPack/DEB/Helpers.cmake b/Tests/RunCMake/CPack/DEB/Helpers.cmake
index ad1b47bdc..6d8e84a52 100644
--- a/Tests/RunCMake/CPack/DEB/Helpers.cmake
+++ b/Tests/RunCMake/CPack/DEB/Helpers.cmake
@@ -23,7 +23,7 @@ function(getPackageNameGlobexpr NAME COMPONENT VERSION REVISION FILE_NO RESULT_V
endif()
if(GENERATOR_SPECIFIC_FORMAT)
- set(${RESULT_VAR} "${NAME}${COMPONENT}_${VERSION}-${REVISION}_*.deb" PARENT_SCOPE)
+ set(${RESULT_VAR} "${NAME}${COMPONENT}_${VERSION}_*.deb" PARENT_SCOPE)
else()
set(${RESULT_VAR} "${NAME}-${VERSION}-*${COMPONENT}.deb" PARENT_SCOPE)
endif()
diff --git a/Tests/RunCMake/CPack/README.txt b/Tests/RunCMake/CPack/README.txt
index 7c98f6972..cf7c02c79 100644
--- a/Tests/RunCMake/CPack/README.txt
+++ b/Tests/RunCMake/CPack/README.txt
@@ -91,6 +91,11 @@ If test will be used for multiple generators but some of them require some
generator specific commands then those commands should be added to 'test.cmake'
script wrapped with 'if(GENERATOR_TYPE STREQUAL <name_of_the_generator>)'.
+NOTE: In some cases (for example when testing CPackComponent.cmake functions)
+the test has to run some functions after CPack.cmake is included. In such cases
+a function run_after_include_cpack can be declared in test.cmake file and that
+function will run after the inclusion of CPack.cmake.
+
build phase (optional and not available for source package tests)
-----------------------------------------------------------------
diff --git a/Tests/RunCMake/CPack/RPM/Helpers.cmake b/Tests/RunCMake/CPack/RPM/Helpers.cmake
index d8012b11b..88fc23154 100644
--- a/Tests/RunCMake/CPack/RPM/Helpers.cmake
+++ b/Tests/RunCMake/CPack/RPM/Helpers.cmake
@@ -23,6 +23,9 @@ function(getPackageNameGlobexpr NAME COMPONENT VERSION REVISION FILE_NO RESULT_V
endif()
if(GENERATOR_SPECIFIC_FORMAT)
+ if(NOT REVISION)
+ set(REVISION "1")
+ endif()
set(${RESULT_VAR} "${NAME}${COMPONENT}-${VERSION}-${REVISION}.*.rpm" PARENT_SCOPE)
else()
set(${RESULT_VAR} "${NAME}-${VERSION}-*${COMPONENT}.rpm" PARENT_SCOPE)
diff --git a/Tests/RunCMake/CPack/RunCMakeTest.cmake b/Tests/RunCMake/CPack/RunCMakeTest.cmake
index faf151a13..aa55c4462 100644
--- a/Tests/RunCMake/CPack/RunCMakeTest.cmake
+++ b/Tests/RunCMake/CPack/RunCMakeTest.cmake
@@ -10,6 +10,7 @@ run_cpack_test(DEBUGINFO "RPM" true "COMPONENT")
run_cpack_test(DEPENDENCIES "RPM;DEB" true "COMPONENT")
run_cpack_test(DIST "RPM" false "MONOLITHIC")
run_cpack_test(EMPTY_DIR "RPM;DEB;TGZ" true "MONOLITHIC;COMPONENT")
+run_cpack_test(VERSION "RPM;DEB" false "MONOLITHIC;COMPONENT")
run_cpack_test(EXTRA "DEB" false "COMPONENT")
run_cpack_test(GENERATE_SHLIBS "DEB" true "COMPONENT")
run_cpack_test(GENERATE_SHLIBS_LDCONFIG "DEB" true "COMPONENT")
@@ -27,3 +28,5 @@ run_cpack_test(SUGGESTS "RPM" false "MONOLITHIC")
run_cpack_test(SYMLINKS "RPM;TGZ" false "MONOLITHIC;COMPONENT")
run_cpack_test(USER_FILELIST "RPM" false "MONOLITHIC")
run_cpack_test(MD5SUMS "DEB" false "MONOLITHIC;COMPONENT")
+run_cpack_test(CPACK_INSTALL_SCRIPT "ZIP" false "MONOLITHIC")
+run_cpack_test(DEB_PACKAGE_VERSION_BACK_COMPATIBILITY "DEB" false "MONOLITHIC;COMPONENT")
diff --git a/Tests/RunCMake/CPack/VerifyResult.cmake b/Tests/RunCMake/CPack/VerifyResult.cmake
index 470ebf7a8..1f5ab8716 100644
--- a/Tests/RunCMake/CPack/VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/VerifyResult.cmake
@@ -8,9 +8,7 @@ function(findExpectedFile FILE_NO RESULT_VAR GLOBING_EXPR_VAR)
endif()
if(NOT DEFINED EXPECTED_FILE_${FILE_NO}_VERSION)
set(EXPECTED_FILE_${FILE_NO}_VERSION "0.1.1")
- endif()
- if(NOT DEFINED EXPECTED_FILE_${FILE_NO}_REVISION)
- set(EXPECTED_FILE_${FILE_NO}_REVISION "1")
+ set(EXPECTED_FILE_${FILE_NO}_VERSION "0.1.1" PARENT_SCOPE)
endif()
getPackageNameGlobexpr("${EXPECTED_FILE_${FILE_NO}_NAME}"
diff --git a/Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/ExpectedFiles.cmake
new file mode 100644
index 000000000..5cb12c3ba
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/ExpectedFiles.cmake
@@ -0,0 +1,3 @@
+set(EXPECTED_FILES_COUNT "1")
+
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/abc.txt")
diff --git a/Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/test.cmake b/Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/test.cmake
new file mode 100644
index 000000000..e3fe0ca47
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/CPACK_INSTALL_SCRIPT/test.cmake
@@ -0,0 +1,11 @@
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/abc.txt" "test content")
+file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/user-script.cmake"
+ "file(INSTALL DESTINATION \"\${CMAKE_INSTALL_PREFIX}/foo\"
+ TYPE FILE FILES \"${CMAKE_CURRENT_BINARY_DIR}/abc.txt\")")
+set(CPACK_INSTALL_SCRIPT "${CMAKE_CURRENT_BINARY_DIR}/user-script.cmake")
+
+function(run_after_include_cpack)
+ file(READ "${CPACK_OUTPUT_CONFIG_FILE}" conf_file_)
+ string(REGEX REPLACE "SET\\(CPACK_INSTALL_CMAKE_PROJECTS [^)]*\\)" "" conf_file_ "${conf_file_}")
+ file(WRITE "${CPACK_OUTPUT_CONFIG_FILE}" "${conf_file_}")
+endfunction()
diff --git a/Tests/RunCMake/CPack/tests/DEB_PACKAGE_VERSION_BACK_COMPATIBILITY/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/DEB_PACKAGE_VERSION_BACK_COMPATIBILITY/ExpectedFiles.cmake
new file mode 100644
index 000000000..6142eb39a
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEB_PACKAGE_VERSION_BACK_COMPATIBILITY/ExpectedFiles.cmake
@@ -0,0 +1,2 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
diff --git a/Tests/RunCMake/CPack/tests/DEB_PACKAGE_VERSION_BACK_COMPATIBILITY/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/DEB_PACKAGE_VERSION_BACK_COMPATIBILITY/VerifyResult.cmake
new file mode 100644
index 000000000..771cc1048
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEB_PACKAGE_VERSION_BACK_COMPATIBILITY/VerifyResult.cmake
@@ -0,0 +1,11 @@
+function(checkPackageInfo_ TYPE FILE REGEX)
+ getPackageInfo("${FILE}" "FILE_INFO_")
+ if(NOT FILE_INFO_ MATCHES "${REGEX}")
+ message(FATAL_ERROR "Unexpected ${TYPE} in '${FILE}' ${EXPECTED_FILE_1_VERSION} ${EXPECTED_FILE_1_REVISION}; file info: '${FILE_INFO_}'")
+ endif()
+endfunction()
+
+set(whitespaces_ "[\t\n\r ]*")
+
+checkPackageInfo_("version" "${FOUND_FILE_1}"
+ ".*Version${whitespaces_}:${whitespaces_}5.0.1-71-g884852e")
diff --git a/Tests/RunCMake/CPack/tests/DEB_PACKAGE_VERSION_BACK_COMPATIBILITY/test.cmake b/Tests/RunCMake/CPack/tests/DEB_PACKAGE_VERSION_BACK_COMPATIBILITY/test.cmake
new file mode 100644
index 000000000..403e60dde
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/DEB_PACKAGE_VERSION_BACK_COMPATIBILITY/test.cmake
@@ -0,0 +1,7 @@
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT test)
+
+set(CPACK_DEBIAN_PACKAGE_VERSION "5.0.1-71-g884852e")
+
+if(PACKAGING_TYPE STREQUAL "COMPONENT")
+ set(CPACK_COMPONENTS_ALL test)
+endif()
diff --git a/Tests/RunCMake/CPack/tests/DIST/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/DIST/VerifyResult.cmake
index 7375ecc21..1b2eb4877 100644
--- a/Tests/RunCMake/CPack/tests/DIST/VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/tests/DIST/VerifyResult.cmake
@@ -5,6 +5,11 @@ execute_process(COMMAND ${RPMBUILD_EXECUTABLE} -E %{?dist}
set(whitespaces_ "[\t\n\r ]*")
+# since we have no control over dist tag value we should try to escape
+# the content for use as a regular expression
+string(REPLACE "+" "\\+" DIST_TAG "${DIST_TAG}")
+string(REPLACE "." "\\." DIST_TAG "${DIST_TAG}")
+
getPackageInfo("${FOUND_FILE_1}" "FILE_INFO_")
if(NOT FILE_INFO_ MATCHES ".*Release${whitespaces_}:${whitespaces_}1${DIST_TAG}")
message(FATAL_ERROR "Unexpected Release in '${FOUND_FILE_1}'; file info: '${FILE_INFO_}'")
diff --git a/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake
index e4f9618d3..2bb4d3ff9 100644
--- a/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake
+++ b/Tests/RunCMake/CPack/tests/PACKAGE_CHECKSUM/VerifyResult.cmake
@@ -1,8 +1,7 @@
if(NOT ${RunCMake_SUBTEST_SUFFIX} MATCHES "invalid")
- string(TOLOWER ${RunCMake_SUBTEST_SUFFIX} EXTENSION)
+ string(TOLOWER ${RunCMake_SUBTEST_SUFFIX} CHECKSUM_EXTENSION)
file(GLOB PACKAGE RELATIVE ${bin_dir} "*.tar.gz")
- file(GLOB CSUMFILE RELATIVE ${bin_dir} "*.${EXTENSION}")
- file(STRINGS ${CSUMFILE} CHSUM_VALUE)
+ file(STRINGS ${PACKAGE}.${CHECKSUM_EXTENSION} CHSUM_VALUE)
file(${RunCMake_SUBTEST_SUFFIX} ${PACKAGE} expected_value )
set(expected_value "${expected_value} ${PACKAGE}")
diff --git a/Tests/RunCMake/CPack/tests/VERSION/ExpectedFiles.cmake b/Tests/RunCMake/CPack/tests/VERSION/ExpectedFiles.cmake
new file mode 100644
index 000000000..85c571cad
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/VERSION/ExpectedFiles.cmake
@@ -0,0 +1,3 @@
+set(EXPECTED_FILES_COUNT "1")
+set(EXPECTED_FILE_CONTENT_1_LIST "/usr;/usr/foo;/usr/foo/CMakeLists.txt")
+set(EXPECTED_FILE_1_REVISION "1")
diff --git a/Tests/RunCMake/CPack/tests/VERSION/VerifyResult.cmake b/Tests/RunCMake/CPack/tests/VERSION/VerifyResult.cmake
new file mode 100644
index 000000000..eed9696cd
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/VERSION/VerifyResult.cmake
@@ -0,0 +1,17 @@
+function(checkPackageInfo_ TYPE FILE REGEX)
+ getPackageInfo("${FILE}" "FILE_INFO_")
+ if(NOT FILE_INFO_ MATCHES "${REGEX}")
+ message(FATAL_ERROR "Unexpected ${TYPE} in '${FILE}' ${EXPECTED_FILE_1_VERSION} ${EXPECTED_FILE_1_REVISION}; file info: '${FILE_INFO_}'")
+ endif()
+endfunction()
+
+set(whitespaces_ "[\t\n\r ]*")
+
+if(GENERATOR_TYPE STREQUAL "RPM")
+ checkPackageInfo_("package version" "${FOUND_FILE_1}" "Version${whitespaces_}:${whitespaces_}${EXPECTED_FILE_1_VERSION}")
+ checkPackageInfo_("package revision" "${FOUND_FILE_1}" "Release${whitespaces_}:${whitespaces_}${EXPECTED_FILE_1_REVISION}")
+ checkPackageInfo_("epoch version" "${FOUND_FILE_1}" "Epoch${whitespaces_}:${whitespaces_}3")
+else() # DEB
+ checkPackageInfo_("version" "${FOUND_FILE_1}"
+ ".*Version${whitespaces_}:${whitespaces_}3:${EXPECTED_FILE_1_VERSION}-${EXPECTED_FILE_1_REVISION}")
+endif()
diff --git a/Tests/RunCMake/CPack/tests/VERSION/test.cmake b/Tests/RunCMake/CPack/tests/VERSION/test.cmake
new file mode 100644
index 000000000..301ab6126
--- /dev/null
+++ b/Tests/RunCMake/CPack/tests/VERSION/test.cmake
@@ -0,0 +1,14 @@
+install(FILES CMakeLists.txt DESTINATION foo COMPONENT test)
+
+if(GENERATOR_TYPE STREQUAL "DEB")
+ set(package_type_ "DEBIAN")
+ set(CPACK_DEBIAN_PACKAGE_RELEASE "1")
+else()
+ set(package_type_ "${GENERATOR_TYPE}")
+endif()
+
+set(CPACK_${package_type_}_PACKAGE_EPOCH "3")
+
+if(PACKAGING_TYPE STREQUAL "COMPONENT")
+ set(CPACK_COMPONENTS_ALL test)
+endif()
diff --git a/Tests/RunCMake/CPackInstallProperties/FilenameGenex.cmake b/Tests/RunCMake/CPackInstallProperties/FilenameGenex.cmake
index 1a373b928..8fc1218f2 100644
--- a/Tests/RunCMake/CPackInstallProperties/FilenameGenex.cmake
+++ b/Tests/RunCMake/CPackInstallProperties/FilenameGenex.cmake
@@ -1,6 +1,6 @@
add_executable(mytest test.cpp)
-file(GENERATE OUTPUT runtest_info.cmake CONTENT [[
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/runtest_info.cmake CONTENT [[
set(EXPECTED_MYTEST_NAME "$<TARGET_FILE_NAME:mytest>")
]])
diff --git a/Tests/RunCMake/CPackInstallProperties/PerConfigValue.cmake b/Tests/RunCMake/CPackInstallProperties/PerConfigValue.cmake
index 77fe8ed5d..b23d3c7df 100644
--- a/Tests/RunCMake/CPackInstallProperties/PerConfigValue.cmake
+++ b/Tests/RunCMake/CPackInstallProperties/PerConfigValue.cmake
@@ -6,7 +6,7 @@ foreach(CONFIG IN LISTS CMAKE_CONFIGURATION_TYPES)
OUTPUT_NAME_${UPPER_CONFIG} bar_${CONFIG})
endforeach()
-file(GENERATE OUTPUT runtest_info_$<CONFIG>.cmake CONTENT [[
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/runtest_info_$<CONFIG>.cmake CONTENT [[
set(CPACK_BUILD_CONFIG "$<CONFIG>")
set(EXPECTED_MYTEST_NAME "$<TARGET_FILE_NAME:mytest>")
]])
diff --git a/Tests/RunCMake/CPackInstallProperties/ValueGenex.cmake b/Tests/RunCMake/CPackInstallProperties/ValueGenex.cmake
index 2e1d4656c..2001d9f4c 100644
--- a/Tests/RunCMake/CPackInstallProperties/ValueGenex.cmake
+++ b/Tests/RunCMake/CPackInstallProperties/ValueGenex.cmake
@@ -1,6 +1,6 @@
add_executable(mytest test.cpp)
-file(GENERATE OUTPUT runtest_info.cmake CONTENT [[
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/runtest_info.cmake CONTENT [[
set(EXPECTED_MYTEST_NAME "$<TARGET_FILE_NAME:mytest>")
]])
diff --git a/Tests/RunCMake/CSharpCustomCommand/CMakeLists.txt b/Tests/RunCMake/CSharpCustomCommand/CMakeLists.txt
new file mode 100644
index 000000000..74b3ff8de
--- /dev/null
+++ b/Tests/RunCMake/CSharpCustomCommand/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.3)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/CSharpCustomCommand/CommandWithOutput-check.cmake b/Tests/RunCMake/CSharpCustomCommand/CommandWithOutput-check.cmake
new file mode 100644
index 000000000..60d77eb60
--- /dev/null
+++ b/Tests/RunCMake/CSharpCustomCommand/CommandWithOutput-check.cmake
@@ -0,0 +1,21 @@
+if(checkLevel EQUAL 0)
+ message("checking generation (${srcName} does not exist)")
+ if(EXISTS "${generatedFileName}")
+ set(RunCMake_TEST_FAILED "file \"${generatedFileName}\" should not exist")
+ endif()
+elseif(checkLevel EQUAL 1)
+ message("checking build 1 (generate ${srcName})")
+ if(NOT "${actual_stdout}" MATCHES "${commandComment}")
+ set(RunCMake_TEST_FAILED "command not executed")
+ endif()
+elseif(checkLevel EQUAL 2)
+ message("checking build 2 (no change in ${srcName}.in)")
+ if("${actual_stdout}" MATCHES "${commandComment}")
+ set(RunCMake_TEST_FAILED "command executed")
+ endif()
+elseif(checkLevel EQUAL 3)
+ message("checking build 3 (update ${srcName})")
+ if(NOT "${actual_stdout}" MATCHES "${commandComment}")
+ set(RunCMake_TEST_FAILED "command not executed")
+ endif()
+endif()
diff --git a/Tests/RunCMake/CSharpCustomCommand/CommandWithOutput.cmake b/Tests/RunCMake/CSharpCustomCommand/CommandWithOutput.cmake
new file mode 100644
index 000000000..68341fa88
--- /dev/null
+++ b/Tests/RunCMake/CSharpCustomCommand/CommandWithOutput.cmake
@@ -0,0 +1,13 @@
+enable_language(CSharp)
+
+add_executable(CSharpCustomCommand dummy.cs)
+
+add_custom_command(OUTPUT ${generatedFileName}
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ ${inputFileName} ${generatedFileName}
+ MAIN_DEPENDENCY ${inputFileName}
+ COMMENT "${commandComment}")
+
+target_sources(CSharpCustomCommand PRIVATE
+ ${inputFileName}
+ ${generatedFileName})
diff --git a/Tests/RunCMake/CSharpCustomCommand/RunCMakeTest.cmake b/Tests/RunCMake/CSharpCustomCommand/RunCMakeTest.cmake
new file mode 100644
index 000000000..fa5618aab
--- /dev/null
+++ b/Tests/RunCMake/CSharpCustomCommand/RunCMakeTest.cmake
@@ -0,0 +1,34 @@
+include(RunCMake)
+
+# Use a single build tree for a few tests without cleaning.
+set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/CommandWithOutput-build)
+set(RunCMake_TEST_NO_CLEAN 1)
+file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+set(RunCMake-check-file CommandWithOutput-check.cmake)
+
+set(srcName "test.cs")
+set(srcFileName "${CMAKE_CURRENT_LIST_DIR}/${srcName}.in")
+set(inputFileName "${RunCMake_TEST_BINARY_DIR}/${srcName}.in")
+set(generatedFileName "${RunCMake_TEST_BINARY_DIR}/${srcName}")
+set(commandComment "Generating ${srcName}")
+
+# copy the input file to build dir to avoid changing files in cmake
+# source tree.
+file(COPY "${srcFileName}" DESTINATION "${RunCMake_TEST_BINARY_DIR}")
+
+set(RunCMake_TEST_OPTIONS ${RunCMake_TEST_OPTIONS}
+ "-DinputFileName=${inputFileName}"
+ "-DgeneratedFileName=${generatedFileName}"
+ "-DcommandComment=${commandComment}")
+
+set(checkLevel 0)
+run_cmake(CommandWithOutput)
+set(checkLevel 1)
+run_cmake_command(CommandWithOutput-build1 ${CMAKE_COMMAND} --build . --config Debug)
+set(checkLevel 2)
+run_cmake_command(CommandWithOutput-build2 ${CMAKE_COMMAND} --build . --config Debug)
+# change file content to trigger custom command with next build
+file(APPEND ${inputFileName} "\n")
+set(checkLevel 3)
+run_cmake_command(CommandWithOutput-build3 ${CMAKE_COMMAND} --build . --config Debug)
diff --git a/Tests/RunCMake/CSharpCustomCommand/dummy.cs b/Tests/RunCMake/CSharpCustomCommand/dummy.cs
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/CSharpCustomCommand/dummy.cs
diff --git a/Tests/RunCMake/CSharpCustomCommand/test.cs.in b/Tests/RunCMake/CSharpCustomCommand/test.cs.in
new file mode 100644
index 000000000..05a7531e0
--- /dev/null
+++ b/Tests/RunCMake/CSharpCustomCommand/test.cs.in
@@ -0,0 +1,8 @@
+class TestCs
+{
+ public static int Main(string[] args)
+ {
+ System.Console.WriteLine("Test C#");
+ return 0;
+ }
+}
diff --git a/Tests/RunCMake/CTestCommandLine/LabelCount-stdout.txt b/Tests/RunCMake/CTestCommandLine/LabelCount-stdout.txt
index 7fe04eb6a..9cfe41ca3 100644
--- a/Tests/RunCMake/CTestCommandLine/LabelCount-stdout.txt
+++ b/Tests/RunCMake/CTestCommandLine/LabelCount-stdout.txt
@@ -1,7 +1,7 @@
100% tests passed, 0 tests failed out of 4
+
+Label Time Summary:
-+'bar' = +[0-9.]+ sec \(3 tests\)
-+'foo' = +[0-9.]+ sec \(1 test\)
++'bar' = +[0-9.]+ sec\*proc \(3 tests\)
++'foo' = +[0-9.]+ sec\*proc \(1 test\)
+
Total Test time \(real\) = +[0-9.]+ sec
diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-bad-iwyu-result.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-result.txt
index d00491fd7..d00491fd7 100644
--- a/Tests/RunCMake/CommandLine/E___run_iwyu-bad-iwyu-result.txt
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-result.txt
diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-bad-iwyu-stderr.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-stderr.txt
index 338f7c4e6..338f7c4e6 100644
--- a/Tests/RunCMake/CommandLine/E___run_iwyu-bad-iwyu-stderr.txt
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-bad-iwyu-stderr.txt
diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no----result.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no----result.txt
index d00491fd7..d00491fd7 100644
--- a/Tests/RunCMake/CommandLine/E___run_iwyu-no----result.txt
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no----result.txt
diff --git a/Tests/RunCMake/CommandLine/E___run_co_compile-no----stderr.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no----stderr.txt
new file mode 100644
index 000000000..f0597d2cf
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no----stderr.txt
@@ -0,0 +1 @@
+^__run_co_compile given unknown argument: command-does-not-exist$
diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no-cc-result.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-result.txt
index d00491fd7..d00491fd7 100644
--- a/Tests/RunCMake/CommandLine/E___run_iwyu-no-cc-result.txt
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-result.txt
diff --git a/Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-stderr.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-stderr.txt
new file mode 100644
index 000000000..bba846e41
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no-cc-stderr.txt
@@ -0,0 +1 @@
+^__run_co_compile missing compile command after --$
diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-result.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-result.txt
index d00491fd7..d00491fd7 100644
--- a/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-result.txt
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-result.txt
diff --git a/Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-stderr.txt b/Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-stderr.txt
new file mode 100644
index 000000000..a7fbad667
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E___run_co_compile-no-iwyu-stderr.txt
@@ -0,0 +1,6 @@
+^__run_co_compile missing command to run. Looking for one or more of the following:
+--cppcheck=
+--cpplint=
+--iwyu=
+--lwyu=
+--tidy=
diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no----stderr.txt b/Tests/RunCMake/CommandLine/E___run_iwyu-no----stderr.txt
deleted file mode 100644
index c251adf00..000000000
--- a/Tests/RunCMake/CommandLine/E___run_iwyu-no----stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^__run_iwyu given unknown argument: command-does-not-exist$
diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no-cc-stderr.txt b/Tests/RunCMake/CommandLine/E___run_iwyu-no-cc-stderr.txt
deleted file mode 100644
index 1998abb22..000000000
--- a/Tests/RunCMake/CommandLine/E___run_iwyu-no-cc-stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^__run_iwyu missing compile command after --$
diff --git a/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-stderr.txt b/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-stderr.txt
deleted file mode 100644
index 35f50b76b..000000000
--- a/Tests/RunCMake/CommandLine/E___run_iwyu-no-iwyu-stderr.txt
+++ /dev/null
@@ -1 +0,0 @@
-^__run_iwyu missing --cpplint=, --iwyu=, --lwyu=, and/or --tidy=$
diff --git a/Tests/RunCMake/CommandLine/E_md5sum-dir-result.txt b/Tests/RunCMake/CommandLine/E_md5sum-dir-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_md5sum-dir-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_md5sum-dir-stderr.txt b/Tests/RunCMake/CommandLine/E_md5sum-dir-stderr.txt
new file mode 100644
index 000000000..061fd64d7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_md5sum-dir-stderr.txt
@@ -0,0 +1 @@
+Error: . is a directory
diff --git a/Tests/RunCMake/CommandLine/E_md5sum-mixed-result.txt b/Tests/RunCMake/CommandLine/E_md5sum-mixed-result.txt
new file mode 100644
index 000000000..0cfbf0888
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_md5sum-mixed-result.txt
@@ -0,0 +1 @@
+2
diff --git a/Tests/RunCMake/CommandLine/E_md5sum-mixed-stderr.txt b/Tests/RunCMake/CommandLine/E_md5sum-mixed-stderr.txt
new file mode 100644
index 000000000..b6b84c39a
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_md5sum-mixed-stderr.txt
@@ -0,0 +1,2 @@
+Error: . is a directory
+nonexisting: No such file or directory
diff --git a/Tests/RunCMake/CommandLine/E_md5sum-mixed-stdout.txt b/Tests/RunCMake/CommandLine/E_md5sum-mixed-stdout.txt
new file mode 100644
index 000000000..18e49bef0
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_md5sum-mixed-stdout.txt
@@ -0,0 +1 @@
+275876e34cf609db118f3d84b799a790 ../dummy
diff --git a/Tests/RunCMake/CommandLine/E_md5sum-no-file-result.txt b/Tests/RunCMake/CommandLine/E_md5sum-no-file-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_md5sum-no-file-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_md5sum-no-file-stderr.txt b/Tests/RunCMake/CommandLine/E_md5sum-no-file-stderr.txt
new file mode 100644
index 000000000..732e8c4f6
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_md5sum-no-file-stderr.txt
@@ -0,0 +1 @@
+nonexisting: No such file or directory
diff --git a/Tests/RunCMake/CommandLine/E_md5sum-result.txt b/Tests/RunCMake/CommandLine/E_md5sum-result.txt
new file mode 100644
index 000000000..573541ac9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_md5sum-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/CommandLine/E_md5sum-stdout.txt b/Tests/RunCMake/CommandLine/E_md5sum-stdout.txt
new file mode 100644
index 000000000..18e49bef0
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_md5sum-stdout.txt
@@ -0,0 +1 @@
+275876e34cf609db118f3d84b799a790 ../dummy
diff --git a/Tests/RunCMake/CommandLine/E_sha1sum-dir-result.txt b/Tests/RunCMake/CommandLine/E_sha1sum-dir-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha1sum-dir-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_sha1sum-dir-stderr.txt b/Tests/RunCMake/CommandLine/E_sha1sum-dir-stderr.txt
new file mode 100644
index 000000000..061fd64d7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha1sum-dir-stderr.txt
@@ -0,0 +1 @@
+Error: . is a directory
diff --git a/Tests/RunCMake/CommandLine/E_sha1sum-no-file-result.txt b/Tests/RunCMake/CommandLine/E_sha1sum-no-file-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha1sum-no-file-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_sha1sum-no-file-stderr.txt b/Tests/RunCMake/CommandLine/E_sha1sum-no-file-stderr.txt
new file mode 100644
index 000000000..732e8c4f6
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha1sum-no-file-stderr.txt
@@ -0,0 +1 @@
+nonexisting: No such file or directory
diff --git a/Tests/RunCMake/CommandLine/E_sha1sum-result.txt b/Tests/RunCMake/CommandLine/E_sha1sum-result.txt
new file mode 100644
index 000000000..573541ac9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha1sum-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/CommandLine/E_sha1sum-stdout.txt b/Tests/RunCMake/CommandLine/E_sha1sum-stdout.txt
new file mode 100644
index 000000000..689b85bc3
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha1sum-stdout.txt
@@ -0,0 +1 @@
+829c3804401b0727f70f73d4415e162400cbe57b ../dummy
diff --git a/Tests/RunCMake/CommandLine/E_sha224sum-dir-result.txt b/Tests/RunCMake/CommandLine/E_sha224sum-dir-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha224sum-dir-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_sha224sum-dir-stderr.txt b/Tests/RunCMake/CommandLine/E_sha224sum-dir-stderr.txt
new file mode 100644
index 000000000..061fd64d7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha224sum-dir-stderr.txt
@@ -0,0 +1 @@
+Error: . is a directory
diff --git a/Tests/RunCMake/CommandLine/E_sha224sum-no-file-result.txt b/Tests/RunCMake/CommandLine/E_sha224sum-no-file-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha224sum-no-file-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_sha224sum-no-file-stderr.txt b/Tests/RunCMake/CommandLine/E_sha224sum-no-file-stderr.txt
new file mode 100644
index 000000000..732e8c4f6
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha224sum-no-file-stderr.txt
@@ -0,0 +1 @@
+nonexisting: No such file or directory
diff --git a/Tests/RunCMake/CommandLine/E_sha224sum-result.txt b/Tests/RunCMake/CommandLine/E_sha224sum-result.txt
new file mode 100644
index 000000000..573541ac9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha224sum-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/CommandLine/E_sha224sum-stdout.txt b/Tests/RunCMake/CommandLine/E_sha224sum-stdout.txt
new file mode 100644
index 000000000..5b3e2178a
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha224sum-stdout.txt
@@ -0,0 +1 @@
+37d32c6dbabed711cb1d4620b64090fef0ef63ab16a4a51d668259e6 ../dummy
diff --git a/Tests/RunCMake/CommandLine/E_sha256sum-dir-result.txt b/Tests/RunCMake/CommandLine/E_sha256sum-dir-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha256sum-dir-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_sha256sum-dir-stderr.txt b/Tests/RunCMake/CommandLine/E_sha256sum-dir-stderr.txt
new file mode 100644
index 000000000..061fd64d7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha256sum-dir-stderr.txt
@@ -0,0 +1 @@
+Error: . is a directory
diff --git a/Tests/RunCMake/CommandLine/E_sha256sum-no-file-result.txt b/Tests/RunCMake/CommandLine/E_sha256sum-no-file-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha256sum-no-file-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_sha256sum-no-file-stderr.txt b/Tests/RunCMake/CommandLine/E_sha256sum-no-file-stderr.txt
new file mode 100644
index 000000000..732e8c4f6
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha256sum-no-file-stderr.txt
@@ -0,0 +1 @@
+nonexisting: No such file or directory
diff --git a/Tests/RunCMake/CommandLine/E_sha256sum-result.txt b/Tests/RunCMake/CommandLine/E_sha256sum-result.txt
new file mode 100644
index 000000000..573541ac9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha256sum-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/CommandLine/E_sha256sum-stdout.txt b/Tests/RunCMake/CommandLine/E_sha256sum-stdout.txt
new file mode 100644
index 000000000..9a1877082
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha256sum-stdout.txt
@@ -0,0 +1 @@
+b5a2c96250612366ea272ffac6d9744aaf4b45aacd96aa7cfcb931ee3b558259 ../dummy
diff --git a/Tests/RunCMake/CommandLine/E_sha384sum-dir-result.txt b/Tests/RunCMake/CommandLine/E_sha384sum-dir-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha384sum-dir-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_sha384sum-dir-stderr.txt b/Tests/RunCMake/CommandLine/E_sha384sum-dir-stderr.txt
new file mode 100644
index 000000000..061fd64d7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha384sum-dir-stderr.txt
@@ -0,0 +1 @@
+Error: . is a directory
diff --git a/Tests/RunCMake/CommandLine/E_sha384sum-no-file-result.txt b/Tests/RunCMake/CommandLine/E_sha384sum-no-file-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha384sum-no-file-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_sha384sum-no-file-stderr.txt b/Tests/RunCMake/CommandLine/E_sha384sum-no-file-stderr.txt
new file mode 100644
index 000000000..732e8c4f6
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha384sum-no-file-stderr.txt
@@ -0,0 +1 @@
+nonexisting: No such file or directory
diff --git a/Tests/RunCMake/CommandLine/E_sha384sum-result.txt b/Tests/RunCMake/CommandLine/E_sha384sum-result.txt
new file mode 100644
index 000000000..573541ac9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha384sum-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/CommandLine/E_sha384sum-stdout.txt b/Tests/RunCMake/CommandLine/E_sha384sum-stdout.txt
new file mode 100644
index 000000000..b706ac587
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha384sum-stdout.txt
@@ -0,0 +1 @@
+43c1835ceba2e29596f05e3859d4fe2b6d124a181ed670f68e914bd3ed251b02b4be609608a13f23ec3d98da6c4eb8cd ../dummy
diff --git a/Tests/RunCMake/CommandLine/E_sha512sum-dir-result.txt b/Tests/RunCMake/CommandLine/E_sha512sum-dir-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha512sum-dir-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_sha512sum-dir-stderr.txt b/Tests/RunCMake/CommandLine/E_sha512sum-dir-stderr.txt
new file mode 100644
index 000000000..061fd64d7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha512sum-dir-stderr.txt
@@ -0,0 +1 @@
+Error: . is a directory
diff --git a/Tests/RunCMake/CommandLine/E_sha512sum-no-file-result.txt b/Tests/RunCMake/CommandLine/E_sha512sum-no-file-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha512sum-no-file-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/CommandLine/E_sha512sum-no-file-stderr.txt b/Tests/RunCMake/CommandLine/E_sha512sum-no-file-stderr.txt
new file mode 100644
index 000000000..732e8c4f6
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha512sum-no-file-stderr.txt
@@ -0,0 +1 @@
+nonexisting: No such file or directory
diff --git a/Tests/RunCMake/CommandLine/E_sha512sum-result.txt b/Tests/RunCMake/CommandLine/E_sha512sum-result.txt
new file mode 100644
index 000000000..573541ac9
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha512sum-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/CommandLine/E_sha512sum-stdout.txt b/Tests/RunCMake/CommandLine/E_sha512sum-stdout.txt
new file mode 100644
index 000000000..4305383bb
--- /dev/null
+++ b/Tests/RunCMake/CommandLine/E_sha512sum-stdout.txt
@@ -0,0 +1 @@
+1692526aab84461a8aebcefddcba2b33fb5897ab180c53e8b345ae125484d0aaa35baf60487050be21ed8909a48eace93851bf139087ce1f7a87d97b6120a651 ../dummy
diff --git a/Tests/RunCMake/CommandLine/RunCMakeTest.cmake b/Tests/RunCMake/CommandLine/RunCMakeTest.cmake
index f94b10ac5..55eac5ec2 100644
--- a/Tests/RunCMake/CommandLine/RunCMakeTest.cmake
+++ b/Tests/RunCMake/CommandLine/RunCMakeTest.cmake
@@ -21,10 +21,10 @@ run_cmake_command(E_touch_nocreate-no-arg ${CMAKE_COMMAND} -E touch_nocreate)
run_cmake_command(E_time ${CMAKE_COMMAND} -E time ${CMAKE_COMMAND} -E echo "hello world")
run_cmake_command(E_time-no-arg ${CMAKE_COMMAND} -E time)
-run_cmake_command(E___run_iwyu-no-iwyu ${CMAKE_COMMAND} -E __run_iwyu -- command-does-not-exist)
-run_cmake_command(E___run_iwyu-bad-iwyu ${CMAKE_COMMAND} -E __run_iwyu --iwyu=iwyu-does-not-exist -- command-does-not-exist)
-run_cmake_command(E___run_iwyu-no--- ${CMAKE_COMMAND} -E __run_iwyu --iwyu=iwyu-does-not-exist command-does-not-exist)
-run_cmake_command(E___run_iwyu-no-cc ${CMAKE_COMMAND} -E __run_iwyu --iwyu=iwyu-does-not-exist --)
+run_cmake_command(E___run_co_compile-no-iwyu ${CMAKE_COMMAND} -E __run_co_compile -- command-does-not-exist)
+run_cmake_command(E___run_co_compile-bad-iwyu ${CMAKE_COMMAND} -E __run_co_compile --iwyu=iwyu-does-not-exist -- command-does-not-exist)
+run_cmake_command(E___run_co_compile-no--- ${CMAKE_COMMAND} -E __run_co_compile --iwyu=iwyu-does-not-exist command-does-not-exist)
+run_cmake_command(E___run_co_compile-no-cc ${CMAKE_COMMAND} -E __run_co_compile --iwyu=iwyu-does-not-exist --)
run_cmake_command(G_no-arg ${CMAKE_COMMAND} -G)
run_cmake_command(G_bad-arg ${CMAKE_COMMAND} -G NoSuchGenerator)
@@ -172,6 +172,30 @@ run_cmake_command(E_env-bad-arg1 ${CMAKE_COMMAND} -E env -bad-arg1)
run_cmake_command(E_env-set ${CMAKE_COMMAND} -E env TEST_ENV=1 ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/E_env-set.cmake)
run_cmake_command(E_env-unset ${CMAKE_COMMAND} -E env TEST_ENV=1 ${CMAKE_COMMAND} -E env --unset=TEST_ENV ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/E_env-unset.cmake)
+run_cmake_command(E_md5sum-dir ${CMAKE_COMMAND} -E md5sum .)
+run_cmake_command(E_sha1sum-dir ${CMAKE_COMMAND} -E sha1sum .)
+run_cmake_command(E_sha224sum-dir ${CMAKE_COMMAND} -E sha224sum .)
+run_cmake_command(E_sha256sum-dir ${CMAKE_COMMAND} -E sha256sum .)
+run_cmake_command(E_sha384sum-dir ${CMAKE_COMMAND} -E sha384sum .)
+run_cmake_command(E_sha512sum-dir ${CMAKE_COMMAND} -E sha512sum .)
+
+run_cmake_command(E_md5sum-no-file ${CMAKE_COMMAND} -E md5sum nonexisting)
+run_cmake_command(E_sha1sum-no-file ${CMAKE_COMMAND} -E sha1sum nonexisting)
+run_cmake_command(E_sha224sum-no-file ${CMAKE_COMMAND} -E sha224sum nonexisting)
+run_cmake_command(E_sha256sum-no-file ${CMAKE_COMMAND} -E sha256sum nonexisting)
+run_cmake_command(E_sha384sum-no-file ${CMAKE_COMMAND} -E sha384sum nonexisting)
+run_cmake_command(E_sha512sum-no-file ${CMAKE_COMMAND} -E sha512sum nonexisting)
+
+file(WRITE "${RunCMake_BINARY_DIR}/dummy" "dummy")
+run_cmake_command(E_md5sum ${CMAKE_COMMAND} -E md5sum ../dummy)
+run_cmake_command(E_md5sum-mixed ${CMAKE_COMMAND} -E md5sum . ../dummy nonexisting)
+run_cmake_command(E_sha1sum ${CMAKE_COMMAND} -E sha1sum ../dummy)
+run_cmake_command(E_sha224sum ${CMAKE_COMMAND} -E sha224sum ../dummy)
+run_cmake_command(E_sha256sum ${CMAKE_COMMAND} -E sha256sum ../dummy)
+run_cmake_command(E_sha384sum ${CMAKE_COMMAND} -E sha384sum ../dummy)
+run_cmake_command(E_sha512sum ${CMAKE_COMMAND} -E sha512sum ../dummy)
+file(REMOVE "${RunCMake_BINARY_DIR}/dummy")
+
set(RunCMake_DEFAULT_stderr ".")
run_cmake_command(E_sleep-no-args ${CMAKE_COMMAND} -E sleep)
unset(RunCMake_DEFAULT_stderr)
diff --git a/Tests/RunCMake/CommandLine/cmake_depends/.gitattributes b/Tests/RunCMake/CommandLine/cmake_depends/.gitattributes
deleted file mode 100644
index 9c22288cd..000000000
--- a/Tests/RunCMake/CommandLine/cmake_depends/.gitattributes
+++ /dev/null
@@ -1,2 +0,0 @@
-# Do not format a source encoded in UTF-16.
-test_UTF-16LE.h -format.clang-format
diff --git a/Tests/RunCMake/CompilerLauncher/CUDA-Build-stdout.txt b/Tests/RunCMake/CompilerLauncher/CUDA-Build-stdout.txt
new file mode 100644
index 000000000..3313e31f6
--- /dev/null
+++ b/Tests/RunCMake/CompilerLauncher/CUDA-Build-stdout.txt
@@ -0,0 +1 @@
+.*-E env USED_LAUNCHER=1.*
diff --git a/Tests/RunCMake/CompilerLauncher/CUDA-launch-Build-stdout.txt b/Tests/RunCMake/CompilerLauncher/CUDA-launch-Build-stdout.txt
new file mode 100644
index 000000000..3313e31f6
--- /dev/null
+++ b/Tests/RunCMake/CompilerLauncher/CUDA-launch-Build-stdout.txt
@@ -0,0 +1 @@
+.*-E env USED_LAUNCHER=1.*
diff --git a/Tests/RunCMake/CompilerLauncher/CUDA-launch.cmake b/Tests/RunCMake/CompilerLauncher/CUDA-launch.cmake
new file mode 100644
index 000000000..6b4b816e9
--- /dev/null
+++ b/Tests/RunCMake/CompilerLauncher/CUDA-launch.cmake
@@ -0,0 +1,3 @@
+set(CTEST_USE_LAUNCHERS 1)
+include(CTestUseLaunchers)
+include(CUDA.cmake)
diff --git a/Tests/RunCMake/CompilerLauncher/CUDA.cmake b/Tests/RunCMake/CompilerLauncher/CUDA.cmake
new file mode 100644
index 000000000..fe5560bc7
--- /dev/null
+++ b/Tests/RunCMake/CompilerLauncher/CUDA.cmake
@@ -0,0 +1,4 @@
+enable_language(CUDA)
+set(CMAKE_CUDA_COMPILER_LAUNCHER "${CMAKE_COMMAND};-E;env;USED_LAUNCHER=1")
+set(CMAKE_VERBOSE_MAKEFILE TRUE)
+add_executable(main main.cu)
diff --git a/Tests/RunCMake/CompilerLauncher/RunCMakeTest.cmake b/Tests/RunCMake/CompilerLauncher/RunCMakeTest.cmake
index 5884d5c4d..ab2651203 100644
--- a/Tests/RunCMake/CompilerLauncher/RunCMakeTest.cmake
+++ b/Tests/RunCMake/CompilerLauncher/RunCMakeTest.cmake
@@ -15,9 +15,14 @@ function(run_compiler_launcher lang)
run_cmake_command(${lang}-Build ${CMAKE_COMMAND} --build . ${verbose_args})
endfunction()
-run_compiler_launcher(C)
-run_compiler_launcher(CXX)
-if (NOT RunCMake_GENERATOR STREQUAL "Watcom WMake")
- run_compiler_launcher(C-launch)
- run_compiler_launcher(CXX-launch)
+set(langs C CXX)
+if(CMake_TEST_CUDA)
+ list(APPEND langs CUDA)
endif()
+
+foreach(lang ${langs})
+ run_compiler_launcher(${lang})
+ if (NOT RunCMake_GENERATOR STREQUAL "Watcom WMake")
+ run_compiler_launcher(${lang}-launch)
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/CompilerLauncher/main.cu b/Tests/RunCMake/CompilerLauncher/main.cu
new file mode 100644
index 000000000..f8b643afb
--- /dev/null
+++ b/Tests/RunCMake/CompilerLauncher/main.cu
@@ -0,0 +1,4 @@
+int main()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/Cppcheck/C-Build-stdout.txt b/Tests/RunCMake/Cppcheck/C-Build-stdout.txt
new file mode 100644
index 000000000..26eded30e
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/C-Build-stdout.txt
@@ -0,0 +1 @@
+.*Warning: cppcheck reported diagnostics.*error.*warning.*style.*performance.*information.*
diff --git a/Tests/RunCMake/Cppcheck/C-bad-Build-result.txt b/Tests/RunCMake/Cppcheck/C-bad-Build-result.txt
new file mode 100644
index 000000000..573541ac9
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/C-bad-Build-result.txt
@@ -0,0 +1 @@
+0
diff --git a/Tests/RunCMake/Cppcheck/C-bad-Build-stdout.txt b/Tests/RunCMake/Cppcheck/C-bad-Build-stdout.txt
new file mode 100644
index 000000000..2370ce1c1
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/C-bad-Build-stdout.txt
@@ -0,0 +1,2 @@
+stdout from bad command line arg '-bad'
+stderr from bad command line arg '-bad'
diff --git a/Tests/RunCMake/Cppcheck/C-bad.cmake b/Tests/RunCMake/Cppcheck/C-bad.cmake
new file mode 100644
index 000000000..920e4b4bc
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/C-bad.cmake
@@ -0,0 +1,3 @@
+enable_language(C)
+set(CMAKE_C_CPPCHECK "${PSEUDO_CPPCHECK}" -bad)
+add_executable(main main.c)
diff --git a/Tests/RunCMake/Cppcheck/C-launch-Build-stdout.txt b/Tests/RunCMake/Cppcheck/C-launch-Build-stdout.txt
new file mode 100644
index 000000000..26eded30e
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/C-launch-Build-stdout.txt
@@ -0,0 +1 @@
+.*Warning: cppcheck reported diagnostics.*error.*warning.*style.*performance.*information.*
diff --git a/Tests/RunCMake/Cppcheck/C-launch.cmake b/Tests/RunCMake/Cppcheck/C-launch.cmake
new file mode 100644
index 000000000..e66ca203e
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/C-launch.cmake
@@ -0,0 +1,3 @@
+set(CTEST_USE_LAUNCHERS 1)
+include(CTestUseLaunchers)
+include(C.cmake)
diff --git a/Tests/RunCMake/Cppcheck/C.cmake b/Tests/RunCMake/Cppcheck/C.cmake
new file mode 100644
index 000000000..b1f5bf789
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/C.cmake
@@ -0,0 +1,4 @@
+
+enable_language(C)
+set(CMAKE_C_CPPCHECK "${PSEUDO_CPPCHECK}")
+add_executable(main main.c)
diff --git a/Tests/RunCMake/Cppcheck/CMakeLists.txt b/Tests/RunCMake/Cppcheck/CMakeLists.txt
new file mode 100644
index 000000000..a640c569e
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.7)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/Cppcheck/CXX-Build-stdout.txt b/Tests/RunCMake/Cppcheck/CXX-Build-stdout.txt
new file mode 100644
index 000000000..26eded30e
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/CXX-Build-stdout.txt
@@ -0,0 +1 @@
+.*Warning: cppcheck reported diagnostics.*error.*warning.*style.*performance.*information.*
diff --git a/Tests/RunCMake/Cppcheck/CXX-launch-Build-stdout.txt b/Tests/RunCMake/Cppcheck/CXX-launch-Build-stdout.txt
new file mode 100644
index 000000000..26eded30e
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/CXX-launch-Build-stdout.txt
@@ -0,0 +1 @@
+.*Warning: cppcheck reported diagnostics.*error.*warning.*style.*performance.*information.*
diff --git a/Tests/RunCMake/Cppcheck/CXX-launch.cmake b/Tests/RunCMake/Cppcheck/CXX-launch.cmake
new file mode 100644
index 000000000..3002c9d68
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/CXX-launch.cmake
@@ -0,0 +1,3 @@
+set(CTEST_USE_LAUNCHERS 1)
+include(CTestUseLaunchers)
+include(CXX.cmake)
diff --git a/Tests/RunCMake/Cppcheck/CXX.cmake b/Tests/RunCMake/Cppcheck/CXX.cmake
new file mode 100644
index 000000000..3b7947127
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/CXX.cmake
@@ -0,0 +1,3 @@
+enable_language(CXX)
+set(CMAKE_CXX_CPPCHECK "${PSEUDO_CPPCHECK}")
+add_executable(main main.cxx)
diff --git a/Tests/RunCMake/Cppcheck/RunCMakeTest.cmake b/Tests/RunCMake/Cppcheck/RunCMakeTest.cmake
new file mode 100644
index 000000000..5fd4ead13
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/RunCMakeTest.cmake
@@ -0,0 +1,23 @@
+include(RunCMake)
+
+set(RunCMake_TEST_OPTIONS "-DPSEUDO_CPPCHECK=${PSEUDO_CPPCHECK}")
+
+function(run_cppcheck lang)
+ # Use a single build tree for tests without cleaning.
+ set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/${lang}-build")
+ set(RunCMake_TEST_NO_CLEAN 1)
+ file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+ file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+ run_cmake(${lang})
+ set(RunCMake_TEST_OUTPUT_MERGE 1)
+ run_cmake_command(${lang}-Build ${CMAKE_COMMAND} --build .)
+endfunction()
+
+run_cppcheck(C)
+run_cppcheck(CXX)
+run_cppcheck(C-bad)
+
+if(NOT RunCMake_GENERATOR STREQUAL "Watcom WMake")
+ run_cppcheck(C-launch)
+ run_cppcheck(CXX-launch)
+endif()
diff --git a/Tests/RunCMake/Cppcheck/main.c b/Tests/RunCMake/Cppcheck/main.c
new file mode 100644
index 000000000..8488f4e58
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/main.c
@@ -0,0 +1,4 @@
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/Cppcheck/main.cxx b/Tests/RunCMake/Cppcheck/main.cxx
new file mode 100644
index 000000000..f8b643afb
--- /dev/null
+++ b/Tests/RunCMake/Cppcheck/main.cxx
@@ -0,0 +1,4 @@
+int main()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/ExternalProject/MultiCommand-build-stdout.txt b/Tests/RunCMake/ExternalProject/MultiCommand-build-stdout.txt
new file mode 100644
index 000000000..30ebc7dcc
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/MultiCommand-build-stdout.txt
@@ -0,0 +1,15 @@
+.* *download 1
+.* *download 2
+.* *update 1
+.* *update 2
+.* *patch 1
+.* *patch 2
+.* *configure 1
+.* *configure 2
+.* *build 1
+.* *build 2
+.* *install 1
+.* *install 2
+.* *test 1
+.* *test 2
+.*
diff --git a/Tests/RunCMake/ExternalProject/MultiCommand.cmake b/Tests/RunCMake/ExternalProject/MultiCommand.cmake
new file mode 100644
index 000000000..a8dbfea5d
--- /dev/null
+++ b/Tests/RunCMake/ExternalProject/MultiCommand.cmake
@@ -0,0 +1,30 @@
+cmake_minimum_required(VERSION 3.9)
+
+include(ExternalProject)
+
+# Verify COMMAND keyword is recognised after various *_COMMAND options
+ExternalProject_Add(multiCommand
+ DOWNLOAD_COMMAND "${CMAKE_COMMAND}" -E echo "download 1"
+ COMMAND "${CMAKE_COMMAND}" -E echo "download 2"
+ UPDATE_COMMAND "${CMAKE_COMMAND}" -E echo "update 1"
+ COMMAND "${CMAKE_COMMAND}" -E echo "update 2"
+ PATCH_COMMAND "${CMAKE_COMMAND}" -E echo "patch 1"
+ COMMAND "${CMAKE_COMMAND}" -E echo "patch 2"
+ CONFIGURE_COMMAND "${CMAKE_COMMAND}" -E echo "configure 1"
+ COMMAND "${CMAKE_COMMAND}" -E echo "configure 2"
+ BUILD_COMMAND "${CMAKE_COMMAND}" -E echo "build 1"
+ COMMAND "${CMAKE_COMMAND}" -E echo "build 2"
+ TEST_COMMAND "${CMAKE_COMMAND}" -E echo "test 1"
+ COMMAND "${CMAKE_COMMAND}" -E echo "test 2"
+ INSTALL_COMMAND "${CMAKE_COMMAND}" -E echo "install 1"
+ COMMAND "${CMAKE_COMMAND}" -E echo "install 2"
+)
+
+# Workaround for issue 17229 (missing dependency between update and patch steps)
+ExternalProject_Add_StepTargets(multiCommand NO_DEPENDS update)
+ExternalProject_Add_StepDependencies(multiCommand patch multiCommand-update)
+
+# Force all steps to be re-run by removing timestamps from any previous run
+ExternalProject_Get_Property(multiCommand STAMP_DIR)
+file(REMOVE_RECURSE "${STAMP_DIR}")
+file(MAKE_DIRECTORY "${STAMP_DIR}")
diff --git a/Tests/RunCMake/ExternalProject/NoOptions-stderr.txt b/Tests/RunCMake/ExternalProject/NoOptions-stderr.txt
index 12a76c5d4..2fc7d291b 100644
--- a/Tests/RunCMake/ExternalProject/NoOptions-stderr.txt
+++ b/Tests/RunCMake/ExternalProject/NoOptions-stderr.txt
@@ -6,12 +6,12 @@
is not an existing non-empty directory. Please specify one of:
\* SOURCE_DIR with an existing non-empty directory
+ \* DOWNLOAD_COMMAND
\* URL
\* GIT_REPOSITORY
+ \* SVN_REPOSITORY
\* HG_REPOSITORY
\* CVS_REPOSITORY and CVS_MODULE
- \* SVN_REVISION
- \* DOWNLOAD_COMMAND
Call Stack \(most recent call first\):
.*/Modules/ExternalProject.cmake:[0-9]+ \(_ep_add_download_command\)
NoOptions.cmake:[0-9]+ \(ExternalProject_Add\)
diff --git a/Tests/RunCMake/ExternalProject/RunCMakeTest.cmake b/Tests/RunCMake/ExternalProject/RunCMakeTest.cmake
index 47d612969..994e2aa90 100644
--- a/Tests/RunCMake/ExternalProject/RunCMakeTest.cmake
+++ b/Tests/RunCMake/ExternalProject/RunCMakeTest.cmake
@@ -12,3 +12,13 @@ run_cmake(Add_StepDependencies_iface)
run_cmake(Add_StepDependencies_iface_step)
run_cmake(Add_StepDependencies_no_target)
run_cmake(UsesTerminal)
+
+# Run both cmake and build steps. We always do a clean before the
+# build to ensure that the download step re-runs each time.
+set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/MultiCommand-build)
+set(RunCMake_TEST_NO_CLEAN 1)
+file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+run_cmake(MultiCommand)
+run_cmake_command(MultiCommand-clean ${CMAKE_COMMAND} --build . --target clean)
+run_cmake_command(MultiCommand-build ${CMAKE_COMMAND} --build .)
diff --git a/Tests/RunCMake/ExternalProject/SourceEmpty-stderr.txt b/Tests/RunCMake/ExternalProject/SourceEmpty-stderr.txt
index 58a343ccf..07c6e8798 100644
--- a/Tests/RunCMake/ExternalProject/SourceEmpty-stderr.txt
+++ b/Tests/RunCMake/ExternalProject/SourceEmpty-stderr.txt
@@ -6,12 +6,12 @@
is not an existing non-empty directory. Please specify one of:
\* SOURCE_DIR with an existing non-empty directory
+ \* DOWNLOAD_COMMAND
\* URL
\* GIT_REPOSITORY
+ \* SVN_REPOSITORY
\* HG_REPOSITORY
\* CVS_REPOSITORY and CVS_MODULE
- \* SVN_REVISION
- \* DOWNLOAD_COMMAND
Call Stack \(most recent call first\):
.*/Modules/ExternalProject.cmake:[0-9]+ \(_ep_add_download_command\)
SourceEmpty.cmake:[0-9]+ \(ExternalProject_Add\)
diff --git a/Tests/RunCMake/ExternalProject/SourceMissing-stderr.txt b/Tests/RunCMake/ExternalProject/SourceMissing-stderr.txt
index e62f7cf5a..373f6e3aa 100644
--- a/Tests/RunCMake/ExternalProject/SourceMissing-stderr.txt
+++ b/Tests/RunCMake/ExternalProject/SourceMissing-stderr.txt
@@ -6,12 +6,12 @@
is not an existing non-empty directory. Please specify one of:
\* SOURCE_DIR with an existing non-empty directory
+ \* DOWNLOAD_COMMAND
\* URL
\* GIT_REPOSITORY
+ \* SVN_REPOSITORY
\* HG_REPOSITORY
\* CVS_REPOSITORY and CVS_MODULE
- \* SVN_REVISION
- \* DOWNLOAD_COMMAND
Call Stack \(most recent call first\):
.*/Modules/ExternalProject.cmake:[0-9]+ \(_ep_add_download_command\)
SourceMissing.cmake:[0-9]+ \(ExternalProject_Add\)
diff --git a/Tests/RunCMake/FPHSA/FindPseudoNoVersionVar.cmake b/Tests/RunCMake/FPHSA/FindPseudoNoVersionVar.cmake
new file mode 100644
index 000000000..d961c6489
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/FindPseudoNoVersionVar.cmake
@@ -0,0 +1,6 @@
+# pseudo find_module without specifying VERSION_VAR
+
+set(FOOBAR TRUE)
+
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(PseudoNoVersionVar REQUIRED_VARS FOOBAR)
diff --git a/Tests/RunCMake/FPHSA/RunCMakeTest.cmake b/Tests/RunCMake/FPHSA/RunCMakeTest.cmake
index e9b2a7a70..dd73cd487 100644
--- a/Tests/RunCMake/FPHSA/RunCMakeTest.cmake
+++ b/Tests/RunCMake/FPHSA/RunCMakeTest.cmake
@@ -4,7 +4,18 @@ run_cmake(BadFoundVar)
# The pseudo module will "find" a package with the given version. Check if the
# version selection code in FPHSA works correctly.
-set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" "-DPseudo_VERSION=1.2.3.4.5")
+
+# Find a package with version 0.
+set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" "-DPseudo_VERSION=0")
+run_cmake(any_version_find_0)
+
+# Find a package with more customary version number, without requesting a specific version and in
+# the presence of a cache variable VERSION.
+set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" "-DPseudoNoVersionVar_VERSION=1.2.3.4_SHOULD_BE_IGNORED" "-DVERSION=BAD_VERSION")
+run_cmake(any_version_VERSION_cache_variable)
+
+# Find a package with a more customary version number, without requesting a specific version.
+set(RunCMake_TEST_OPTIONS "-DCMAKE_MODULE_PATH=${CMAKE_CURRENT_LIST_DIR}" "-DPseudo_VERSION=1.2.3.4")
run_cmake(any_version)
# test EXACT mode with every subcomponent
diff --git a/Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable-stdout.txt b/Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable-stdout.txt
new file mode 100644
index 000000000..f9acece45
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable-stdout.txt
@@ -0,0 +1,2 @@
+Found PseudoNoVersionVar: TRUE *
++
diff --git a/Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable.cmake b/Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable.cmake
new file mode 100644
index 000000000..9f278979b
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/any_version_VERSION_cache_variable.cmake
@@ -0,0 +1 @@
+find_package(PseudoNoVersionVar REQUIRED)
diff --git a/Tests/RunCMake/FPHSA/any_version_find_0-stdout.txt b/Tests/RunCMake/FPHSA/any_version_find_0-stdout.txt
new file mode 100644
index 000000000..861a33987
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/any_version_find_0-stdout.txt
@@ -0,0 +1,2 @@
+Found Pseudo: [^
+]*\(found version "0\"\)
diff --git a/Tests/RunCMake/FPHSA/any_version_find_0.cmake b/Tests/RunCMake/FPHSA/any_version_find_0.cmake
new file mode 100644
index 000000000..b34a540c9
--- /dev/null
+++ b/Tests/RunCMake/FPHSA/any_version_find_0.cmake
@@ -0,0 +1 @@
+find_package(Pseudo REQUIRED)
diff --git a/Tests/RunCMake/File_Generate/CMP0070-NEW-check.cmake b/Tests/RunCMake/File_Generate/CMP0070-NEW-check.cmake
new file mode 100644
index 000000000..05ec26eed
--- /dev/null
+++ b/Tests/RunCMake/File_Generate/CMP0070-NEW-check.cmake
@@ -0,0 +1,13 @@
+foreach(f
+ "${RunCMake_TEST_SOURCE_DIR}/relative-input-NEW.txt"
+ "${RunCMake_TEST_BINARY_DIR}/relative-output-NEW.txt"
+ )
+ if(EXISTS "${f}")
+ file(READ "${f}" content)
+ if(NOT content MATCHES "^relative-input-NEW[\r\n]*$")
+ string(APPEND RunCMake_TEST_FAILED "File\n ${f}\ndoes not have expected content.\n")
+ endif()
+ else()
+ string(APPEND RunCMake_TEST_FAILED "Missing\n ${f}\n")
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/File_Generate/CMP0070-NEW.cmake b/Tests/RunCMake/File_Generate/CMP0070-NEW.cmake
new file mode 100644
index 000000000..1a0382221
--- /dev/null
+++ b/Tests/RunCMake/File_Generate/CMP0070-NEW.cmake
@@ -0,0 +1,2 @@
+cmake_policy(SET CMP0070 NEW)
+file(GENERATE OUTPUT relative-output-NEW.txt INPUT relative-input-NEW.txt)
diff --git a/Tests/RunCMake/File_Generate/CMP0070-OLD-check.cmake b/Tests/RunCMake/File_Generate/CMP0070-OLD-check.cmake
new file mode 100644
index 000000000..a71d822bb
--- /dev/null
+++ b/Tests/RunCMake/File_Generate/CMP0070-OLD-check.cmake
@@ -0,0 +1,13 @@
+foreach(f
+ "${RunCMake_TEST_BINARY_DIR}/relative-input-OLD.txt"
+ "${RunCMake_TEST_BINARY_DIR}/relative-output-OLD.txt"
+ )
+ if(EXISTS "${f}")
+ file(READ "${f}" content)
+ if(NOT content MATCHES "^relative-input-OLD[\r\n]*$")
+ string(APPEND RunCMake_TEST_FAILED "File\n ${f}\ndoes not have expected content.\n")
+ endif()
+ else()
+ string(APPEND RunCMake_TEST_FAILED "Missing\n ${f}\n")
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/File_Generate/CMP0070-OLD.cmake b/Tests/RunCMake/File_Generate/CMP0070-OLD.cmake
new file mode 100644
index 000000000..0fb47cdfa
--- /dev/null
+++ b/Tests/RunCMake/File_Generate/CMP0070-OLD.cmake
@@ -0,0 +1,3 @@
+cmake_policy(SET CMP0070 OLD)
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/relative-input-OLD.txt "relative-input-OLD\n")
+file(GENERATE OUTPUT relative-output-OLD.txt INPUT relative-input-OLD.txt)
diff --git a/Tests/RunCMake/File_Generate/CMP0070-WARN-check.cmake b/Tests/RunCMake/File_Generate/CMP0070-WARN-check.cmake
new file mode 100644
index 000000000..1488df09d
--- /dev/null
+++ b/Tests/RunCMake/File_Generate/CMP0070-WARN-check.cmake
@@ -0,0 +1,13 @@
+foreach(f
+ "${RunCMake_TEST_BINARY_DIR}/relative-input-WARN.txt"
+ "${RunCMake_TEST_BINARY_DIR}/relative-output-WARN.txt"
+ )
+ if(EXISTS "${f}")
+ file(READ "${f}" content)
+ if(NOT content MATCHES "^relative-input-WARN[\r\n]*$")
+ string(APPEND RunCMake_TEST_FAILED "File\n ${f}\ndoes not have expected content.\n")
+ endif()
+ else()
+ string(APPEND RunCMake_TEST_FAILED "Missing\n ${f}\n")
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/File_Generate/CMP0070-WARN-stderr.txt b/Tests/RunCMake/File_Generate/CMP0070-WARN-stderr.txt
new file mode 100644
index 000000000..dbabaa97b
--- /dev/null
+++ b/Tests/RunCMake/File_Generate/CMP0070-WARN-stderr.txt
@@ -0,0 +1,27 @@
+^CMake Warning \(dev\) in CMakeLists.txt:
+ Policy CMP0070 is not set: Define file\(GENERATE\) behavior for relative
+ paths. Run "cmake --help-policy CMP0070" for policy details. Use the
+ cmake_policy command to set the policy and suppress this warning.
+
+ file\(GENERATE\) given relative INPUT path:
+
+ relative-input-WARN.txt
+
+ This is not defined behavior unless CMP0070 is set to NEW. For
+ compatibility with older versions of CMake, the previous undefined behavior
+ will be used.
+This warning is for project developers. Use -Wno-dev to suppress it.(
++
+CMake Warning \(dev\) in CMakeLists.txt:
+ Policy CMP0070 is not set: Define file\(GENERATE\) behavior for relative
+ paths. Run "cmake --help-policy CMP0070" for policy details. Use the
+ cmake_policy command to set the policy and suppress this warning.
+
+ file\(GENERATE\) given relative OUTPUT path:
+
+ relative-output-WARN.txt
+
+ This is not defined behavior unless CMP0070 is set to NEW. For
+ compatibility with older versions of CMake, the previous undefined behavior
+ will be used.
+This warning is for project developers. Use -Wno-dev to suppress it.)+$
diff --git a/Tests/RunCMake/File_Generate/CMP0070-WARN.cmake b/Tests/RunCMake/File_Generate/CMP0070-WARN.cmake
new file mode 100644
index 000000000..ccb045231
--- /dev/null
+++ b/Tests/RunCMake/File_Generate/CMP0070-WARN.cmake
@@ -0,0 +1,2 @@
+file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/relative-input-WARN.txt "relative-input-WARN\n")
+file(GENERATE OUTPUT relative-output-WARN.txt INPUT relative-input-WARN.txt)
diff --git a/Tests/RunCMake/File_Generate/COMPILE_LANGUAGE-genex.cmake b/Tests/RunCMake/File_Generate/COMPILE_LANGUAGE-genex.cmake
index e2b081d48..59ccf197d 100644
--- a/Tests/RunCMake/File_Generate/COMPILE_LANGUAGE-genex.cmake
+++ b/Tests/RunCMake/File_Generate/COMPILE_LANGUAGE-genex.cmake
@@ -7,6 +7,6 @@ target_compile_options(empty
)
file(GENERATE
- OUTPUT opts-$<COMPILE_LANGUAGE>.txt
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/opts-$<COMPILE_LANGUAGE>.txt
CONTENT "$<TARGET_PROPERTY:empty,COMPILE_OPTIONS>\n"
)
diff --git a/Tests/RunCMake/File_Generate/ReRunCMake.cmake b/Tests/RunCMake/File_Generate/ReRunCMake.cmake
index 109d60e6f..541d86df2 100644
--- a/Tests/RunCMake/File_Generate/ReRunCMake.cmake
+++ b/Tests/RunCMake/File_Generate/ReRunCMake.cmake
@@ -1,5 +1,5 @@
file(GENERATE
- OUTPUT output_file.txt
+ OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/output_file.txt"
INPUT "${CMAKE_CURRENT_BINARY_DIR}/input_file.txt"
)
diff --git a/Tests/RunCMake/File_Generate/RunCMakeTest.cmake b/Tests/RunCMake/File_Generate/RunCMakeTest.cmake
index 82e903d82..b6604636a 100644
--- a/Tests/RunCMake/File_Generate/RunCMakeTest.cmake
+++ b/Tests/RunCMake/File_Generate/RunCMakeTest.cmake
@@ -1,5 +1,9 @@
include(RunCMake)
+run_cmake(CMP0070-NEW)
+run_cmake(CMP0070-OLD)
+run_cmake(CMP0070-WARN)
+
run_cmake(CommandConflict)
if("${RunCMake_GENERATOR}" MATCHES "Visual Studio|Xcode")
run_cmake(OutputConflict)
diff --git a/Tests/RunCMake/File_Generate/WriteIfDifferent.cmake b/Tests/RunCMake/File_Generate/WriteIfDifferent.cmake
index d1d832a11..bb36a4c48 100644
--- a/Tests/RunCMake/File_Generate/WriteIfDifferent.cmake
+++ b/Tests/RunCMake/File_Generate/WriteIfDifferent.cmake
@@ -1,5 +1,5 @@
file(GENERATE
- OUTPUT output_file.txt
+ OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/output_file.txt
CONTENT "123"
)
diff --git a/Tests/RunCMake/File_Generate/relative-input-NEW.txt b/Tests/RunCMake/File_Generate/relative-input-NEW.txt
new file mode 100644
index 000000000..7293e904a
--- /dev/null
+++ b/Tests/RunCMake/File_Generate/relative-input-NEW.txt
@@ -0,0 +1 @@
+relative-input-NEW
diff --git a/Tests/RunCMake/FindBoost/CMakeLists.txt b/Tests/RunCMake/FindBoost/CMakeLists.txt
new file mode 100644
index 000000000..d3137f614
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.9)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/FindBoost/CMakePackage-stdout.txt b/Tests/RunCMake/FindBoost/CMakePackage-stdout.txt
new file mode 100644
index 000000000..664e4a5f8
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage-stdout.txt
@@ -0,0 +1,3 @@
+-- Boost 1\.12345 found\.
+-- Found Boost components:
+ date_time
diff --git a/Tests/RunCMake/FindBoost/CMakePackage.cmake b/Tests/RunCMake/FindBoost/CMakePackage.cmake
new file mode 100644
index 000000000..06aeccb2d
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage.cmake
@@ -0,0 +1,2 @@
+set(Boost_DIR ${CMAKE_CURRENT_SOURCE_DIR}/CMakePackage)
+find_package(Boost 1.12345 COMPONENTS date_time)
diff --git a/Tests/RunCMake/FindBoost/CMakePackage/BoostConfig.cmake b/Tests/RunCMake/FindBoost/CMakePackage/BoostConfig.cmake
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage/BoostConfig.cmake
diff --git a/Tests/RunCMake/FindBoost/CMakePackage/BoostConfigVersion.cmake b/Tests/RunCMake/FindBoost/CMakePackage/BoostConfigVersion.cmake
new file mode 100644
index 000000000..8176ced19
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/CMakePackage/BoostConfigVersion.cmake
@@ -0,0 +1,7 @@
+set(PACKAGE_VERSION 1.12345)
+if(PACKAGE_FIND_VERSION_MAJOR EQUAL 1)
+ set(PACKAGE_VERSION_COMPATIBLE 1)
+ if(PACKAGE_FIND_VERSION_MINOR EQUAL 12345)
+ set(PACKAGE_VERSION_EXACT 1)
+ endif()
+endif()
diff --git a/Tests/RunCMake/FindBoost/RunCMakeTest.cmake b/Tests/RunCMake/FindBoost/RunCMakeTest.cmake
new file mode 100644
index 000000000..a153ae18f
--- /dev/null
+++ b/Tests/RunCMake/FindBoost/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake(CMakePackage)
diff --git a/Tests/RunCMake/FindPkgConfig/dummy-pkg-config.bat b/Tests/RunCMake/FindPkgConfig/dummy-pkg-config.bat
index b03837030..486977cbb 100755
--- a/Tests/RunCMake/FindPkgConfig/dummy-pkg-config.bat
+++ b/Tests/RunCMake/FindPkgConfig/dummy-pkg-config.bat
@@ -1,27 +1,27 @@
-@ECHO OFF
-
-:LOOP
-
-IF "%1"=="" (
- EXIT /B 255
-)
-
-IF "%1"=="--version" (
- ECHO 0.0-cmake-dummy
- EXIT /B 0
-)
-
-IF "%1"=="--exists" (
- SHIFT
- ECHO Expected: %*
- ECHO Found: %PKG_CONFIG_PATH%
- IF NOT "%*"=="%PKG_CONFIG_PATH%" (
- EXIT /B 1
- ) ELSE (
- EXIT /B 0
- )
-)
-SHIFT
-IF NOT "%~1"=="" GOTO LOOP
-
-EXIT /B 255
+@ECHO OFF
+
+:LOOP
+
+IF "%1"=="" (
+ EXIT /B 255
+)
+
+IF "%1"=="--version" (
+ ECHO 0.0-cmake-dummy
+ EXIT /B 0
+)
+
+IF "%1"=="--exists" (
+ SHIFT
+ ECHO Expected: %*
+ ECHO Found: %PKG_CONFIG_PATH%
+ IF NOT "%*"=="%PKG_CONFIG_PATH%" (
+ EXIT /B 1
+ ) ELSE (
+ EXIT /B 0
+ )
+)
+SHIFT
+IF NOT "%~1"=="" GOTO LOOP
+
+EXIT /B 255
diff --git a/Tests/RunCMake/Framework/FrameworkLayout.cmake b/Tests/RunCMake/Framework/FrameworkLayout.cmake
index 3d62a8af3..4f4245952 100644
--- a/Tests/RunCMake/Framework/FrameworkLayout.cmake
+++ b/Tests/RunCMake/Framework/FrameworkLayout.cmake
@@ -22,4 +22,4 @@ set_source_files_properties(some.txt PROPERTIES MACOSX_PACKAGE_LOCATION somedir)
add_custom_command(TARGET Framework POST_BUILD
COMMAND /usr/bin/file $<TARGET_FILE:Framework>)
-file(GENERATE OUTPUT FrameworkName.cmake CONTENT "set(framework-dir \"$<TARGET_BUNDLE_DIR:Framework>\")\n")
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/FrameworkName.cmake CONTENT "set(framework-dir \"$<TARGET_BUNDLE_DIR:Framework>\")\n")
diff --git a/Tests/RunCMake/Framework/FrameworkTypeSTATIC-build-stdout.txt b/Tests/RunCMake/Framework/FrameworkTypeSTATIC-build-stdout.txt
index 532cfedcc..4b5f761af 100644
--- a/Tests/RunCMake/Framework/FrameworkTypeSTATIC-build-stdout.txt
+++ b/Tests/RunCMake/Framework/FrameworkTypeSTATIC-build-stdout.txt
@@ -1,2 +1,2 @@
-.*/Framework:( Mach-O universal binary with [^
-]*)? current ar archive random library.*
+/Framework: (Mach-O universal binary with [^
+]*)?current ar archive random library
diff --git a/Tests/RunCMake/Framework/ios.cmake b/Tests/RunCMake/Framework/ios.cmake
index 209a50d39..446e9146a 100644
--- a/Tests/RunCMake/Framework/ios.cmake
+++ b/Tests/RunCMake/Framework/ios.cmake
@@ -20,6 +20,16 @@ execute_process(
OUTPUT_VARIABLE IOS_SDK_PATH
OUTPUT_STRIP_TRAILING_WHITESPACE)
+execute_process(
+ COMMAND ${XCRUN_EXECUTABLE} --sdk iphoneos --show-sdk-version
+ OUTPUT_VARIABLE IOS_SDK_VERSION
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+if(IOS_SDK_VERSION VERSION_GREATER_EQUAL 11.0)
+ set(IOS_ARCH arm64)
+else()
+ set(IOS_ARCH armv7)
+endif()
+
set(CMAKE_OSX_SYSROOT ${IOS_SDK_PATH} CACHE PATH "Sysroot used for iOS support")
-set(CMAKE_OSX_ARCHITECTURES "armv7" CACHE STRING "Architectures to build for")
+set(CMAKE_OSX_ARCHITECTURES "${IOS_ARCH}" CACHE STRING "Architectures to build for")
set(CMAKE_FIND_ROOT_PATH ${IOS_SDK_PATH} CACHE PATH "Find search path root")
diff --git a/Tests/RunCMake/GenerateExportHeader/GEH.cmake b/Tests/RunCMake/GenerateExportHeader/GEH.cmake
index e0677a7a3..cfca8fe01 100644
--- a/Tests/RunCMake/GenerateExportHeader/GEH.cmake
+++ b/Tests/RunCMake/GenerateExportHeader/GEH.cmake
@@ -45,13 +45,6 @@ include(GenerateExportHeader)
set(CMAKE_CXX_STANDARD 98)
-# Those versions of the HP compiler that need a flag to get proper C++98
-# template support also need a flag to use the newer C++ library.
-if (CMAKE_CXX_COMPILER_ID STREQUAL HP AND
- CMAKE_CXX98_STANDARD_COMPILE_OPTION STREQUAL "+hpxstd98")
- string(APPEND CMAKE_CXX_FLAGS " -AA")
-endif ()
-
# Clang/C2 in C++98 mode cannot properly handle some of MSVC headers
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND
CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC")
diff --git a/Tests/RunCMake/GenerateExportHeader/reference/.gitattributes b/Tests/RunCMake/GenerateExportHeader/reference/.gitattributes
deleted file mode 100644
index 883a7f16d..000000000
--- a/Tests/RunCMake/GenerateExportHeader/reference/.gitattributes
+++ /dev/null
@@ -1,2 +0,0 @@
-# Exclude reference content from formatting.
-* -format.clang-format
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_custom_command-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_custom_command-stderr.txt
index 789b4d09a..c8b124af3 100644
--- a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_custom_command-stderr.txt
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_custom_command-stderr.txt
@@ -3,8 +3,8 @@ CMake Error at COMPILE_LANGUAGE-add_custom_command.cmake:6 \(add_custom_command\
\$<COMPILE_LANGUAGE>
- \$<COMPILE_LANGUAGE:...> may only be used to specify include directories
- compile definitions, compile options and to evaluate components of the
+ \$<COMPILE_LANGUAGE:...> may only be used to specify include directories,
+ compile definitions, compile options, and to evaluate components of the
file\(GENERATE\) command.
Call Stack \(most recent call first\):
CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_custom_target-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_custom_target-stderr.txt
index 400fbc035..e8cefc72b 100644
--- a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_custom_target-stderr.txt
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_custom_target-stderr.txt
@@ -3,8 +3,8 @@ CMake Error at COMPILE_LANGUAGE-add_custom_target.cmake:4 \(add_custom_target\):
\$<COMPILE_LANGUAGE>
- \$<COMPILE_LANGUAGE:...> may only be used to specify include directories
- compile definitions, compile options and to evaluate components of the
+ \$<COMPILE_LANGUAGE:...> may only be used to specify include directories,
+ compile definitions, compile options, and to evaluate components of the
file\(GENERATE\) command.
Call Stack \(most recent call first\):
CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_executable-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_executable-stderr.txt
index e45bb020e..7fa1f2589 100644
--- a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_executable-stderr.txt
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_executable-stderr.txt
@@ -3,8 +3,8 @@ CMake Error at COMPILE_LANGUAGE-add_executable.cmake:4 \(add_executable\):
\$<COMPILE_LANGUAGE>
- \$<COMPILE_LANGUAGE:...> may only be used to specify include directories
- compile definitions, compile options and to evaluate components of the
+ \$<COMPILE_LANGUAGE:...> may only be used to specify include directories,
+ compile definitions, compile options, and to evaluate components of the
file\(GENERATE\) command.
Call Stack \(most recent call first\):
CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_library-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_library-stderr.txt
index c9ee6fe2a..ee60b5895 100644
--- a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_library-stderr.txt
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_library-stderr.txt
@@ -3,8 +3,8 @@ CMake Error at COMPILE_LANGUAGE-add_library.cmake:4 \(add_library\):
\$<COMPILE_LANGUAGE>
- \$<COMPILE_LANGUAGE:...> may only be used to specify include directories
- compile definitions, compile options and to evaluate components of the
+ \$<COMPILE_LANGUAGE:...> may only be used to specify include directories,
+ compile definitions, compile options, and to evaluate components of the
file\(GENERATE\) command.
Call Stack \(most recent call first\):
CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_test-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_test-stderr.txt
index 9955f5d91..fd8a731f1 100644
--- a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_test-stderr.txt
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-add_test-stderr.txt
@@ -3,8 +3,8 @@ CMake Error at COMPILE_LANGUAGE-add_test.cmake:5 \(add_test\):
\$<COMPILE_LANGUAGE>
- \$<COMPILE_LANGUAGE:...> may only be used to specify include directories
- compile definitions, compile options and to evaluate components of the
+ \$<COMPILE_LANGUAGE:...> may only be used to specify include directories,
+ compile definitions, compile options, and to evaluate components of the
file\(GENERATE\) command.
Call Stack \(most recent call first\):
CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-install-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-install-stderr.txt
index eca700f4d..bef7f63b9 100644
--- a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-install-stderr.txt
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-install-stderr.txt
@@ -3,6 +3,6 @@ CMake Error:
\$<COMPILE_LANGUAGE>
- \$<COMPILE_LANGUAGE:...> may only be used to specify include directories
- compile definitions, compile options and to evaluate components of the
+ \$<COMPILE_LANGUAGE:...> may only be used to specify include directories,
+ compile definitions, compile options, and to evaluate components of the
file\(GENERATE\) command.
diff --git a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-target_sources-stderr.txt b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-target_sources-stderr.txt
index 2d324e2ac..687d9b782 100644
--- a/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-target_sources-stderr.txt
+++ b/Tests/RunCMake/GeneratorExpression/COMPILE_LANGUAGE-target_sources-stderr.txt
@@ -3,8 +3,8 @@ CMake Error at COMPILE_LANGUAGE-target_sources.cmake:5 \(target_sources\):
\$<COMPILE_LANGUAGE>
- \$<COMPILE_LANGUAGE:...> may only be used to specify include directories
- compile definitions, compile options and to evaluate components of the
+ \$<COMPILE_LANGUAGE:...> may only be used to specify include directories,
+ compile definitions, compile options, and to evaluate components of the
file\(GENERATE\) command.
Call Stack \(most recent call first\):
CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-SOURCES.cmake b/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-SOURCES.cmake
index 89993ee09..dee7ead54 100644
--- a/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-SOURCES.cmake
+++ b/Tests/RunCMake/GeneratorExpression/TARGET_PROPERTY-SOURCES.cmake
@@ -1,5 +1,5 @@
+cmake_policy(SET CMP0070 NEW)
enable_language(C)
add_library(foo empty.c empty2.c)
target_sources(foo PRIVATE empty3.c)
-file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/foo.txt
- CONTENT "$<TARGET_PROPERTY:foo,SOURCES>")
+file(GENERATE OUTPUT foo.txt CONTENT "$<TARGET_PROPERTY:foo,SOURCES>")
diff --git a/Tests/RunCMake/GetPrerequisites/RunCMakeTest.cmake b/Tests/RunCMake/GetPrerequisites/RunCMakeTest.cmake
new file mode 100644
index 000000000..3856c54b6
--- /dev/null
+++ b/Tests/RunCMake/GetPrerequisites/RunCMakeTest.cmake
@@ -0,0 +1,3 @@
+include(RunCMake)
+
+run_cmake_command(TargetMissing ${CMAKE_COMMAND} -P ${RunCMake_SOURCE_DIR}/TargetMissing.cmake)
diff --git a/Tests/RunCMake/GetPrerequisites/TargetMissing-stderr.txt b/Tests/RunCMake/GetPrerequisites/TargetMissing-stderr.txt
new file mode 100644
index 000000000..cffe5f804
--- /dev/null
+++ b/Tests/RunCMake/GetPrerequisites/TargetMissing-stderr.txt
@@ -0,0 +1,3 @@
+^warning: target 'does_not_exist' is not absolute\.\.\.
+warning: target 'does_not_exist' does not exist\.\.\.
+result_var='value;before;call'$
diff --git a/Tests/RunCMake/GetPrerequisites/TargetMissing.cmake b/Tests/RunCMake/GetPrerequisites/TargetMissing.cmake
new file mode 100644
index 000000000..84fd32ce1
--- /dev/null
+++ b/Tests/RunCMake/GetPrerequisites/TargetMissing.cmake
@@ -0,0 +1,4 @@
+include(GetPrerequisites)
+set(result_var value before call)
+get_prerequisites(does_not_exist result_var 0 0 "" "")
+message("result_var='${result_var}'")
diff --git a/Tests/RunCMake/GoogleTest/CMakeLists.txt b/Tests/RunCMake/GoogleTest/CMakeLists.txt
new file mode 100644
index 000000000..dc9248697
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.6)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest-test-stdout.txt b/Tests/RunCMake/GoogleTest/GoogleTest-test-stdout.txt
new file mode 100644
index 000000000..5f7753dba
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest-test-stdout.txt
@@ -0,0 +1,25 @@
+Test project .*
+ Start 1: TEST:basic\.case_foo!1
+1/8 Test #1: TEST:basic\.case_foo!1 \.+ +Passed +[0-9.]+ sec
+ Start 2: TEST:basic\.case_bar!1
+2/8 Test #2: TEST:basic\.case_bar!1 \.+ +Passed +[0-9.]+ sec
+ Start 3: TEST:basic\.disabled_case!1
+3/8 Test #3: TEST:basic\.disabled_case!1 \.+\*+Not Run \(Disabled\) +[0-9.]+ sec
+ Start 4: TEST:disabled\.case!1
+4/8 Test #4: TEST:disabled\.case!1 \.+\*+Not Run \(Disabled\) +[0-9.]+ sec
+ Start 5: TEST:typed/short\.case!1
+5/8 Test #5: TEST:typed/short\.case!1 \.+ +Passed +[0-9.]+ sec
+ Start 6: TEST:typed/float\.case!1
+6/8 Test #6: TEST:typed/float\.case!1 \.+ +Passed +[0-9.]+ sec
+ Start 7: TEST:value/test\.case/1!1
+7/8 Test #7: TEST:value/test\.case/1!1 \.+ +Passed +[0-9.]+ sec
+ Start 8: TEST:value/test\.case/"foo"!1
+8/8 Test #8: TEST:value/test\.case/"foo"!1 \.+ +Passed +[0-9.]+ sec
+
+100% tests passed, 0 tests failed out of 6
+
+Total Test time \(real\) = +[0-9.]+ sec
+
+The following tests did not run:
+.*3 - TEST:basic\.disabled_case!1 \(Disabled\)
+.*4 - TEST:disabled\.case!1 \(Disabled\)
diff --git a/Tests/RunCMake/GoogleTest/GoogleTest.cmake b/Tests/RunCMake/GoogleTest/GoogleTest.cmake
new file mode 100644
index 000000000..9a3677fae
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/GoogleTest.cmake
@@ -0,0 +1,15 @@
+project(test_include_dirs)
+include(CTest)
+include(GoogleTest)
+
+enable_testing()
+
+add_executable(fake_gtest fake_gtest.cpp)
+
+gtest_discover_tests(
+ fake_gtest
+ TEST_PREFIX TEST:
+ TEST_SUFFIX !1
+ EXTRA_ARGS how now "\"brown\" cow"
+ PROPERTIES LABELS TEST
+)
diff --git a/Tests/RunCMake/GoogleTest/RunCMakeTest.cmake b/Tests/RunCMake/GoogleTest/RunCMakeTest.cmake
new file mode 100644
index 000000000..aec8568d0
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/RunCMakeTest.cmake
@@ -0,0 +1,26 @@
+include(RunCMake)
+
+function(run_GoogleTest)
+ # Use a single build tree for a few tests without cleaning.
+ set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/GoogleTest-build)
+ set(RunCMake_TEST_NO_CLEAN 1)
+ if(RunCMake_GENERATOR MATCHES "Make|Ninja")
+ set(RunCMake_TEST_OPTIONS -DCMAKE_BUILD_TYPE=Debug)
+ endif()
+ file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+ file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+ run_cmake(GoogleTest)
+ run_cmake_command(GoogleTest-build
+ ${CMAKE_COMMAND}
+ --build .
+ --config Debug
+ )
+ run_cmake_command(GoogleTest-test
+ ${CMAKE_CTEST_COMMAND}
+ -C Debug
+ -L TEST
+ --no-label-summary
+ )
+endfunction()
+
+run_GoogleTest()
diff --git a/Tests/RunCMake/GoogleTest/fake_gtest.cpp b/Tests/RunCMake/GoogleTest/fake_gtest.cpp
new file mode 100644
index 000000000..f1bd7efc8
--- /dev/null
+++ b/Tests/RunCMake/GoogleTest/fake_gtest.cpp
@@ -0,0 +1,41 @@
+#include <iostream>
+#include <string>
+
+int main(int argc, char** argv)
+{
+ // Note: GoogleTest.cmake doesn't actually depend on Google Test as such;
+ // 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.
+ 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 << "DISABLED_disabled." << 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;
+ return 0;
+ }
+
+ if (argc > 5) {
+ // Simple test of EXTRA_ARGS
+ if (std::string(argv[3]) == "how" && std::string(argv[4]) == "now" &&
+ std::string(argv[5]) == "\"brown\" cow") {
+ return 0;
+ }
+ }
+
+ // Print arguments for debugging, if we didn't get the expected arguments
+ for (int i = 1; i < argc; ++i) {
+ std::cerr << "arg[" << i << "]: '" << argv[i] << "'\n";
+ }
+
+ return 1;
+}
diff --git a/Tests/RunCMake/MultiLint/C-Build-stdout.txt b/Tests/RunCMake/MultiLint/C-Build-stdout.txt
new file mode 100644
index 000000000..d10427ea6
--- /dev/null
+++ b/Tests/RunCMake/MultiLint/C-Build-stdout.txt
@@ -0,0 +1,8 @@
+Warning: include-what-you-use reported diagnostics:
+should add these lines:
+*
+#include <\.\.\.>
++
+.*Tests[/\]RunCMake[/\]MultiLint[/\]main\.c:0:0: warning: message \[checker\].*
+Total errors found: 0
+.*Warning: cppcheck reported diagnostics.*error.*warning.*style.*performance.*information.*
diff --git a/Tests/RunCMake/MultiLint/C-launch-Build-stdout.txt b/Tests/RunCMake/MultiLint/C-launch-Build-stdout.txt
new file mode 100644
index 000000000..d10427ea6
--- /dev/null
+++ b/Tests/RunCMake/MultiLint/C-launch-Build-stdout.txt
@@ -0,0 +1,8 @@
+Warning: include-what-you-use reported diagnostics:
+should add these lines:
+*
+#include <\.\.\.>
++
+.*Tests[/\]RunCMake[/\]MultiLint[/\]main\.c:0:0: warning: message \[checker\].*
+Total errors found: 0
+.*Warning: cppcheck reported diagnostics.*error.*warning.*style.*performance.*information.*
diff --git a/Tests/RunCMake/MultiLint/C-launch.cmake b/Tests/RunCMake/MultiLint/C-launch.cmake
new file mode 100644
index 000000000..e66ca203e
--- /dev/null
+++ b/Tests/RunCMake/MultiLint/C-launch.cmake
@@ -0,0 +1,3 @@
+set(CTEST_USE_LAUNCHERS 1)
+include(CTestUseLaunchers)
+include(C.cmake)
diff --git a/Tests/RunCMake/MultiLint/C.cmake b/Tests/RunCMake/MultiLint/C.cmake
new file mode 100644
index 000000000..495d6f042
--- /dev/null
+++ b/Tests/RunCMake/MultiLint/C.cmake
@@ -0,0 +1,6 @@
+enable_language(C)
+set(CMAKE_C_INCLUDE_WHAT_YOU_USE "${PSEUDO_IWYU}" -some -args)
+set(CMAKE_C_CLANG_TIDY "${PSEUDO_TIDY}" -some -args)
+set(CMAKE_C_CPPLINT "${PSEUDO_CPPLINT}" --verbose=0 --linelength=80)
+set(CMAKE_C_CPPCHECK "${PSEUDO_CPPCHECK}")
+add_executable(main main.c)
diff --git a/Tests/RunCMake/MultiLint/CMakeLists.txt b/Tests/RunCMake/MultiLint/CMakeLists.txt
new file mode 100644
index 000000000..bf2ef1506
--- /dev/null
+++ b/Tests/RunCMake/MultiLint/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.10)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/MultiLint/CXX-Build-stdout.txt b/Tests/RunCMake/MultiLint/CXX-Build-stdout.txt
new file mode 100644
index 000000000..aaf5fd738
--- /dev/null
+++ b/Tests/RunCMake/MultiLint/CXX-Build-stdout.txt
@@ -0,0 +1,8 @@
+Warning: include-what-you-use reported diagnostics:
+should add these lines:
+*
+#include <\.\.\.>
++
+.*Tests[/\]RunCMake[/\]MultiLint[/\]main\.cxx:0:0: warning: message \[checker\].*
+Total errors found: 0
+.*Warning: cppcheck reported diagnostics.*error.*warning.*style.*performance.*information.*
diff --git a/Tests/RunCMake/MultiLint/CXX-launch-Build-stdout.txt b/Tests/RunCMake/MultiLint/CXX-launch-Build-stdout.txt
new file mode 100644
index 000000000..aaf5fd738
--- /dev/null
+++ b/Tests/RunCMake/MultiLint/CXX-launch-Build-stdout.txt
@@ -0,0 +1,8 @@
+Warning: include-what-you-use reported diagnostics:
+should add these lines:
+*
+#include <\.\.\.>
++
+.*Tests[/\]RunCMake[/\]MultiLint[/\]main\.cxx:0:0: warning: message \[checker\].*
+Total errors found: 0
+.*Warning: cppcheck reported diagnostics.*error.*warning.*style.*performance.*information.*
diff --git a/Tests/RunCMake/MultiLint/CXX-launch.cmake b/Tests/RunCMake/MultiLint/CXX-launch.cmake
new file mode 100644
index 000000000..3002c9d68
--- /dev/null
+++ b/Tests/RunCMake/MultiLint/CXX-launch.cmake
@@ -0,0 +1,3 @@
+set(CTEST_USE_LAUNCHERS 1)
+include(CTestUseLaunchers)
+include(CXX.cmake)
diff --git a/Tests/RunCMake/MultiLint/CXX.cmake b/Tests/RunCMake/MultiLint/CXX.cmake
new file mode 100644
index 000000000..dc30146a6
--- /dev/null
+++ b/Tests/RunCMake/MultiLint/CXX.cmake
@@ -0,0 +1,6 @@
+enable_language(CXX)
+set(CMAKE_CXX_INCLUDE_WHAT_YOU_USE "${PSEUDO_IWYU}" -some -args)
+set(CMAKE_CXX_CLANG_TIDY "${PSEUDO_TIDY}" -some -args)
+set(CMAKE_CXX_CPPLINT "${PSEUDO_CPPLINT}" --verbose=0 --linelength=80)
+set(CMAKE_CXX_CPPCHECK "${PSEUDO_CPPCHECK}")
+add_executable(main main.cxx)
diff --git a/Tests/RunCMake/MultiLint/RunCMakeTest.cmake b/Tests/RunCMake/MultiLint/RunCMakeTest.cmake
new file mode 100644
index 000000000..afd98fd08
--- /dev/null
+++ b/Tests/RunCMake/MultiLint/RunCMakeTest.cmake
@@ -0,0 +1,27 @@
+include(RunCMake)
+
+set(RunCMake_TEST_OPTIONS
+ "-DPSEUDO_CPPCHECK=${PSEUDO_CPPCHECK}"
+ "-DPSEUDO_CPPLINT=${PSEUDO_CPPLINT}"
+ "-DPSEUDO_IWYU=${PSEUDO_IWYU}"
+ "-DPSEUDO_TIDY=${PSEUDO_TIDY}"
+ )
+
+function(run_multilint lang)
+ # Use a single build tree for tests without cleaning.
+ set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/${lang}-build")
+ set(RunCMake_TEST_NO_CLEAN 1)
+ file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+ file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+ run_cmake(${lang})
+ set(RunCMake_TEST_OUTPUT_MERGE 1)
+ run_cmake_command(${lang}-Build ${CMAKE_COMMAND} --build .)
+endfunction()
+
+run_multilint(C)
+run_multilint(CXX)
+
+if(NOT RunCMake_GENERATOR STREQUAL "Watcom WMake")
+ run_multilint(C-launch)
+ run_multilint(CXX-launch)
+endif()
diff --git a/Tests/RunCMake/MultiLint/main.c b/Tests/RunCMake/MultiLint/main.c
new file mode 100644
index 000000000..8488f4e58
--- /dev/null
+++ b/Tests/RunCMake/MultiLint/main.c
@@ -0,0 +1,4 @@
+int main(void)
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/MultiLint/main.cxx b/Tests/RunCMake/MultiLint/main.cxx
new file mode 100644
index 000000000..f8b643afb
--- /dev/null
+++ b/Tests/RunCMake/MultiLint/main.cxx
@@ -0,0 +1,4 @@
+int main()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/README.rst b/Tests/RunCMake/README.rst
index 4aae4aed5..08b51d9c7 100644
--- a/Tests/RunCMake/README.rst
+++ b/Tests/RunCMake/README.rst
@@ -47,11 +47,11 @@ but do not actually build anything. To add a test:
containing expected test results:
``<SubTest>-result.txt``
- Process result expected if not "0"
+ Regex matching expected process result, if not ``0``
``<SubTest>-stdout.txt``
Regex matching expected stdout content
``<SubTest>-stderr.txt``
- Regex matching expected stderr content, if not "^$"
+ Regex matching expected stderr content, if not ``^$``
``<SubTest>-check.cmake``
Custom result check.
diff --git a/Tests/RunCMake/Syntax/.gitattributes b/Tests/RunCMake/Syntax/.gitattributes
deleted file mode 100644
index 35a9eaf2b..000000000
--- a/Tests/RunCMake/Syntax/.gitattributes
+++ /dev/null
@@ -1,3 +0,0 @@
-CommandTabs.cmake whitespace=-tab-in-indent
-StringCRLF.cmake whitespace=cr-at-eol -crlf
-BracketCRLF.cmake whitespace=cr-at-eol -crlf
diff --git a/Tests/RunCMake/Syntax/NullTerminatedArgument-result.txt b/Tests/RunCMake/Syntax/NullTerminatedArgument-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/Syntax/NullTerminatedArgument-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/Syntax/NullTerminatedArgument-stderr.txt b/Tests/RunCMake/Syntax/NullTerminatedArgument-stderr.txt
new file mode 100644
index 000000000..f26754e69
--- /dev/null
+++ b/Tests/RunCMake/Syntax/NullTerminatedArgument-stderr.txt
@@ -0,0 +1,5 @@
+CMake Error at NullTerminatedArgument.cmake:1:
+ Parse error. Function missing ending "\)". Instead found bad character
+ with text "".
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/Syntax/NullTerminatedArgument.cmake b/Tests/RunCMake/Syntax/NullTerminatedArgument.cmake
new file mode 100644
index 000000000..c82aceb53
--- /dev/null
+++ b/Tests/RunCMake/Syntax/NullTerminatedArgument.cmake
Binary files differ
diff --git a/Tests/RunCMake/Syntax/RunCMakeTest.cmake b/Tests/RunCMake/Syntax/RunCMakeTest.cmake
index d1fbb16aa..628df91cf 100644
--- a/Tests/RunCMake/Syntax/RunCMakeTest.cmake
+++ b/Tests/RunCMake/Syntax/RunCMakeTest.cmake
@@ -55,6 +55,7 @@ run_cmake(BracketNoSpace5)
run_cmake(Escape1)
run_cmake(Escape2)
run_cmake(EscapeCharsAllowed)
+run_cmake(NullTerminatedArgument)
include("${RunCMake_SOURCE_DIR}/EscapeCharsDisallowed.cmake")
run_cmake(ParenNoSpace0)
run_cmake(ParenNoSpace1)
diff --git a/Tests/RunCMake/TargetObjects/NoTarget.cmake b/Tests/RunCMake/TargetObjects/NoTarget.cmake
index 5d7e33e79..268577d50 100644
--- a/Tests/RunCMake/TargetObjects/NoTarget.cmake
+++ b/Tests/RunCMake/TargetObjects/NoTarget.cmake
@@ -1,7 +1,7 @@
add_library(iface INTERFACE)
target_sources(iface INTERFACE $<TARGET_OBJECTS:NoTarget>)
-file(GENERATE OUTPUT test_output CONTENT $<TARGET_OBJECTS:NoTarget>)
-file(GENERATE OUTPUT test_output2 CONTENT $<TARGET_PROPERTY:iface,INTERFACE_SOURCES>)
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/test_output CONTENT $<TARGET_OBJECTS:NoTarget>)
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/test_output2 CONTENT $<TARGET_PROPERTY:iface,INTERFACE_SOURCES>)
install(FILES $<TARGET_OBJECTS:NoTarget> DESTINATION objects)
diff --git a/Tests/RunCMake/TargetObjects/NotObjlibTarget.cmake b/Tests/RunCMake/TargetObjects/NotObjlibTarget.cmake
index 8e5fdd047..3bb3e374d 100644
--- a/Tests/RunCMake/TargetObjects/NotObjlibTarget.cmake
+++ b/Tests/RunCMake/TargetObjects/NotObjlibTarget.cmake
@@ -1,3 +1,3 @@
add_library(StaticLib empty.cpp)
-file(GENERATE OUTPUT test_output CONTENT $<TARGET_OBJECTS:StaticLib>)
+file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/test_output CONTENT $<TARGET_OBJECTS:StaticLib>)
diff --git a/Tests/RunCMake/VS10Project/RunCMakeTest.cmake b/Tests/RunCMake/VS10Project/RunCMakeTest.cmake
index 3af877f4f..6e7c2f313 100644
--- a/Tests/RunCMake/VS10Project/RunCMakeTest.cmake
+++ b/Tests/RunCMake/VS10Project/RunCMakeTest.cmake
@@ -4,3 +4,4 @@ run_cmake(VsTargetsFileReferences)
run_cmake(VsCustomProps)
run_cmake(VsDebuggerWorkingDir)
run_cmake(VsCSharpCustomTags)
+run_cmake(VsCSharpReferenceProps)
diff --git a/Tests/RunCMake/VS10Project/VsCSharpCustomTags-check.cmake b/Tests/RunCMake/VS10Project/VsCSharpCustomTags-check.cmake
index 70ea19326..9eb4619f4 100644
--- a/Tests/RunCMake/VS10Project/VsCSharpCustomTags-check.cmake
+++ b/Tests/RunCMake/VS10Project/VsCSharpCustomTags-check.cmake
@@ -4,20 +4,31 @@ if(NOT EXISTS "${csProjectFile}")
return()
endif()
-set(tagFound FALSE)
+# test VS_CSHARP_* for the following extensions
+set(fileExtensions
+ "cs"
+ "png"
+ "jpg"
+ "xml"
+ "settings")
+#
set(tagName "MyCustomTag")
set(tagValue "MyCustomValue")
file(STRINGS "${csProjectFile}" lines)
-foreach(line IN LISTS lines)
- if(line MATCHES "^ *<${tagName}>${tagValue}</${tagName}>")
- message(STATUS "foo.csproj has tag ${tagName} with value ${tagValue} defined")
- set(tagFound TRUE)
+
+foreach(e ${fileExtensions})
+ string(TOUPPER ${e} eUC)
+ set(tagFound FALSE)
+ foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<${tagName}${eUC}>${tagValue}${eUC}</${tagName}${eUC}>")
+ message(STATUS "foo.csproj has tag ${tagName}${eUC} with value ${tagValue}${eUC} defined")
+ set(tagFound TRUE)
+ endif()
+ endforeach()
+ if(NOT tagFound)
+ set(RunCMake_TEST_FAILED "Source file tag ${tagName}${eUC} with value ${tagValue}${eUC} not found.")
+ return()
endif()
endforeach()
-
-if(NOT tagFound)
- set(RunCMake_TEST_FAILED "Source file tag ${tagName} with value ${tagValue} not found.")
- return()
-endif()
diff --git a/Tests/RunCMake/VS10Project/VsCSharpCustomTags.cmake b/Tests/RunCMake/VS10Project/VsCSharpCustomTags.cmake
index c51e9c370..45766a07c 100644
--- a/Tests/RunCMake/VS10Project/VsCSharpCustomTags.cmake
+++ b/Tests/RunCMake/VS10Project/VsCSharpCustomTags.cmake
@@ -1,11 +1,27 @@
enable_language(CSharp)
-add_library(foo foo.cs)
-set(props_file "${CMAKE_CURRENT_SOURCE_DIR}/my.props")
+# test VS_CSHARP_* for the following extensions
+set(fileExtensions
+ "cs"
+ "png"
+ "jpg"
+ "xml"
+ "settings")
+#
set(tagName "MyCustomTag")
set(tagValue "MyCustomValue")
-set_source_files_properties(foo.cs
- PROPERTIES
- VS_CSHARP_${tagName} "${tagValue}")
+set(fileNames)
+foreach(e ${fileExtensions})
+ set(currentFile "${CMAKE_CURRENT_BINARY_DIR}/foo.${e}")
+ list(APPEND fileNames ${currentFile})
+ execute_process(COMMAND ${CMAKE_COMMAND} -E touch
+ "${currentFile}")
+ string(TOUPPER ${e} eUC)
+ set_source_files_properties("${currentFile}"
+ PROPERTIES
+ VS_CSHARP_${tagName}${eUC} "${tagValue}${eUC}")
+endforeach()
+
+add_library(foo ${fileNames})
diff --git a/Tests/RunCMake/VS10Project/VsCSharpReferenceProps-check.cmake b/Tests/RunCMake/VS10Project/VsCSharpReferenceProps-check.cmake
new file mode 100644
index 000000000..8b9bb6731
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpReferenceProps-check.cmake
@@ -0,0 +1,49 @@
+set(csProjectFile "${RunCMake_TEST_BINARY_DIR}/foo.csproj")
+if(NOT EXISTS "${csProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${csProjectFile} does not exist.")
+ return()
+endif()
+
+set(test1Reference "System")
+set(test1Tag "Hello")
+set(test1Value "World")
+
+set(test2Reference "foo2")
+set(test2Tag "Hallo")
+set(test2Value "Welt")
+
+set(tag1Found FALSE)
+set(ref1Found FALSE)
+
+file(STRINGS "${csProjectFile}" lines)
+
+foreach(i 1 2)
+ set(testReference "${test${i}Reference}")
+ set(testTag "${test${i}Tag}")
+ set(testValue "${test${i}Value}")
+ foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<(Project|)Reference .*>$")
+ set(validTag FALSE)
+ if(line MATCHES "^ *<(Project|)Reference .*\".*${testReference}.*\".*>$")
+ set(validTag TRUE)
+ message(STATUS "foo.csproj is using reference ${testReference}")
+ set(ref${i}Found TRUE)
+ endif()
+ endif()
+ if(line MATCHES "^ *<${testTag}>${testValue}</${testTag}>$")
+ if(validTag)
+ message(STATUS "foo.csproj reference ${testReference} has tag ${testTag}")
+ set(tag${i}Found TRUE)
+ else()
+ message(STATUS "tag ${testTag} found in wrong place!")
+ set(tag${i}Found FALSE)
+ endif()
+ endif()
+ endforeach()
+endforeach()
+
+if(NOT tag1Found OR NOT ref1Found OR
+ NOT tag2Found OR NOT ref2Found)
+ set(RunCMake_TEST_FAILED "Custom reference XML tag not found.")
+ return()
+endif()
diff --git a/Tests/RunCMake/VS10Project/VsCSharpReferenceProps.cmake b/Tests/RunCMake/VS10Project/VsCSharpReferenceProps.cmake
new file mode 100644
index 000000000..2af17569e
--- /dev/null
+++ b/Tests/RunCMake/VS10Project/VsCSharpReferenceProps.cmake
@@ -0,0 +1,19 @@
+enable_language(CSharp)
+add_library(foo foo.cs)
+add_library(foo2 foo.cs)
+
+set(test1Reference "System")
+set(test1Tag "Hello")
+set(test1Value "World")
+
+set(test2Reference "foo2")
+set(test2Tag "Hallo")
+set(test2Value "Welt")
+
+target_link_libraries(foo foo2)
+
+set_target_properties(foo PROPERTIES
+ VS_DOTNET_REFERENCES "${test1Reference};Blubb"
+ VS_DOTNET_REFERENCEPROP_${test1Reference}_TAG_${test1Tag} ${test1Value}
+ VS_DOTNET_REFERENCEPROP_${test2Reference}_TAG_${test2Tag} ${test2Value}
+ )
diff --git a/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake b/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake
index 5f4bdc30d..7d436b619 100644
--- a/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake
+++ b/Tests/RunCMake/XcodeProject/RunCMakeTest.cmake
@@ -1,5 +1,9 @@
include(RunCMake)
+if(XCODE_VERSION VERSION_GREATER_EQUAL 9)
+ set(IOS_DEPLOYMENT_TARGET "-DCMAKE_XCODE_ATTRIBUTE_IPHONEOS_DEPLOYMENT_TARGET=10")
+endif()
+
run_cmake(XcodeFileType)
run_cmake(XcodeAttributeLocation)
run_cmake(XcodeAttributeGenex)
@@ -20,7 +24,9 @@ run_cmake(PerConfigPerSourceFlags)
if(NOT XCODE_VERSION VERSION_LESS 5)
set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/XcodeInstallIOS-build)
set(RunCMake_TEST_NO_CLEAN 1)
- set(RunCMake_TEST_OPTIONS "-DCMAKE_INSTALL_PREFIX:PATH=${RunCMake_BINARY_DIR}/ios_install")
+ set(RunCMake_TEST_OPTIONS
+ "-DCMAKE_INSTALL_PREFIX:PATH=${RunCMake_BINARY_DIR}/ios_install"
+ "${IOS_DEPLOYMENT_TARGET}")
file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
@@ -53,7 +59,8 @@ if(NOT XCODE_VERSION VERSION_LESS 5)
set(RunCMake_TEST_NO_CLEAN 1)
set(RunCMake_TEST_OPTIONS
"-DTEST_IOS=ON"
- "-DCMAKE_INSTALL_PREFIX:PATH=${RunCMake_TEST_BINARY_DIR}/_install")
+ "-DCMAKE_INSTALL_PREFIX:PATH=${RunCMake_TEST_BINARY_DIR}/_install"
+ "${IOS_DEPLOYMENT_TARGET}")
file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
@@ -117,7 +124,8 @@ if(NOT XCODE_VERSION VERSION_LESS 6)
set(RunCMake_TEST_NO_CLEAN 1)
set(RunCMake_TEST_OPTIONS
"-DCMAKE_INSTALL_PREFIX:PATH=${RunCMake_TEST_BINARY_DIR}/_install"
- "-DCMAKE_IOS_INSTALL_COMBINED=YES")
+ "-DCMAKE_IOS_INSTALL_COMBINED=YES"
+ "${IOS_DEPLOYMENT_TARGET}")
file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
@@ -135,7 +143,8 @@ if(NOT XCODE_VERSION VERSION_LESS 6)
set(RunCMake_TEST_NO_CLEAN 1)
set(RunCMake_TEST_OPTIONS
"-DCMAKE_INSTALL_PREFIX:PATH=${RunCMake_TEST_BINARY_DIR}/_install"
- "-DCMAKE_IOS_INSTALL_COMBINED=YES")
+ "-DCMAKE_IOS_INSTALL_COMBINED=YES"
+ "${IOS_DEPLOYMENT_TARGET}")
file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
@@ -153,7 +162,8 @@ if(NOT XCODE_VERSION VERSION_LESS 6)
set(RunCMake_TEST_NO_CLEAN 1)
set(RunCMake_TEST_OPTIONS
"-DCMAKE_INSTALL_PREFIX:PATH=${RunCMake_TEST_BINARY_DIR}/_install"
- "-DCMAKE_IOS_INSTALL_COMBINED=YES")
+ "-DCMAKE_IOS_INSTALL_COMBINED=YES"
+ "${IOS_DEPLOYMENT_TARGET}")
file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
@@ -170,6 +180,7 @@ endif()
if(NOT XCODE_VERSION VERSION_LESS 5)
set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/XcodeMultiplatform-build)
set(RunCMake_TEST_NO_CLEAN 1)
+ set(RunCMake_TEST_OPTIONS "${IOS_DEPLOYMENT_TARGET}")
file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
diff --git a/Tests/RunCMake/add_custom_command/RemoveEmptyCommands-check.cmake b/Tests/RunCMake/add_custom_command/RemoveEmptyCommands-check.cmake
new file mode 100644
index 000000000..b2970444e
--- /dev/null
+++ b/Tests/RunCMake/add_custom_command/RemoveEmptyCommands-check.cmake
@@ -0,0 +1,63 @@
+set(vcProjectFile "${RunCMake_TEST_BINARY_DIR}/exe.vcxproj")
+if(NOT EXISTS "${vcProjectFile}")
+ set(RunCMake_TEST_FAILED "Project file ${vcProjectFile} does not exist.")
+ return()
+endif()
+
+set(inGroup FALSE)
+set(inCommand FALSE)
+
+set(expected_Debug
+ "cmd_1 cmd_1_arg"
+ "cmd_1_dbg cmd_1_dbg_arg"
+ "cmd_2_dbg cmd_2_dbg_arg"
+ "cmd_3_dbg cmd_3_dbg_arg")
+
+set(expected_Release
+ "cmd_1 cmd_1_arg"
+ "cmd_3_rel cmd_3_rel_arg")
+
+# extract build events
+file(STRINGS "${vcProjectFile}" lines)
+foreach(line IN LISTS lines)
+ if(line MATCHES "^ *<ItemDefinitionGroup Condition=.*Configuration.*Platform.*>$")
+ set(inGroup TRUE)
+ string(REGEX MATCH "=='(.*)\\|(.*)'" out ${line})
+ set(config ${CMAKE_MATCH_1})
+ elseif(line MATCHES "^ *</ItemDefinitionGroup>$")
+ set(inGroup FALSE)
+ elseif(inGroup)
+ if(line MATCHES "^ *<Command>.*$")
+ set(inCommand TRUE)
+ string(REGEX MATCH "<Command>(.*)" cmd ${line})
+ set(currentCommand ${CMAKE_MATCH_1})
+ elseif(line MATCHES "^(.*)</Command>$")
+ string(REGEX MATCH "(.*)</Command>" cmd ${line})
+ list(APPEND currentCommand ${CMAKE_MATCH_1})
+ set(command_${config} ${currentCommand})
+ set(inCommand FALSE)
+ elseif(inCommand)
+ list(APPEND currentCommand ${line})
+ endif()
+ endif()
+endforeach()
+
+foreach(config "Debug" "Release")
+ set(currentName command_${config})
+ set(expectedName expected_${config})
+ set(strippedCommand "")
+ if(DEFINED ${currentName})
+ foreach(v ${${currentName}})
+ if(${v} MATCHES "cmd_")
+ list(APPEND strippedCommand ${v})
+ endif()
+ endforeach()
+ if(NOT "${strippedCommand}" STREQUAL
+ "${${expectedName}}")
+ message(" - ${strippedCommand}")
+ message(" + ${${expectedName}}")
+ set(RunCMake_TEST_FAILED "build event command does not match")
+ return()
+ endif()
+ endif()
+endforeach()
diff --git a/Tests/RunCMake/add_custom_command/RemoveEmptyCommands.cmake b/Tests/RunCMake/add_custom_command/RemoveEmptyCommands.cmake
new file mode 100644
index 000000000..eb190cc99
--- /dev/null
+++ b/Tests/RunCMake/add_custom_command/RemoveEmptyCommands.cmake
@@ -0,0 +1,22 @@
+enable_language(CXX)
+
+# reduce number of configuration types
+set(CMAKE_CONFIGURATION_TYPES "Debug" "Release")
+
+set(main_file "${CMAKE_BINARY_DIR}/main.cpp")
+file(WRITE "${main_file}" "test")
+add_executable(exe "${main_file}")
+
+# add one command for all and one for debug only
+add_custom_command(TARGET exe
+ COMMAND "cmd_1" "cmd_1_arg"
+ COMMAND $<$<CONFIG:Debug>:cmd_1_dbg> $<$<CONFIG:Debug>:cmd_1_dbg_arg>)
+
+# add command for debug only
+add_custom_command(TARGET exe
+ COMMAND $<$<CONFIG:Debug>:cmd_2_dbg> $<$<CONFIG:Debug>:cmd_2_dbg_arg>)
+
+# add separate commands for configurations
+add_custom_command(TARGET exe
+ COMMAND $<$<CONFIG:Debug>:cmd_3_dbg> $<$<CONFIG:Debug>:cmd_3_dbg_arg>
+ COMMAND $<$<CONFIG:Release>:cmd_3_rel> $<$<CONFIG:Release>:cmd_3_rel_arg>)
diff --git a/Tests/RunCMake/add_custom_command/RunCMakeTest.cmake b/Tests/RunCMake/add_custom_command/RunCMakeTest.cmake
index 397c63d0a..c12e5aa6e 100644
--- a/Tests/RunCMake/add_custom_command/RunCMakeTest.cmake
+++ b/Tests/RunCMake/add_custom_command/RunCMakeTest.cmake
@@ -10,3 +10,7 @@ run_cmake(SourceByproducts)
run_cmake(SourceUsesTerminal)
run_cmake(TargetImported)
run_cmake(TargetNotInDir)
+
+if(${RunCMake_GENERATOR} MATCHES "Visual Studio ([^89]|[89][0-9])")
+ run_cmake(RemoveEmptyCommands)
+endif()
diff --git a/Tests/RunCMake/add_executable/CMakeLists.txt b/Tests/RunCMake/add_executable/CMakeLists.txt
new file mode 100644
index 000000000..ef2163c29
--- /dev/null
+++ b/Tests/RunCMake/add_executable/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.1)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/add_executable/NoSources-result.txt b/Tests/RunCMake/add_executable/NoSources-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_executable/NoSources-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_executable/NoSources-stderr.txt b/Tests/RunCMake/add_executable/NoSources-stderr.txt
new file mode 100644
index 000000000..598590595
--- /dev/null
+++ b/Tests/RunCMake/add_executable/NoSources-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at NoSources.cmake:[0-9]+ \(add_executable\):
+ add_executable called with incorrect number of arguments
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/add_executable/NoSources.cmake b/Tests/RunCMake/add_executable/NoSources.cmake
new file mode 100644
index 000000000..563564ad6
--- /dev/null
+++ b/Tests/RunCMake/add_executable/NoSources.cmake
@@ -0,0 +1 @@
+add_executable(TestExeWithoutSources)
diff --git a/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-result.txt b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-stderr.txt
new file mode 100644
index 000000000..c8afadb06
--- /dev/null
+++ b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects-stderr.txt
@@ -0,0 +1,11 @@
+^CMake Error at NoSourcesButLinkObjects.cmake:[0-9]+ \(add_executable\):
+ add_executable called with incorrect number of arguments
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
+
+
+CMake Error at NoSourcesButLinkObjects.cmake:[0-9]+ \(target_link_libraries\):
+ Cannot specify link libraries for target \"TestExeWithoutSources\" which is
+ not built by this project.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/add_executable/NoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects.cmake
new file mode 100644
index 000000000..d0f20934e
--- /dev/null
+++ b/Tests/RunCMake/add_executable/NoSourcesButLinkObjects.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_executable(TestExeWithoutSources)
+target_link_libraries(TestExeWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_executable/OnlyObjectSources-result.txt b/Tests/RunCMake/add_executable/OnlyObjectSources-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_executable/OnlyObjectSources-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_executable/OnlyObjectSources-stderr.txt b/Tests/RunCMake/add_executable/OnlyObjectSources-stderr.txt
new file mode 100644
index 000000000..ea72d5dea
--- /dev/null
+++ b/Tests/RunCMake/add_executable/OnlyObjectSources-stderr.txt
@@ -0,0 +1,11 @@
+^CMake Error at OnlyObjectSources.cmake:[0-9]+ \(add_executable\):
+ add_executable called with incorrect number of arguments
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
+
+
+CMake Error at OnlyObjectSources.cmake:[0-9]+ \(target_sources\):
+ Cannot specify sources for target \"TestExeWithoutSources\" which is not
+ built by this project.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/add_executable/OnlyObjectSources.cmake b/Tests/RunCMake/add_executable/OnlyObjectSources.cmake
new file mode 100644
index 000000000..1c90e9adc
--- /dev/null
+++ b/Tests/RunCMake/add_executable/OnlyObjectSources.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_executable(TestExeWithoutSources)
+target_sources(TestExeWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_executable/RunCMakeTest.cmake b/Tests/RunCMake/add_executable/RunCMakeTest.cmake
new file mode 100644
index 000000000..70a68f265
--- /dev/null
+++ b/Tests/RunCMake/add_executable/RunCMakeTest.cmake
@@ -0,0 +1,5 @@
+include(RunCMake)
+
+run_cmake(NoSources)
+run_cmake(OnlyObjectSources)
+run_cmake(NoSourcesButLinkObjects)
diff --git a/Tests/RunCMake/add_executable/test.cpp b/Tests/RunCMake/add_executable/test.cpp
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/add_executable/test.cpp
diff --git a/Tests/RunCMake/add_library/CMakeLists.txt b/Tests/RunCMake/add_library/CMakeLists.txt
new file mode 100644
index 000000000..ef2163c29
--- /dev/null
+++ b/Tests/RunCMake/add_library/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.1)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/add_library/INTERFACEwithNoSources.cmake b/Tests/RunCMake/add_library/INTERFACEwithNoSources.cmake
new file mode 100644
index 000000000..79188f387
--- /dev/null
+++ b/Tests/RunCMake/add_library/INTERFACEwithNoSources.cmake
@@ -0,0 +1 @@
+add_library(TestInterfaceLibWithoutSources INTERFACE)
diff --git a/Tests/RunCMake/add_library/INTERFACEwithNoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_library/INTERFACEwithNoSourcesButLinkObjects.cmake
new file mode 100644
index 000000000..53a48f0bd
--- /dev/null
+++ b/Tests/RunCMake/add_library/INTERFACEwithNoSourcesButLinkObjects.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_library(TestInterfaceLibWithoutSources INTERFACE)
+target_link_libraries(TestInterfaceLibWithoutSources INTERFACE $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_library/INTERFACEwithOnlyObjectSources.cmake b/Tests/RunCMake/add_library/INTERFACEwithOnlyObjectSources.cmake
new file mode 100644
index 000000000..86fab1dee
--- /dev/null
+++ b/Tests/RunCMake/add_library/INTERFACEwithOnlyObjectSources.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_library(TestInterfaceLibWithoutSources INTERFACE)
+target_sources(TestInterfaceLibWithoutSources INTERFACE $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_library/MODULEwithNoSources-result.txt b/Tests/RunCMake/add_library/MODULEwithNoSources-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_library/MODULEwithNoSources-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_library/MODULEwithNoSources-stderr.txt b/Tests/RunCMake/add_library/MODULEwithNoSources-stderr.txt
new file mode 100644
index 000000000..5cf0b1e8d
--- /dev/null
+++ b/Tests/RunCMake/add_library/MODULEwithNoSources-stderr.txt
@@ -0,0 +1,3 @@
+^You have called ADD_LIBRARY for library TestModuleLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file(
+CMake Error: CMake can not determine linker language for target: TestModuleLibWithoutSources)+(
+CMake Error: Cannot determine link language for target \"TestModuleLibWithoutSources\".)?$
diff --git a/Tests/RunCMake/add_library/MODULEwithNoSources.cmake b/Tests/RunCMake/add_library/MODULEwithNoSources.cmake
new file mode 100644
index 000000000..5df5033c6
--- /dev/null
+++ b/Tests/RunCMake/add_library/MODULEwithNoSources.cmake
@@ -0,0 +1 @@
+add_library(TestModuleLibWithoutSources MODULE)
diff --git a/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-result.txt b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-stderr.txt
new file mode 100644
index 000000000..951594a56
--- /dev/null
+++ b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects-stderr.txt
@@ -0,0 +1,3 @@
+^You have called ADD_LIBRARY for library TestModuleLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file(
+CMake Error: CMake can not determine linker language for target: TestModuleLibWithoutSources)+(
+CMake Error: Cannot determine link language for target \"TestModuleLibWithoutSources\".)*$
diff --git a/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects.cmake
new file mode 100644
index 000000000..f9d00dea8
--- /dev/null
+++ b/Tests/RunCMake/add_library/MODULEwithNoSourcesButLinkObjects.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_library(TestModuleLibWithoutSources MODULE)
+target_link_libraries(TestModuleLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_library/MODULEwithOnlyObjectSources-stderr.txt b/Tests/RunCMake/add_library/MODULEwithOnlyObjectSources-stderr.txt
new file mode 100644
index 000000000..de837554e
--- /dev/null
+++ b/Tests/RunCMake/add_library/MODULEwithOnlyObjectSources-stderr.txt
@@ -0,0 +1 @@
+^You have called ADD_LIBRARY for library TestModuleLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file$
diff --git a/Tests/RunCMake/add_library/MODULEwithOnlyObjectSources.cmake b/Tests/RunCMake/add_library/MODULEwithOnlyObjectSources.cmake
new file mode 100644
index 000000000..187481a14
--- /dev/null
+++ b/Tests/RunCMake/add_library/MODULEwithOnlyObjectSources.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_library(TestModuleLibWithoutSources MODULE)
+target_sources(TestModuleLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSources-result.txt b/Tests/RunCMake/add_library/OBJECTwithNoSources-result.txt
new file mode 100644
index 000000000..9c558e357
--- /dev/null
+++ b/Tests/RunCMake/add_library/OBJECTwithNoSources-result.txt
@@ -0,0 +1 @@
+.
diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSources-stderr.txt b/Tests/RunCMake/add_library/OBJECTwithNoSources-stderr.txt
new file mode 100644
index 000000000..099ec4fad
--- /dev/null
+++ b/Tests/RunCMake/add_library/OBJECTwithNoSources-stderr.txt
@@ -0,0 +1,2 @@
+^You have called ADD_LIBRARY for library TestObjectLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file(
+CMake Error: CMake can not determine linker language for target: TestObjectLibWithoutSources)*$
diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSources.cmake b/Tests/RunCMake/add_library/OBJECTwithNoSources.cmake
new file mode 100644
index 000000000..742e8299a
--- /dev/null
+++ b/Tests/RunCMake/add_library/OBJECTwithNoSources.cmake
@@ -0,0 +1 @@
+add_library(TestObjectLibWithoutSources OBJECT)
diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-result.txt b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-stderr.txt
new file mode 100644
index 000000000..8f2009616
--- /dev/null
+++ b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects-stderr.txt
@@ -0,0 +1,6 @@
+^You have called ADD_LIBRARY for library TestObjectLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file
+CMake Error at OBJECTwithNoSourcesButLinkObjects.cmake:[0-9]+ \(target_link_libraries\):
+ Object library target \"TestObjectLibWithoutSources\" may not link to
+ anything.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects.cmake
new file mode 100644
index 000000000..6b4b55fda
--- /dev/null
+++ b/Tests/RunCMake/add_library/OBJECTwithNoSourcesButLinkObjects.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_library(TestObjectLibWithoutSources OBJECT)
+target_link_libraries(TestObjectLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-result.txt b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-stderr.txt b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-stderr.txt
new file mode 100644
index 000000000..f9cbf6b7d
--- /dev/null
+++ b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources-stderr.txt
@@ -0,0 +1,17 @@
+^You have called ADD_LIBRARY for library TestObjectLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file
+CMake Error at OBJECTwithOnlyObjectSources.cmake:[0-9]+ \(add_library\):
+ OBJECT library \"TestObjectLibWithoutSources\" contains:
+
+ [^
+]*test(\.cpp)?\.o(bj)?
+
+ but may contain only sources that compile, header files, and other files
+ that would not affect linking of a normal library.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)
+
+
+CMake Error at OBJECTwithOnlyObjectSources.cmake:[0-9]+ \(add_library\):
+ Only executables and non-OBJECT libraries may reference target objects.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources.cmake b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources.cmake
new file mode 100644
index 000000000..ff75a8cb4
--- /dev/null
+++ b/Tests/RunCMake/add_library/OBJECTwithOnlyObjectSources.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_library(TestObjectLibWithoutSources OBJECT)
+target_sources(TestObjectLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_library/RunCMakeTest.cmake b/Tests/RunCMake/add_library/RunCMakeTest.cmake
new file mode 100644
index 000000000..0ba621606
--- /dev/null
+++ b/Tests/RunCMake/add_library/RunCMakeTest.cmake
@@ -0,0 +1,24 @@
+include(RunCMake)
+
+run_cmake(INTERFACEwithNoSources)
+run_cmake(OBJECTwithNoSources)
+run_cmake(STATICwithNoSources)
+run_cmake(SHAREDwithNoSources)
+run_cmake(MODULEwithNoSources)
+run_cmake(UNKNOWNwithNoSources)
+
+run_cmake(INTERFACEwithOnlyObjectSources)
+run_cmake(OBJECTwithOnlyObjectSources)
+run_cmake(STATICwithOnlyObjectSources)
+run_cmake(SHAREDwithOnlyObjectSources)
+run_cmake(MODULEwithOnlyObjectSources)
+run_cmake(UNKNOWNwithOnlyObjectSources)
+
+if(NOT RunCMake_GENERATOR STREQUAL "Xcode" OR NOT "$ENV{CMAKE_OSX_ARCHITECTURES}" MATCHES "[;$]")
+ run_cmake(INTERFACEwithNoSourcesButLinkObjects)
+ run_cmake(OBJECTwithNoSourcesButLinkObjects)
+ run_cmake(STATICwithNoSourcesButLinkObjects)
+ run_cmake(SHAREDwithNoSourcesButLinkObjects)
+ run_cmake(MODULEwithNoSourcesButLinkObjects)
+ run_cmake(UNKNOWNwithNoSourcesButLinkObjects)
+endif()
diff --git a/Tests/RunCMake/add_library/SHAREDwithNoSources-result.txt b/Tests/RunCMake/add_library/SHAREDwithNoSources-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_library/SHAREDwithNoSources-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_library/SHAREDwithNoSources-stderr.txt b/Tests/RunCMake/add_library/SHAREDwithNoSources-stderr.txt
new file mode 100644
index 000000000..228d1cc95
--- /dev/null
+++ b/Tests/RunCMake/add_library/SHAREDwithNoSources-stderr.txt
@@ -0,0 +1,3 @@
+^You have called ADD_LIBRARY for library TestSharedLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file(
+CMake Error: CMake can not determine linker language for target: TestSharedLibWithoutSources)+(
+CMake Error: Cannot determine link language for target \"TestSharedLibWithoutSources\".)*$
diff --git a/Tests/RunCMake/add_library/SHAREDwithNoSources.cmake b/Tests/RunCMake/add_library/SHAREDwithNoSources.cmake
new file mode 100644
index 000000000..e147b44bc
--- /dev/null
+++ b/Tests/RunCMake/add_library/SHAREDwithNoSources.cmake
@@ -0,0 +1 @@
+add_library(TestSharedLibWithoutSources SHARED)
diff --git a/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-result.txt b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-stderr.txt
new file mode 100644
index 000000000..228d1cc95
--- /dev/null
+++ b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects-stderr.txt
@@ -0,0 +1,3 @@
+^You have called ADD_LIBRARY for library TestSharedLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file(
+CMake Error: CMake can not determine linker language for target: TestSharedLibWithoutSources)+(
+CMake Error: Cannot determine link language for target \"TestSharedLibWithoutSources\".)*$
diff --git a/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects.cmake
new file mode 100644
index 000000000..5e3c2709d
--- /dev/null
+++ b/Tests/RunCMake/add_library/SHAREDwithNoSourcesButLinkObjects.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_library(TestSharedLibWithoutSources SHARED)
+target_link_libraries(TestSharedLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources-stderr.txt b/Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources-stderr.txt
new file mode 100644
index 000000000..ec350cd44
--- /dev/null
+++ b/Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources-stderr.txt
@@ -0,0 +1 @@
+^You have called ADD_LIBRARY for library TestSharedLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file$
diff --git a/Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources.cmake b/Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources.cmake
new file mode 100644
index 000000000..09281b00d
--- /dev/null
+++ b/Tests/RunCMake/add_library/SHAREDwithOnlyObjectSources.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_library(TestSharedLibWithoutSources SHARED)
+target_sources(TestSharedLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_library/STATICwithNoSources-result.txt b/Tests/RunCMake/add_library/STATICwithNoSources-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_library/STATICwithNoSources-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_library/STATICwithNoSources-stderr.txt b/Tests/RunCMake/add_library/STATICwithNoSources-stderr.txt
new file mode 100644
index 000000000..830eb221f
--- /dev/null
+++ b/Tests/RunCMake/add_library/STATICwithNoSources-stderr.txt
@@ -0,0 +1,3 @@
+^You have called ADD_LIBRARY for library TestStaticLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file(
+CMake Error: Cannot determine link language for target \"TestStaticLibWithoutSources\".)?(
+CMake Error: CMake can not determine linker language for target: TestStaticLibWithoutSources)+$
diff --git a/Tests/RunCMake/add_library/STATICwithNoSources.cmake b/Tests/RunCMake/add_library/STATICwithNoSources.cmake
new file mode 100644
index 000000000..94a2d9ab0
--- /dev/null
+++ b/Tests/RunCMake/add_library/STATICwithNoSources.cmake
@@ -0,0 +1 @@
+add_library(TestStaticLibWithoutSources STATIC)
diff --git a/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-result.txt b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-stderr.txt
new file mode 100644
index 000000000..830eb221f
--- /dev/null
+++ b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects-stderr.txt
@@ -0,0 +1,3 @@
+^You have called ADD_LIBRARY for library TestStaticLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file(
+CMake Error: Cannot determine link language for target \"TestStaticLibWithoutSources\".)?(
+CMake Error: CMake can not determine linker language for target: TestStaticLibWithoutSources)+$
diff --git a/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects.cmake
new file mode 100644
index 000000000..b6e137f3a
--- /dev/null
+++ b/Tests/RunCMake/add_library/STATICwithNoSourcesButLinkObjects.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_library(TestStaticLibWithoutSources STATIC)
+target_link_libraries(TestStaticLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_library/STATICwithOnlyObjectSources-stderr.txt b/Tests/RunCMake/add_library/STATICwithOnlyObjectSources-stderr.txt
new file mode 100644
index 000000000..5cd10d4fc
--- /dev/null
+++ b/Tests/RunCMake/add_library/STATICwithOnlyObjectSources-stderr.txt
@@ -0,0 +1 @@
+^You have called ADD_LIBRARY for library TestStaticLibWithoutSources without any source files. This typically indicates a problem with your CMakeLists.txt file$
diff --git a/Tests/RunCMake/add_library/STATICwithOnlyObjectSources.cmake b/Tests/RunCMake/add_library/STATICwithOnlyObjectSources.cmake
new file mode 100644
index 000000000..74a8947f2
--- /dev/null
+++ b/Tests/RunCMake/add_library/STATICwithOnlyObjectSources.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_library(TestStaticLibWithoutSources STATIC)
+target_sources(TestStaticLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_library/UNKNOWNwithNoSources.cmake b/Tests/RunCMake/add_library/UNKNOWNwithNoSources.cmake
new file mode 100644
index 000000000..dc5d7773b
--- /dev/null
+++ b/Tests/RunCMake/add_library/UNKNOWNwithNoSources.cmake
@@ -0,0 +1 @@
+add_library(TestUnknownLibWithoutSources UNKNOWN IMPORTED)
diff --git a/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-result.txt b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-stderr.txt b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-stderr.txt
new file mode 100644
index 000000000..adcd3a29e
--- /dev/null
+++ b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects-stderr.txt
@@ -0,0 +1,5 @@
+^CMake Error at UNKNOWNwithNoSourcesButLinkObjects.cmake:[0-9]+ \(target_link_libraries\):
+ Cannot specify link libraries for target \"TestUnknownLibWithoutSources\"
+ which is not built by this project.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects.cmake b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects.cmake
new file mode 100644
index 000000000..8e014c2b2
--- /dev/null
+++ b/Tests/RunCMake/add_library/UNKNOWNwithNoSourcesButLinkObjects.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_library(TestUnknownLibWithoutSources UNKNOWN IMPORTED)
+target_link_libraries(TestUnknownLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-result.txt b/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-stderr.txt b/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-stderr.txt
new file mode 100644
index 000000000..e332281d2
--- /dev/null
+++ b/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources-stderr.txt
@@ -0,0 +1,4 @@
+^CMake Error at UNKNOWNwithOnlyObjectSources.cmake:[0-9]+ \(target_sources\):
+ target_sources called with non-compilable target type
+Call Stack \(most recent call first\):
+ CMakeLists.txt:[0-9]+ \(include\)$
diff --git a/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources.cmake b/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources.cmake
new file mode 100644
index 000000000..604e339aa
--- /dev/null
+++ b/Tests/RunCMake/add_library/UNKNOWNwithOnlyObjectSources.cmake
@@ -0,0 +1,5 @@
+enable_language(CXX)
+add_library(ObjectLibDependency OBJECT test.cpp)
+
+add_library(TestUnknownLibWithoutSources UNKNOWN IMPORTED)
+target_sources(TestUnknownLibWithoutSources PUBLIC $<TARGET_OBJECTS:ObjectLibDependency>)
diff --git a/Tests/RunCMake/add_library/test.cpp b/Tests/RunCMake/add_library/test.cpp
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/Tests/RunCMake/add_library/test.cpp
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CMakeLists.txt.in b/Tests/RunCMake/ctest_labels_for_subprojects/CMakeLists.txt.in
new file mode 100644
index 000000000..30dd37e8e
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/CMakeLists.txt.in
@@ -0,0 +1,5 @@
+cmake_minimum_required(VERSION 3.9)
+@CASE_CMAKELISTS_PREFIX_CODE@
+project(CTestLabelsForSubprojects@CASE_NAME@ NONE)
+include(CTest)
+@CASE_CMAKELISTS_SUFFIX_CODE@
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfig.cmake.in b/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfig.cmake.in
new file mode 100644
index 000000000..1e1905b1b
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfig.cmake.in
@@ -0,0 +1,2 @@
+set(CTEST_PROJECT_NAME "CTestLabelsForSubprojects@CASE_NAME@")
+@CTEST_EXTRA_CONFIG@
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfigCTestScript-check.cmake b/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfigCTestScript-check.cmake
new file mode 100644
index 000000000..ea0585113
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfigCTestScript-check.cmake
@@ -0,0 +1,36 @@
+set(EXPERIMENTAL_FEATURE_REGEX "<Subproject name=\"MyExperimentalFeature\">.*<Label>MyExperimentalFeature</Label>.*</Subproject>")
+set(PRODUCTION_CODE_REGEX "<Subproject name=\"MyProductionCode\">.*<Label>MyProductionCode</Label>.*</Subproject>")
+set(SUBPROJECTS_REGEX "${EXPERIMENTAL_FEATURE_REGEX}.*${PRODUCTION_CODE_REGEX}")
+
+file(GLOB configure_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/Configure.xml")
+if(configure_xml_file)
+ file(READ "${configure_xml_file}" configure_xml)
+ if(NOT configure_xml MATCHES "${SUBPROJECTS_REGEX}.*<Configure>")
+ set(RunCMake_TEST_FAILED "Configure.xml does not contain the expected list of subprojects")
+ endif()
+else()
+ set(RunCMake_TEST_FAILED "Configure.xml not found")
+endif()
+
+file(GLOB build_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/Build.xml")
+if(build_xml_file)
+ file(READ "${build_xml_file}" build_xml)
+ set(BUILD_WARNING_REGEX "<Failure type=\"Warning\">.*<Labels>.*<Label>MyExperimentalFeature</Label>.*</Labels>")
+ if(NOT build_xml MATCHES "${SUBPROJECTS_REGEX}.*<Build>.*${BUILD_ERROR_REGEX}.*</Build>")
+ set(RunCMake_TEST_FAILED "Build.xml does not contain the expected list of subprojects and labels")
+ endif()
+else()
+ set(RunCMake_TEST_FAILED "Build.xml not found")
+endif()
+
+file(GLOB test_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/Test.xml")
+if(test_xml_file)
+ file(READ "${test_xml_file}" test_xml)
+ set(TEST_FAILED_REGEX "<Test Status=\"failed\">.*<Labels>.*<Label>MyExperimentalFeature</Label>.*<Label>NotASubproject</Label>.*</Labels>")
+ set(TEST_PASSED_REGEX "<Test Status=\"passed\">.*<Labels>.*<Label>MyProductionCode</Label>.*</Labels>")
+ if(NOT test_xml MATCHES "${SUBPROJECTS_REGEX}.*<Testing>.*${TEST_FAILED_REGEX}.*${TEST_PASSED_REGEX}.*${TEST_NOTRUN_REGEX}.*</Testing>")
+ set(RunCMake_TEST_FAILED "Test.xml does not contain the expected list of subprojects and labels")
+ endif()
+else()
+ set(RunCMake_TEST_FAILED "${CTEST_BINARY_DIRECTORY}/Testing/*/Test.xml not found")
+endif()
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfigCTestScript-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfigCTestScript-stdout.txt
new file mode 100644
index 000000000..05b484daa
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestConfigCTestScript-stdout.txt
@@ -0,0 +1,10 @@
+17% tests passed, 5 tests failed out of 6
++
+Subproject Time Summary:
+MyExperimentalFeature += +[0-9.]+ sec\*proc \(5 tests\)
+MyProductionCode += +[0-9.]+ sec\*proc \(1 test\)
++
+Label Time Summary:
+NotASubproject += +[0-9.]+ sec\*proc \(6 tests\)
++
+Total Test time \(real\) = +[0-9.]+ sec
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariable-check.cmake b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariable-check.cmake
new file mode 100644
index 000000000..ea0585113
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariable-check.cmake
@@ -0,0 +1,36 @@
+set(EXPERIMENTAL_FEATURE_REGEX "<Subproject name=\"MyExperimentalFeature\">.*<Label>MyExperimentalFeature</Label>.*</Subproject>")
+set(PRODUCTION_CODE_REGEX "<Subproject name=\"MyProductionCode\">.*<Label>MyProductionCode</Label>.*</Subproject>")
+set(SUBPROJECTS_REGEX "${EXPERIMENTAL_FEATURE_REGEX}.*${PRODUCTION_CODE_REGEX}")
+
+file(GLOB configure_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/Configure.xml")
+if(configure_xml_file)
+ file(READ "${configure_xml_file}" configure_xml)
+ if(NOT configure_xml MATCHES "${SUBPROJECTS_REGEX}.*<Configure>")
+ set(RunCMake_TEST_FAILED "Configure.xml does not contain the expected list of subprojects")
+ endif()
+else()
+ set(RunCMake_TEST_FAILED "Configure.xml not found")
+endif()
+
+file(GLOB build_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/Build.xml")
+if(build_xml_file)
+ file(READ "${build_xml_file}" build_xml)
+ set(BUILD_WARNING_REGEX "<Failure type=\"Warning\">.*<Labels>.*<Label>MyExperimentalFeature</Label>.*</Labels>")
+ if(NOT build_xml MATCHES "${SUBPROJECTS_REGEX}.*<Build>.*${BUILD_ERROR_REGEX}.*</Build>")
+ set(RunCMake_TEST_FAILED "Build.xml does not contain the expected list of subprojects and labels")
+ endif()
+else()
+ set(RunCMake_TEST_FAILED "Build.xml not found")
+endif()
+
+file(GLOB test_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/Test.xml")
+if(test_xml_file)
+ file(READ "${test_xml_file}" test_xml)
+ set(TEST_FAILED_REGEX "<Test Status=\"failed\">.*<Labels>.*<Label>MyExperimentalFeature</Label>.*<Label>NotASubproject</Label>.*</Labels>")
+ set(TEST_PASSED_REGEX "<Test Status=\"passed\">.*<Labels>.*<Label>MyProductionCode</Label>.*</Labels>")
+ if(NOT test_xml MATCHES "${SUBPROJECTS_REGEX}.*<Testing>.*${TEST_FAILED_REGEX}.*${TEST_PASSED_REGEX}.*${TEST_NOTRUN_REGEX}.*</Testing>")
+ set(RunCMake_TEST_FAILED "Test.xml does not contain the expected list of subprojects and labels")
+ endif()
+else()
+ set(RunCMake_TEST_FAILED "${CTEST_BINARY_DIRECTORY}/Testing/*/Test.xml not found")
+endif()
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariable-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariable-stdout.txt
new file mode 100644
index 000000000..05b484daa
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariable-stdout.txt
@@ -0,0 +1,10 @@
+17% tests passed, 5 tests failed out of 6
++
+Subproject Time Summary:
+MyExperimentalFeature += +[0-9.]+ sec\*proc \(5 tests\)
+MyProductionCode += +[0-9.]+ sec\*proc \(1 test\)
++
+Label Time Summary:
+NotASubproject += +[0-9.]+ sec\*proc \(6 tests\)
++
+Total Test time \(real\) = +[0-9.]+ sec
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-check.cmake b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-check.cmake
new file mode 100644
index 000000000..7beefba2f
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-check.cmake
@@ -0,0 +1,34 @@
+set(THIRD_PARTY_REGEX "<Subproject name=\"MyThirdPartyDependency\">.*<Label>MyThirdPartyDependency</Label>.*</Subproject>")
+set(SUBPROJECTS_REGEX "${THIRD_PARTY_REGEX}")
+
+file(GLOB configure_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/Configure.xml")
+if(configure_xml_file)
+ file(READ "${configure_xml_file}" configure_xml)
+ if(NOT configure_xml MATCHES "${SUBPROJECTS_REGEX}.*<Configure>")
+ set(RunCMake_TEST_FAILED "Configure.xml does not contain the expected list of subprojects")
+ endif()
+else()
+ set(RunCMake_TEST_FAILED "Configure.xml not found")
+endif()
+
+file(GLOB build_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/Build.xml")
+if(build_xml_file)
+ file(READ "${build_xml_file}" build_xml)
+ set(BUILD_ERROR_REGEX "<Failure type=\"Error\">.*<Labels>.*<Label>MyThirdPartyDependency</Label>.*<Label>NotASubproject</Label>.*</Labels>")
+ if(NOT build_xml MATCHES "${SUBPROJECTS_REGEX}.*<Build>.*${BUILD_ERROR_REGEX}.*</Build>")
+ set(RunCMake_TEST_FAILED "Build.xml does not contain the expected list of subprojects and labels")
+ endif()
+else()
+ set(RunCMake_TEST_FAILED "Build.xml not found")
+endif()
+
+file(GLOB test_xml_file "${RunCMake_TEST_BINARY_DIR}/Testing/*/Test.xml")
+if(test_xml_file)
+ file(READ "${test_xml_file}" test_xml)
+ set(TEST_NOTRUN_REGEX "<Test Status=\"notrun\">.*<Labels>.*<Label>MyThirdPartyDependency</Label>.*<Label>NotASubproject</Label>.*</Labels>")
+ if(NOT test_xml MATCHES "${SUBPROJECTS_REGEX}.*<Testing>.*${TEST_FAILED_REGEX}.*${TEST_PASSED_REGEX}.*${TEST_NOTRUN_REGEX}.*</Testing>")
+ set(RunCMake_TEST_FAILED "Test.xml does not contain the expected list of subprojects and labels")
+ endif()
+else()
+ set(RunCMake_TEST_FAILED "${CTEST_BINARY_DIRECTORY}/Testing/*/Test.xml not found")
+endif()
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-result.txt b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-result.txt
new file mode 100644
index 000000000..b57e2deb7
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-result.txt
@@ -0,0 +1 @@
+(-1|255)
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-stderr.txt b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-stderr.txt
new file mode 100644
index 000000000..38566fb2a
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-stderr.txt
@@ -0,0 +1 @@
+Unable to find executable:.*MyThirdPartyDependency/src/thirdparty
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-stdout.txt
new file mode 100644
index 000000000..c2c1bc7a0
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/CTestScriptVariableCommandLine-stdout.txt
@@ -0,0 +1,9 @@
+0% tests passed, 1 tests failed out of 1
++
+Subproject Time Summary:
+MyThirdPartyDependency += +[0-9.]+ sec\*proc \(1 test\)
++
+Label Time Summary:
+NotASubproject += +[0-9.]+ sec\*proc \(1 test\)
++
+Total Test time \(real\) = +[0-9.]+ sec
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-result.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-result.txt
new file mode 100644
index 000000000..45a4fb75d
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-result.txt
@@ -0,0 +1 @@
+8
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-stderr.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-stderr.txt
new file mode 100644
index 000000000..ba4235def
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-stderr.txt
@@ -0,0 +1 @@
+Errors while running CTest
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-stdout.txt
new file mode 100644
index 000000000..3567a92b8
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCMakeLists-stdout.txt
@@ -0,0 +1,6 @@
+50% tests passed, 1 tests failed out of 2
++
+Subproject Time Summary:
+MySubproject += +[0-9.]+ sec\*proc \(2 tests\)
++
+Total Test time \(real\) = +[0-9.]+ sec
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-result.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-result.txt
new file mode 100644
index 000000000..45a4fb75d
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-result.txt
@@ -0,0 +1 @@
+8
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-stderr.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-stderr.txt
new file mode 100644
index 000000000..ba4235def
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-stderr.txt
@@ -0,0 +1 @@
+Errors while running CTest
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-stdout.txt
new file mode 100644
index 000000000..3a7102247
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfig-stdout.txt
@@ -0,0 +1,9 @@
+67% tests passed, 1 tests failed out of 3
++
+Subproject Time Summary:
+MySubproject += +[0-9.]+ sec\*proc \(2 tests\)
++
+Label Time Summary:
+NotASubproject += +[0-9.]+ sec\*proc \(1 test\)
++
+Total Test time \(real\) = +[0-9.]+ sec
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-result.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-result.txt
new file mode 100644
index 000000000..45a4fb75d
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-result.txt
@@ -0,0 +1 @@
+8
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-stderr.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-stderr.txt
new file mode 100644
index 000000000..ba4235def
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-stderr.txt
@@ -0,0 +1 @@
+Errors while running CTest
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-stdout.txt
new file mode 100644
index 000000000..1146bfe39
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCTestConfigNoSummary-stdout.txt
@@ -0,0 +1,6 @@
+67% tests passed, 1 tests failed out of 3
++
+Label Time Summary:
+NotASubproject += +[0-9.]+ sec\*proc \(1 test\)
++
+Total Test time \(real\) = +[0-9.]+ sec
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-result.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-result.txt
new file mode 100644
index 000000000..45a4fb75d
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-result.txt
@@ -0,0 +1 @@
+8
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-stderr.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-stderr.txt
new file mode 100644
index 000000000..ba4235def
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-stderr.txt
@@ -0,0 +1 @@
+Errors while running CTest
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-stdout.txt b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-stdout.txt
new file mode 100644
index 000000000..3567a92b8
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/ModuleVariableCommandLine-stdout.txt
@@ -0,0 +1,6 @@
+50% tests passed, 1 tests failed out of 2
++
+Subproject Time Summary:
+MySubproject += +[0-9.]+ sec\*proc \(2 tests\)
++
+Total Test time \(real\) = +[0-9.]+ sec
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/MyExperimentalFeature/CMakeLists.txt b/Tests/RunCMake/ctest_labels_for_subprojects/MyExperimentalFeature/CMakeLists.txt
new file mode 100644
index 000000000..cc07a07f7
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/MyExperimentalFeature/CMakeLists.txt
@@ -0,0 +1,33 @@
+project(MyExperimentalFeature)
+cmake_minimum_required(VERSION 3.8)
+
+include(CTest)
+
+set(CMAKE_DIRECTORY_LABELS "MyExperimentalFeature;NotASubproject")
+
+add_executable(testapp experimental.c)
+
+add_test(experimentalFail1 testapp 5)
+set_tests_properties (experimentalFail1
+ PROPERTIES PASS_REGULAR_EXPRESSION "Test!"
+ )
+
+add_test(experimentalFail2 testapp -5)
+set_tests_properties (experimentalFail2
+ PROPERTIES PASS_REGULAR_EXPRESSION "Test!"
+ )
+
+add_test(experimentalFail3 testapp -5)
+set_tests_properties (experimentalFail3
+ PROPERTIES PASS_REGULAR_EXPRESSION "Test!"
+ )
+
+add_test(experimentalFail4 testapp -5)
+set_tests_properties (experimentalFail4
+ PROPERTIES PASS_REGULAR_EXPRESSION "Test!"
+ )
+
+add_test(experimentalFail5 testapp -5)
+set_tests_properties (experimentalFail5
+ PROPERTIES PASS_REGULAR_EXPRESSION "Test!"
+ )
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/MyExperimentalFeature/experimental.c b/Tests/RunCMake/ctest_labels_for_subprojects/MyExperimentalFeature/experimental.c
new file mode 100644
index 000000000..7cb11ae50
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/MyExperimentalFeature/experimental.c
@@ -0,0 +1,16 @@
+#include <stdio.h>
+
+int main(void)
+{
+ int i = 0;
+ if (i > 0) {
+ printf("This doesn't happen.\n");
+ printf("Neither does this.\n");
+ }
+ i = i + 1;
+ if (i > 0) {
+ printf("This does happen.\n");
+ }
+
+ return 0;
+}
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/MyProductionCode/CMakeLists.txt b/Tests/RunCMake/ctest_labels_for_subprojects/MyProductionCode/CMakeLists.txt
new file mode 100644
index 000000000..c2ee673ab
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/MyProductionCode/CMakeLists.txt
@@ -0,0 +1,12 @@
+project(MyProductionCode)
+cmake_minimum_required(VERSION 3.8)
+
+include(CTest)
+
+add_executable(production production.c)
+add_test(NAME production COMMAND production)
+
+set_property(TARGET production PROPERTY LABELS MyProductionCode)
+set_property(TEST production PROPERTY LABELS MyProductionCode)
+
+set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY LABELS "NotASubproject")
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/MyProductionCode/production.c b/Tests/RunCMake/ctest_labels_for_subprojects/MyProductionCode/production.c
new file mode 100644
index 000000000..54dc2bec0
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/MyProductionCode/production.c
@@ -0,0 +1,16 @@
+#include <stdio.h>
+
+int main(void)
+{
+ int j = 0;
+ if (j > 0) {
+ printf("This doesn't happen.\n");
+ printf("Neither does this.\n");
+ }
+ j = j + 1;
+ if (j > 0) {
+ printf("This does happen.\n");
+ }
+
+ return 0;
+}
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/MyThirdPartyDependency/CMakeLists.txt b/Tests/RunCMake/ctest_labels_for_subprojects/MyThirdPartyDependency/CMakeLists.txt
new file mode 100644
index 000000000..d5b9c2f22
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/MyThirdPartyDependency/CMakeLists.txt
@@ -0,0 +1,7 @@
+project(MyThirdPartyDependency)
+cmake_minimum_required(VERSION 3.8)
+
+include(CTest)
+
+set_directory_properties(PROPERTIES LABELS "NotASubproject;MyThirdPartyDependency")
+add_subdirectory(src)
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/MyThirdPartyDependency/src/CMakeLists.txt b/Tests/RunCMake/ctest_labels_for_subprojects/MyThirdPartyDependency/src/CMakeLists.txt
new file mode 100644
index 000000000..dc6cb2a57
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/MyThirdPartyDependency/src/CMakeLists.txt
@@ -0,0 +1,10 @@
+project(MyThirdPartyDependency)
+cmake_minimum_required(VERSION 3.8)
+
+include(CTest)
+
+add_executable(thirdparty thirdparty.c)
+add_test(NAME thirdparty COMMAND thirdparty)
+
+set_property(TARGET thirdparty PROPERTY LABELS NotASubproject)
+set_property(TEST thirdparty PROPERTY LABELS NotASubproject)
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/MyThirdPartyDependency/src/thirdparty.c b/Tests/RunCMake/ctest_labels_for_subprojects/MyThirdPartyDependency/src/thirdparty.c
new file mode 100644
index 000000000..babe82d2d
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/MyThirdPartyDependency/src/thirdparty.c
@@ -0,0 +1,14 @@
+#include <stdio.h>
+
+int main(void)
+{
+ printf(This function has an error!\n");
+ n = 5;
+ return 0;
+}
+
+int notcalled()
+{
+ printf(This function doesn't get called.\n");
+ return 0;
+}
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/RunCMakeTest.cmake b/Tests/RunCMake/ctest_labels_for_subprojects/RunCMakeTest.cmake
new file mode 100644
index 000000000..dbe7bf826
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/RunCMakeTest.cmake
@@ -0,0 +1,185 @@
+include(RunCTest)
+
+
+# 1. Specify subprojects in the CTest script
+function(run_CTestScriptVariable)
+ set(CTEST_EXTRA_CONFIG "set(CTEST_USE_LAUNCHERS 1)")
+ set(CASE_TEST_PREFIX_CODE [[
+file(COPY "${CTEST_RUNCMAKE_SOURCE_DIRECTORY}/MyProductionCode"
+ DESTINATION ${CTEST_SOURCE_DIRECTORY})
+file(COPY "${CTEST_RUNCMAKE_SOURCE_DIRECTORY}/MyExperimentalFeature"
+ DESTINATION ${CTEST_SOURCE_DIRECTORY})
+
+set(CTEST_LABELS_FOR_SUBPROJECTS "MyProductionCode;MyExperimentalFeature")
+ ]])
+ set(CASE_CMAKELISTS_SUFFIX_CODE [[
+add_subdirectory(MyExperimentalFeature)
+add_subdirectory(MyProductionCode)
+ ]])
+
+ run_ctest(CTestScriptVariable)
+
+ unset(CTEST_EXTRA_CONFIG)
+ unset(CASE_TEST_PREFIX_CODE)
+ unset(CASE_CMAKELISTS_SUFFIX_CODE)
+endfunction()
+run_CTestScriptVariable()
+
+# 2. Specify subprojects via a CTest script variable on the command line e.g.
+# ctest -S test.cmake -DCTEST_LABELS_FOR_SUBPROJECTS:STRING="MySubproject"
+# Note: This test includes a failing build
+function(run_CTestScriptVariableCommandLine)
+ set(CTEST_EXTRA_CONFIG "set(CTEST_USE_LAUNCHERS 1)")
+ set(CASE_TEST_PREFIX_CODE [[
+file(COPY "${CTEST_RUNCMAKE_SOURCE_DIRECTORY}/MyThirdPartyDependency"
+ DESTINATION ${CTEST_SOURCE_DIRECTORY})
+ ]])
+ set(CASE_CMAKELISTS_SUFFIX_CODE [[
+add_subdirectory(MyThirdPartyDependency)
+ ]])
+
+ run_ctest(CTestScriptVariableCommandLine "-DCTEST_LABELS_FOR_SUBPROJECTS:STRING=MyThirdPartyDependency")
+
+ unset(CTEST_EXTRA_CONFIG)
+ unset(CASE_TEST_PREFIX_CODE)
+ unset(CASE_CMAKELISTS_SUFFIX_CODE)
+endfunction()
+run_CTestScriptVariableCommandLine()
+
+# 3. Set subprojects via a CTest module variable on the command line
+# (will populate DartConfiguration.tcl)
+function(run_ModuleVariableCommandLine)
+ set(RunCMake_TEST_SOURCE_DIR "${RunCMake_BINARY_DIR}/ModuleVariableCommandLine")
+ set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/ModuleVariableCommandLine-build")
+ set(RunCMake_TEST_NO_CLEAN 1)
+ file(REMOVE_RECURSE "${RunCMake_TEST_SOURCE_DIR}")
+ file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+ file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+
+ set(CASE_CMAKELISTS_SUFFIX_CODE [[
+set(someFile "${CMAKE_CURRENT_SOURCE_DIR}/test.cmake")
+add_test(NAME SuccessfulTest COMMAND "${CMAKE_COMMAND}" --version)
+set_property(TEST SuccessfulTest PROPERTY LABELS MySubproject)
+add_test(NAME FailingTest
+ COMMAND ${CMAKE_COMMAND} -E compare_files "${someFile}" "${someFile}xxx")
+set_property(TEST FailingTest PROPERTY LABELS MySubproject)
+ ]])
+ configure_file(${RunCMake_SOURCE_DIR}/CMakeLists.txt.in
+ ${RunCMake_TEST_SOURCE_DIR}/CMakeLists.txt @ONLY)
+
+ set(RunCMake_TEST_OPTIONS "-DCTEST_LABELS_FOR_SUBPROJECTS:STRING=MySubproject")
+ run_cmake(ModuleVariableCommandLine-cmake)
+ unset(RunCMake_TEST_OPTIONS)
+ run_cmake_command(ModuleVariableCommandLine ${CMAKE_CTEST_COMMAND} -C Debug -V)
+
+ unset(RunCMake_TEST_SOURCE_DIR)
+ unset(RunCMake_TEST_BINARY_DIR)
+ unset(RunCMake_TEST_NO_CLEAN)
+ unset(CASE_CMAKELISTS_SUFFIX_CODE)
+endfunction()
+run_ModuleVariableCommandLine()
+
+# 4. Set subprojects via a CTest module variable in CMakeLists.txt
+# (will populate DartConfiguration.tcl)
+function(run_ModuleVariableCMakeLists)
+ set(RunCMake_TEST_SOURCE_DIR "${RunCMake_BINARY_DIR}/ModuleVariableCMakeLists")
+ set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/ModuleVariableCMakeLists-build")
+ set(RunCMake_TEST_NO_CLEAN 1)
+ file(REMOVE_RECURSE "${RunCMake_TEST_SOURCE_DIR}")
+ file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+ file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+
+ set(CASE_CMAKELISTS_PREFIX_CODE [[
+set(CTEST_LABELS_FOR_SUBPROJECTS MySubproject)
+]])
+
+ set(CASE_CMAKELISTS_SUFFIX_CODE [[
+set(someFile "${CMAKE_CURRENT_SOURCE_DIR}/test.cmake")
+add_test(NAME SuccessfulTest COMMAND "${CMAKE_COMMAND}" --version)
+set_property(TEST SuccessfulTest PROPERTY LABELS MySubproject)
+add_test(NAME FailingTest
+ COMMAND ${CMAKE_COMMAND} -E compare_files "${someFile}" "${someFile}xxx")
+set_property(TEST FailingTest PROPERTY LABELS MySubproject)
+ ]])
+ configure_file(${RunCMake_SOURCE_DIR}/CMakeLists.txt.in
+ ${RunCMake_TEST_SOURCE_DIR}/CMakeLists.txt @ONLY)
+
+ run_cmake(ModuleVariableCMakeLists-cmake)
+ run_cmake_command(ModuleVariableCMakeLists ${CMAKE_CTEST_COMMAND} -C Debug -V)
+
+ unset(RunCMake_TEST_SOURCE_DIR)
+ unset(RunCMake_TEST_BINARY_DIR)
+ unset(RunCMake_TEST_NO_CLEAN)
+ unset(CASE_CMAKELISTS_SUFFIX_CODE)
+ unset(CASE_CMAKELISTS_SUFFIX_CODE)
+endfunction()
+run_ModuleVariableCMakeLists()
+
+# The remaining tests set subprojects in CTestConfig.cmake. Settings in this
+# config file are shared by both the CTest module and the ctest command line
+# `Dashboard Client` mode (e.g. ctest -S).
+
+function(run_ModuleVariableCTestConfig CASE_NAME)
+ set(RunCMake_TEST_SOURCE_DIR "${RunCMake_BINARY_DIR}/${CASE_NAME}")
+ set(RunCMake_TEST_BINARY_DIR "${RunCMake_BINARY_DIR}/${CASE_NAME}-build")
+ set(RunCMake_TEST_NO_CLEAN 1)
+ file(REMOVE_RECURSE "${RunCMake_TEST_SOURCE_DIR}")
+ file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+ file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+
+ set(CTEST_EXTRA_CONFIG "set(CTEST_LABELS_FOR_SUBPROJECTS \"MySubproject\")")
+ configure_file(${RunCMake_SOURCE_DIR}/CTestConfig.cmake.in
+ ${RunCMake_TEST_SOURCE_DIR}/CTestConfig.cmake @ONLY)
+
+ set(CASE_CMAKELISTS_SUFFIX_CODE [[
+set(someFile "${CMAKE_CURRENT_SOURCE_DIR}/test.cmake")
+add_test(NAME SuccessfulTest COMMAND "${CMAKE_COMMAND}" --version)
+set_property(TEST SuccessfulTest PROPERTY LABELS MySubproject)
+add_test(NAME FailingTest
+ COMMAND ${CMAKE_COMMAND} -E compare_files "${someFile}" "${someFile}xxx")
+set_property(TEST FailingTest PROPERTY LABELS MySubproject)
+add_test(NAME AnotherSuccessfulTest COMMAND "${CMAKE_COMMAND}" --version)
+set_property(TEST AnotherSuccessfulTest PROPERTY LABELS NotASubproject)
+ ]])
+ configure_file(${RunCMake_SOURCE_DIR}/CMakeLists.txt.in
+ ${RunCMake_TEST_SOURCE_DIR}/CMakeLists.txt @ONLY)
+
+ run_cmake(${CASE_NAME}-cmake)
+ run_cmake_command(${CASE_NAME} ${CMAKE_CTEST_COMMAND} -C Debug -V ${ARGN})
+
+ unset(RunCMake_TEST_SOURCE_DIR)
+ unset(RunCMake_TEST_BINARY_DIR)
+ unset(RunCMake_TEST_NO_CLEAN)
+ unset(CTEST_EXTRA_CONFIG)
+ unset(CASE_CMAKELISTS_SUFFIX_CODE)
+endfunction()
+
+# 5. Check that the Subproject timing Summary is printed
+run_ModuleVariableCTestConfig(ModuleVariableCTestConfig)
+
+# 6. Use --no-subproject-summary to disable the Subproject timing summary.
+run_ModuleVariableCTestConfig(ModuleVariableCTestConfigNoSummary --no-subproject-summary)
+
+# 7. Verify that subprojects are sent to CDash when running a CTest script
+function(run_CTestConfigCTestScript)
+ set(CTEST_EXTRA_CONFIG [[
+set(CTEST_USE_LAUNCHERS 1)
+set(CTEST_LABELS_FOR_SUBPROJECTS "MyProductionCode;MyExperimentalFeature")
+ ]])
+ set(CASE_TEST_PREFIX_CODE [[
+file(COPY "${CTEST_RUNCMAKE_SOURCE_DIRECTORY}/MyProductionCode"
+ DESTINATION ${CTEST_SOURCE_DIRECTORY})
+file(COPY "${CTEST_RUNCMAKE_SOURCE_DIRECTORY}/MyExperimentalFeature"
+ DESTINATION ${CTEST_SOURCE_DIRECTORY})
+ ]])
+ set(CASE_CMAKELISTS_SUFFIX_CODE [[
+add_subdirectory(MyExperimentalFeature)
+add_subdirectory(MyProductionCode)
+ ]])
+ run_ctest(CTestConfigCTestScript)
+
+ unset(CTEST_EXTRA_CONFIG)
+ unset(CASE_TEST_PREFIX_CODE)
+ unset(CASE_CMAKELISTS_SUFFIX_CODE)
+endfunction()
+run_CTestConfigCTestScript()
diff --git a/Tests/RunCMake/ctest_labels_for_subprojects/test.cmake.in b/Tests/RunCMake/ctest_labels_for_subprojects/test.cmake.in
new file mode 100644
index 000000000..8cec08d46
--- /dev/null
+++ b/Tests/RunCMake/ctest_labels_for_subprojects/test.cmake.in
@@ -0,0 +1,21 @@
+cmake_minimum_required(VERSION 3.7)
+
+# Settings:
+
+set(CTEST_SITE "test-site")
+set(CTEST_BUILD_NAME "test-build-name")
+set(CTEST_SOURCE_DIRECTORY "@RunCMake_BINARY_DIR@/@CASE_NAME@")
+set(CTEST_BINARY_DIRECTORY "@RunCMake_BINARY_DIR@/@CASE_NAME@-build")
+set(CTEST_CMAKE_GENERATOR "@RunCMake_GENERATOR@")
+set(CTEST_CMAKE_GENERATOR_PLATFORM "@RunCMake_GENERATOR_PLATFORM@")
+set(CTEST_CMAKE_GENERATOR_TOOLSET "@RunCMake_GENERATOR_TOOLSET@")
+set(CTEST_BUILD_CONFIGURATION "$ENV{CMAKE_CONFIG_TYPE}")
+set(CTEST_RUNCMAKE_SOURCE_DIRECTORY "@RunCMake_SOURCE_DIR@")
+
+@CASE_TEST_PREFIX_CODE@
+
+set(ctest_test_args "@CASE_CTEST_TEST_ARGS@")
+ctest_start(Experimental)
+ctest_configure()
+ctest_build()
+ctest_test(${ctest_test_args})
diff --git a/Tests/RunCMake/ctest_skipped_test/skip.bat b/Tests/RunCMake/ctest_skipped_test/skip.bat
index 80e1290df..580f46018 100755
--- a/Tests/RunCMake/ctest_skipped_test/skip.bat
+++ b/Tests/RunCMake/ctest_skipped_test/skip.bat
@@ -1 +1 @@
-EXIT 125
+EXIT 125
diff --git a/Tests/RunCMake/execute_process/ExitValues-stdout.txt b/Tests/RunCMake/execute_process/ExitValues-stdout.txt
new file mode 100644
index 000000000..3bcaf46cc
--- /dev/null
+++ b/Tests/RunCMake/execute_process/ExitValues-stdout.txt
@@ -0,0 +1,14 @@
+^-- 1 - 1 RESULT_VARIABLE: 0
+-- 1 - 2 RESULT_VARIABLE: [^0].*
+-- 2 - 1 RESULT_VARIABLE: 0
+-- 2 - 1 RESULTS_VARIABLE: 0
+-- 2 - 2 RESULT_VARIABLE: [^0].*
+-- 2 - 2 RESULTS_VARIABLE: [^0].*
+-- 3 - 1 RESULTS_VARIABLE: 0
+-- 3 - 2 RESULTS_VARIABLE: [^0].*
+-- 4 - 1 RESULT_VARIABLE: 0
+-- 4 - 1 RESULTS_VARIABLE: [^0].*;0;[^0].*;0;[^0].*;0
+-- 4 - 1 RESULTS_VARIABLE_LENGTH: 6
+-- 5 - 1 RESULT_VARIABLE: [^0].*
+-- 5 - 1 RESULTS_VARIABLE: 0;0;[^0].*
+-- 5 - 1 RESULTS_VARIABLE_LENGTH: 3$
diff --git a/Tests/RunCMake/execute_process/ExitValues.cmake b/Tests/RunCMake/execute_process/ExitValues.cmake
new file mode 100644
index 000000000..d80a57b2d
--- /dev/null
+++ b/Tests/RunCMake/execute_process/ExitValues.cmake
@@ -0,0 +1,120 @@
+#1st TEST RESULT_VARIABLE ONLY
+execute_process(COMMAND ${EXIT_CODE_EXE} "zero_exit"
+ RESULT_VARIABLE r0
+ )
+message(STATUS " 1 - 1 RESULT_VARIABLE: ${r0}")
+if(NOT r0 EQUAL 0)
+ message(FATAL_ERROR "zero exit code expected")
+endif()
+execute_process(COMMAND ${EXIT_CODE_EXE} "non_zero_exit"
+ RESULT_VARIABLE r01
+ ERROR_QUIET
+ )
+message(STATUS " 1 - 2 RESULT_VARIABLE: ${r01}")
+if(r01 EQUAL 0)
+ message(FATAL_ERROR "non-zero exit code expected")
+endif()
+#2nd TEST RESULT_VARIABLE and RESULTS_VARIABLE
+execute_process(COMMAND ${EXIT_CODE_EXE} "zero_exit"
+ RESULT_VARIABLE r1
+ RESULTS_VARIABLE r1s
+ )
+message(STATUS " 2 - 1 RESULT_VARIABLE: ${r1}")
+message(STATUS " 2 - 1 RESULTS_VARIABLE: ${r1s}")
+if(NOT r1 EQUAL 0 OR NOT r1s EQUAL 0)
+ message(FATAL_ERROR "zero exit code expected")
+endif()
+execute_process(COMMAND ${EXIT_CODE_EXE} "non_zero_exit"
+ RESULT_VARIABLE r11
+ RESULTS_VARIABLE r11s
+ ERROR_QUIET
+ )
+message(STATUS " 2 - 2 RESULT_VARIABLE: ${r11}")
+message(STATUS " 2 - 2 RESULTS_VARIABLE: ${r11s}")
+if(r11 EQUAL 0 OR r11s EQUAL 0)
+ message(FATAL_ERROR "non-zero exit code expected")
+endif()
+#3rd TEST RESULTS_VARIABLE
+execute_process(COMMAND ${EXIT_CODE_EXE} "zero_exit"
+ RESULTS_VARIABLE r2s
+ )
+message(STATUS " 3 - 1 RESULTS_VARIABLE: ${r2s}")
+if(NOT r2s EQUAL 0)
+ message(FATAL_ERROR "zero exit code expected")
+endif()
+execute_process(COMMAND ${EXIT_CODE_EXE} "non_zero_exit"
+ RESULTS_VARIABLE r21s
+ ERROR_QUIET
+ )
+message(STATUS " 3 - 2 RESULTS_VARIABLE: ${r21s}")
+if(r21s EQUAL 0)
+ message(FATAL_ERROR "non-zero exit code expected")
+endif()
+#4th TEST RESULT_VARIABLE and RESULTS_VARIABLE WITH MULTICOMMAND
+execute_process(COMMAND ${EXIT_CODE_EXE} "non_zero_exit"
+ COMMAND ${EXIT_CODE_EXE} "zero_exit"
+ COMMAND ${EXIT_CODE_EXE} "non_zero_exit"
+ COMMAND ${EXIT_CODE_EXE} "zero_exit"
+ COMMAND ${EXIT_CODE_EXE} "non_zero_exit"
+ COMMAND ${EXIT_CODE_EXE} "zero_exit"
+ RESULT_VARIABLE r31
+ RESULTS_VARIABLE r31s
+ OUTPUT_QUIET
+ ERROR_QUIET
+ )
+message(STATUS " 4 - 1 RESULT_VARIABLE: ${r31}")
+message(STATUS " 4 - 1 RESULTS_VARIABLE: ${r31s}")
+if(NOT r31 EQUAL 0)
+ message(FATAL_ERROR "zero exit code expected for last command")
+endif()
+list(LENGTH r31s r31sLen)
+message(STATUS " 4 - 1 RESULTS_VARIABLE_LENGTH: ${r31sLen}")
+if(NOT r31sLen EQUAL 6)
+ message(FATAL_ERROR "length of RESULTS_VARIABLE is not as expected")
+else()
+ foreach(loop_var RANGE 5)
+ list(GET r31s ${loop_var} rsLocal)
+ math(EXPR isOdd "${loop_var} % 2")
+ if(isOdd)
+ if(NOT rsLocal EQUAL 0)
+ message(FATAL_ERROR "zero exit code expected")
+ endif()
+ else()
+ if(rsLocal EQUAL 0)
+ message(FATAL_ERROR "non-zero exit code expected")
+ endif()
+ endif()
+ endforeach()
+endif()
+#5th TEST RESULT_VARIABLE and RESULTS_VARIABLE WITH MULTICOMMAND
+execute_process(COMMAND ${EXIT_CODE_EXE} "zero_exit"
+ COMMAND ${EXIT_CODE_EXE} "zero_exit"
+ COMMAND ${EXIT_CODE_EXE} "non_zero_exit"
+ RESULT_VARIABLE r41
+ RESULTS_VARIABLE r41s
+ OUTPUT_QUIET
+ ERROR_QUIET
+ )
+message(STATUS " 5 - 1 RESULT_VARIABLE: ${r41}")
+message(STATUS " 5 - 1 RESULTS_VARIABLE: ${r41s}")
+if(r41 EQUAL 0)
+ message(FATAL_ERROR "non-zero exit code expected for last command")
+endif()
+list(LENGTH r41s r41sLen)
+message(STATUS " 5 - 1 RESULTS_VARIABLE_LENGTH: ${r41sLen}")
+if(NOT r31sLen EQUAL 6)
+ message(FATAL_ERROR "length of RESULTS_VARIABLE is not as expected")
+else()
+ list(GET r41s 0 rsLocal)
+ if(NOT rsLocal EQUAL 0)
+ message(FATAL_ERROR "zero exit code expected")
+ endif()
+ list(GET r41s 1 rsLocal)
+ if(NOT rsLocal EQUAL 0)
+ message(FATAL_ERROR "zero exit code expected")
+ endif()
+ list(GET r41s 2 rsLocal)
+ if(rsLocal EQUAL 0)
+ message(FATAL_ERROR "non-zero exit code expected")
+ endif()
+endif()
diff --git a/Tests/RunCMake/execute_process/RunCMakeTest.cmake b/Tests/RunCMake/execute_process/RunCMakeTest.cmake
index 62e18c601..83589bbd0 100644
--- a/Tests/RunCMake/execute_process/RunCMakeTest.cmake
+++ b/Tests/RunCMake/execute_process/RunCMakeTest.cmake
@@ -11,3 +11,7 @@ run_cmake(EncodingMissing)
if(TEST_ENCODING_EXE)
run_cmake_command(EncodingUTF8 ${CMAKE_COMMAND} -DTEST_ENCODING=UTF8 -DTEST_ENCODING_EXE=${TEST_ENCODING_EXE} -P ${RunCMake_SOURCE_DIR}/Encoding.cmake)
endif()
+
+if(EXIT_CODE_EXE)
+ run_cmake_command(ExitValues ${CMAKE_COMMAND} -DEXIT_CODE_EXE=${EXIT_CODE_EXE} -P ${RunCMake_SOURCE_DIR}/ExitValues.cmake)
+endif()
diff --git a/Tests/RunCMake/exit_code.c b/Tests/RunCMake/exit_code.c
new file mode 100644
index 000000000..3eba01941
--- /dev/null
+++ b/Tests/RunCMake/exit_code.c
@@ -0,0 +1,30 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+// Usage:
+//
+// /path/to/program arg1 [arg2 [...]]
+//
+// Return EXIT_SUCCESS if 'zero_exit'
+// string was found in <arg1>.
+// Return EXIT_FAILURE if 'non_zero_exit'
+// string was found in <arg1>.
+
+int main(int argc, const char* argv[])
+{
+ const char* substring_failure = "non_zero_exit";
+ const char* substring_success = "zero_exit";
+ const char* str = argv[1];
+ if (argc < 2) {
+ return EXIT_FAILURE;
+ }
+ if (strcmp(str, substring_success) == 0) {
+ return EXIT_SUCCESS;
+ } else if (strcmp(str, substring_failure) == 0) {
+ return EXIT_FAILURE;
+ }
+ fprintf(stderr, "Failed to find string '%s' in '%s'\n", substring_success,
+ str);
+ return EXIT_FAILURE;
+}
diff --git a/Tests/RunCMake/get_filename_component/KnownComponents.cmake b/Tests/RunCMake/get_filename_component/KnownComponents.cmake
index 7dfb55d79..ac77ac3de 100644
--- a/Tests/RunCMake/get_filename_component/KnownComponents.cmake
+++ b/Tests/RunCMake/get_filename_component/KnownComponents.cmake
@@ -80,6 +80,17 @@ get_filename_component(test_program_name "/ arg1 arg2" PROGRAM
check("PROGRAM with args output: name" "${test_program_name}" "/")
check("PROGRAM with args output: args" "${test_program_args}" " arg1 arg2")
+get_filename_component(test_program_name " " PROGRAM)
+check("PROGRAM with just a space" "${test_program_name}" "")
+
+get_filename_component(test_program_name "${CMAKE_CURRENT_LIST_FILE}" PROGRAM)
+check("PROGRAM specified explicitly without quoting" "${test_program_name}" "${CMAKE_CURRENT_LIST_FILE}")
+
+get_filename_component(test_program_name "\"${CMAKE_CURRENT_LIST_FILE}\" arg1 arg2" PROGRAM
+ PROGRAM_ARGS test_program_args)
+check("PROGRAM specified explicitly with arguments: name" "${test_program_name}" "${CMAKE_CURRENT_LIST_FILE}")
+check("PROGRAM specified explicitly with arguments: args" "${test_program_args}" " arg1 arg2")
+
list(APPEND non_cache_vars test_program_name)
list(APPEND non_cache_vars test_program_args)
diff --git a/Tests/RunCMake/get_property/source_properties-stderr.txt b/Tests/RunCMake/get_property/source_properties-stderr.txt
index 0a46f96a0..00a9b8287 100644
--- a/Tests/RunCMake/get_property/source_properties-stderr.txt
+++ b/Tests/RunCMake/get_property/source_properties-stderr.txt
@@ -3,4 +3,10 @@ get_property: --><--
get_source_file_property: -->value<--
get_property: -->value<--
get_source_file_property: -->NOTFOUND<--
-get_property: --><--$
+get_property: --><--
+get_source_file_property: -->value<--
+get_property: -->value<--
+get_source_file_property: -->NOTFOUND<--
+get_property: --><--
+get_source_file_property: -->value<--
+get_property: -->value<--$
diff --git a/Tests/RunCMake/get_property/source_properties.cmake b/Tests/RunCMake/get_property/source_properties.cmake
index 263ffe123..12d2d0797 100644
--- a/Tests/RunCMake/get_property/source_properties.cmake
+++ b/Tests/RunCMake/get_property/source_properties.cmake
@@ -13,3 +13,13 @@ set_source_files_properties(file.c PROPERTIES empty "" custom value)
check_source_file_property(file.c empty)
check_source_file_property(file.c custom)
check_source_file_property(file.c noexist)
+
+# Test strange legacy behavior in which the order in which source files are
+# first accessed affects how properties are applied without an extension.
+# See also issue #15208.
+get_property(lang SOURCE ${CMAKE_CURRENT_BINARY_DIR}/file2.c PROPERTY LANGUAGE)
+get_property(lang SOURCE ${CMAKE_CURRENT_BINARY_DIR}/file2.h PROPERTY LANGUAGE)
+set_property(SOURCE file2 PROPERTY custom value) # set property without extension
+check_source_file_property(file2 custom) # should have property
+check_source_file_property(file2.h custom) # should not have property
+check_source_file_property(file2.c custom) # should have property
diff --git a/Tests/RunCMake/include_guard/CMakeLists.txt b/Tests/RunCMake/include_guard/CMakeLists.txt
new file mode 100644
index 000000000..d3137f614
--- /dev/null
+++ b/Tests/RunCMake/include_guard/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.9)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/include_guard/DirectoryScope.cmake b/Tests/RunCMake/include_guard/DirectoryScope.cmake
new file mode 100644
index 000000000..d6c5a3ce2
--- /dev/null
+++ b/Tests/RunCMake/include_guard/DirectoryScope.cmake
@@ -0,0 +1,19 @@
+set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/Scripts")
+
+# Test include_guard with DIRECTORY scope
+
+# Add subdirectory which includes DirScript three times:
+# 1. Include at inner function scope
+# 2. At directory scope
+# 3. At another subdirectory to check that the guard is checked
+# against parent directories
+add_subdirectory(sub_dir_script1)
+# Add another directory which includes DirScript
+add_subdirectory(sub_dir_script2)
+
+# check inclusions count
+get_property(dir_count GLOBAL PROPERTY DIR_SCRIPT_COUNT)
+if(NOT dir_count EQUAL 2)
+ message(FATAL_ERROR
+ "Wrong DIR_SCRIPT_COUNT value: ${dir_count}, expected: 2")
+endif()
diff --git a/Tests/RunCMake/include_guard/GlobalScope.cmake b/Tests/RunCMake/include_guard/GlobalScope.cmake
new file mode 100644
index 000000000..02137fa77
--- /dev/null
+++ b/Tests/RunCMake/include_guard/GlobalScope.cmake
@@ -0,0 +1,11 @@
+set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/Scripts")
+
+# Test GLOBAL include guard
+add_subdirectory(global_script_dir)
+include(GlobScript)
+
+get_property(glob_count GLOBAL PROPERTY GLOB_SCRIPT_COUNT)
+if(NOT glob_count EQUAL 1)
+ message(FATAL_ERROR
+ "Wrong GLOB_SCRIPT_COUNT value: ${glob_count}, expected: 1")
+endif()
diff --git a/Tests/RunCMake/include_guard/InvalidArgumentsNumber-result.txt b/Tests/RunCMake/include_guard/InvalidArgumentsNumber-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/include_guard/InvalidArgumentsNumber-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/include_guard/InvalidArgumentsNumber-stderr.txt b/Tests/RunCMake/include_guard/InvalidArgumentsNumber-stderr.txt
new file mode 100644
index 000000000..cdd33ac0d
--- /dev/null
+++ b/Tests/RunCMake/include_guard/InvalidArgumentsNumber-stderr.txt
@@ -0,0 +1,5 @@
+CMake Error at InvalidArgumentsNumber.cmake:1 \(include_guard\):
+ include_guard given an invalid number of arguments. The command takes at
+ most 1 argument.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/include_guard/InvalidArgumentsNumber.cmake b/Tests/RunCMake/include_guard/InvalidArgumentsNumber.cmake
new file mode 100644
index 000000000..a63a395c0
--- /dev/null
+++ b/Tests/RunCMake/include_guard/InvalidArgumentsNumber.cmake
@@ -0,0 +1 @@
+include_guard(ARG1 ARG2)
diff --git a/Tests/RunCMake/include_guard/InvalidScope-result.txt b/Tests/RunCMake/include_guard/InvalidScope-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/include_guard/InvalidScope-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/include_guard/InvalidScope-stderr.txt b/Tests/RunCMake/include_guard/InvalidScope-stderr.txt
new file mode 100644
index 000000000..456709da7
--- /dev/null
+++ b/Tests/RunCMake/include_guard/InvalidScope-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at InvalidScope.cmake:1 \(include_guard\):
+ include_guard given an invalid scope: INVALID
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/include_guard/InvalidScope.cmake b/Tests/RunCMake/include_guard/InvalidScope.cmake
new file mode 100644
index 000000000..f69f9fd64
--- /dev/null
+++ b/Tests/RunCMake/include_guard/InvalidScope.cmake
@@ -0,0 +1 @@
+include_guard(INVALID)
diff --git a/Tests/RunCMake/include_guard/RunCMakeTest.cmake b/Tests/RunCMake/include_guard/RunCMakeTest.cmake
new file mode 100644
index 000000000..e87bddd87
--- /dev/null
+++ b/Tests/RunCMake/include_guard/RunCMakeTest.cmake
@@ -0,0 +1,7 @@
+include(RunCMake)
+
+run_cmake(VariableScope)
+run_cmake(DirectoryScope)
+run_cmake(GlobalScope)
+run_cmake(InvalidScope)
+run_cmake(InvalidArgumentsNumber)
diff --git a/Tests/RunCMake/include_guard/Scripts/DirScript.cmake b/Tests/RunCMake/include_guard/Scripts/DirScript.cmake
new file mode 100644
index 000000000..e61d18051
--- /dev/null
+++ b/Tests/RunCMake/include_guard/Scripts/DirScript.cmake
@@ -0,0 +1,12 @@
+include_guard(DIRECTORY)
+
+set(prop_name DIR_SCRIPT_COUNT)
+get_property(count_is_set GLOBAL PROPERTY ${prop_name} SET)
+
+if(NOT count_is_set)
+ set_property(GLOBAL PROPERTY ${prop_name} 1)
+else()
+ get_property(count GLOBAL PROPERTY ${prop_name})
+ math(EXPR count "${count} + 1")
+ set_property(GLOBAL PROPERTY ${prop_name} ${count})
+endif()
diff --git a/Tests/RunCMake/include_guard/Scripts/GlobScript.cmake b/Tests/RunCMake/include_guard/Scripts/GlobScript.cmake
new file mode 100644
index 000000000..c26bf40e8
--- /dev/null
+++ b/Tests/RunCMake/include_guard/Scripts/GlobScript.cmake
@@ -0,0 +1,12 @@
+include_guard(GLOBAL)
+
+set(prop_name GLOB_SCRIPT_COUNT)
+get_property(count_is_set GLOBAL PROPERTY ${prop_name} SET)
+
+if(NOT count_is_set)
+ set_property(GLOBAL PROPERTY ${prop_name} 1)
+else()
+ get_property(count GLOBAL PROPERTY ${prop_name})
+ math(EXPR count "${count} + 1")
+ set_property(GLOBAL PROPERTY ${prop_name} ${count})
+endif()
diff --git a/Tests/RunCMake/include_guard/Scripts/VarScript.cmake b/Tests/RunCMake/include_guard/Scripts/VarScript.cmake
new file mode 100644
index 000000000..3080377cb
--- /dev/null
+++ b/Tests/RunCMake/include_guard/Scripts/VarScript.cmake
@@ -0,0 +1,12 @@
+include_guard()
+
+set(prop_name VAR_SCRIPT_COUNT)
+get_property(count_is_set GLOBAL PROPERTY ${prop_name} SET)
+
+if(NOT count_is_set)
+ set_property(GLOBAL PROPERTY ${prop_name} 1)
+else()
+ get_property(count GLOBAL PROPERTY ${prop_name})
+ math(EXPR count "${count} + 1")
+ set_property(GLOBAL PROPERTY ${prop_name} ${count})
+endif()
diff --git a/Tests/RunCMake/include_guard/VariableScope.cmake b/Tests/RunCMake/include_guard/VariableScope.cmake
new file mode 100644
index 000000000..7f8477db3
--- /dev/null
+++ b/Tests/RunCMake/include_guard/VariableScope.cmake
@@ -0,0 +1,24 @@
+set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/Scripts")
+
+# Test include_guard with VARIABLE scope
+function(var_include_func)
+ # Include twice in the same scope
+ include(VarScript)
+ include(VarScript)
+ get_property(var_count GLOBAL PROPERTY VAR_SCRIPT_COUNT)
+ if(NOT var_count EQUAL 1)
+ message(FATAL_ERROR
+ "Wrong VAR_SCRIPT_COUNT value: ${var_count}, expected: 1")
+ endif()
+endfunction()
+
+var_include_func()
+
+# Check again that include_guard has been reset
+include(VarScript)
+
+get_property(var_count GLOBAL PROPERTY VAR_SCRIPT_COUNT)
+if(NOT var_count EQUAL 2)
+ message(FATAL_ERROR
+ "Wrong VAR_SCRIPT_COUNT value: ${var_count}, expected: 2")
+endif()
diff --git a/Tests/RunCMake/include_guard/global_script_dir/CMakeLists.txt b/Tests/RunCMake/include_guard/global_script_dir/CMakeLists.txt
new file mode 100644
index 000000000..ee7ea2ecc
--- /dev/null
+++ b/Tests/RunCMake/include_guard/global_script_dir/CMakeLists.txt
@@ -0,0 +1 @@
+include(GlobScript)
diff --git a/Tests/RunCMake/include_guard/sub_dir_script1/CMakeLists.txt b/Tests/RunCMake/include_guard/sub_dir_script1/CMakeLists.txt
new file mode 100644
index 000000000..d3626e5fa
--- /dev/null
+++ b/Tests/RunCMake/include_guard/sub_dir_script1/CMakeLists.txt
@@ -0,0 +1,9 @@
+function(dir_check)
+ include(DirScript)
+endfunction()
+
+dir_check()
+
+include(DirScript)
+
+add_subdirectory(sub_dir_script3)
diff --git a/Tests/RunCMake/include_guard/sub_dir_script1/sub_dir_script3/CMakeLists.txt b/Tests/RunCMake/include_guard/sub_dir_script1/sub_dir_script3/CMakeLists.txt
new file mode 100644
index 000000000..1c3b1b245
--- /dev/null
+++ b/Tests/RunCMake/include_guard/sub_dir_script1/sub_dir_script3/CMakeLists.txt
@@ -0,0 +1 @@
+include(DirScript)
diff --git a/Tests/RunCMake/include_guard/sub_dir_script2/CMakeLists.txt b/Tests/RunCMake/include_guard/sub_dir_script2/CMakeLists.txt
new file mode 100644
index 000000000..1c3b1b245
--- /dev/null
+++ b/Tests/RunCMake/include_guard/sub_dir_script2/CMakeLists.txt
@@ -0,0 +1 @@
+include(DirScript)
diff --git a/Tests/RunCMake/pseudo_cppcheck.c b/Tests/RunCMake/pseudo_cppcheck.c
new file mode 100644
index 000000000..8667e5e4a
--- /dev/null
+++ b/Tests/RunCMake/pseudo_cppcheck.c
@@ -0,0 +1,32 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+int main(int argc, char* argv[])
+{
+ int i;
+ for (i = 1; i < argc; ++i) {
+ if (strcmp(argv[i], "-bad") == 0)
+ if (strcmp(argv[i], "-bad") == 0) {
+ fprintf(stdout, "stdout from bad command line arg '-bad'\n");
+ fprintf(stderr, "stderr from bad command line arg '-bad'\n");
+ return 1;
+ }
+ }
+ fprintf(stderr,
+ "[/foo/bar.c:2]: (error) Array 'abc[10]' accessed at index 12,"
+ " which is out of bounds.\n");
+ fprintf(stderr, "[/foo/bar.c:2]: (warning) Member variable 'foo::bar' is "
+ "not initialized in the constructor.\n");
+ fprintf(stderr, "[/foo/bar.c:2]: (style) C-style pointer casting.\n");
+ fprintf(stderr, "[/foo/bar.c:2]: (performance) Variable 'm_message' is "
+ "assigned in constructor body. Consider performing "
+ "initialization in initialization list.\n");
+ fprintf(stderr, "[/foo/bar.c:2]: (portability) scanf without field width "
+ "limits can crash with huge input data on some versions of "
+ "libc\n");
+ fprintf(stderr, "[/foo/bar.c:2]: (information) cannot find all the include "
+ "files (use --check-config for details)\n");
+ // we allow this to return 1 as we ignore it
+ return 1;
+}
diff --git a/Tests/RunCMake/string/Prepend.cmake b/Tests/RunCMake/string/Prepend.cmake
new file mode 100644
index 000000000..8eaeebb46
--- /dev/null
+++ b/Tests/RunCMake/string/Prepend.cmake
@@ -0,0 +1,58 @@
+set(out)
+string(PREPEND out)
+if(DEFINED out)
+ message(FATAL_ERROR "\"string(PREPEND out)\" set out to \"${out}\"")
+endif()
+
+set(out "")
+string(PREPEND out)
+if(NOT out STREQUAL "")
+ message(FATAL_ERROR "\"string(PREPEND out)\" set out to \"${out}\"")
+endif()
+
+set(out x)
+string(PREPEND out)
+if(NOT out STREQUAL "x")
+ message(FATAL_ERROR "\"string(PREPEND out)\" set out to \"${out}\"")
+endif()
+
+
+set(out)
+string(PREPEND out a)
+if(NOT out STREQUAL "a")
+ message(FATAL_ERROR "\"string(PREPEND out a)\" set out to \"${out}\"")
+endif()
+
+set(out "")
+string(PREPEND out a)
+if(NOT out STREQUAL "a")
+ message(FATAL_ERROR "\"string(PREPEND out a)\" set out to \"${out}\"")
+endif()
+
+set(out x)
+string(PREPEND out a)
+if(NOT out STREQUAL "ax")
+ message(FATAL_ERROR "\"string(PREPEND out a)\" set out to \"${out}\"")
+endif()
+
+
+set(out x)
+string(PREPEND out a "b")
+if(NOT out STREQUAL "abx")
+ message(FATAL_ERROR "\"string(PREPEND out a \"b\")\" set out to \"${out}\"")
+endif()
+
+set(b)
+set(out x)
+string(PREPEND out ${b})
+if(NOT out STREQUAL "x")
+ message(FATAL_ERROR "\"string(PREPEND out \${b})\" set out to \"${out}\"")
+endif()
+
+set(b b)
+set(out x)
+string(PREPEND out a "${b}" [[
+${c}]])
+if(NOT out STREQUAL "ab\${c}x")
+ message(FATAL_ERROR "\"string(PREPEND out a \"\${b}\" [[\${c}]])\" set out to \"${out}\"")
+endif()
diff --git a/Tests/RunCMake/string/PrependNoArgs-result.txt b/Tests/RunCMake/string/PrependNoArgs-result.txt
new file mode 100644
index 000000000..d00491fd7
--- /dev/null
+++ b/Tests/RunCMake/string/PrependNoArgs-result.txt
@@ -0,0 +1 @@
+1
diff --git a/Tests/RunCMake/string/PrependNoArgs-stderr.txt b/Tests/RunCMake/string/PrependNoArgs-stderr.txt
new file mode 100644
index 000000000..8d433f93a
--- /dev/null
+++ b/Tests/RunCMake/string/PrependNoArgs-stderr.txt
@@ -0,0 +1,4 @@
+CMake Error at PrependNoArgs.cmake:1 \(string\):
+ string sub-command PREPEND requires at least one argument.
+Call Stack \(most recent call first\):
+ CMakeLists.txt:3 \(include\)
diff --git a/Tests/RunCMake/string/PrependNoArgs.cmake b/Tests/RunCMake/string/PrependNoArgs.cmake
new file mode 100644
index 000000000..f324f2854
--- /dev/null
+++ b/Tests/RunCMake/string/PrependNoArgs.cmake
@@ -0,0 +1 @@
+string(PREPEND)
diff --git a/Tests/RunCMake/string/RegexMultiMatchClear-stderr.txt b/Tests/RunCMake/string/RegexMultiMatchClear-stderr.txt
new file mode 100644
index 000000000..4360d79c1
--- /dev/null
+++ b/Tests/RunCMake/string/RegexMultiMatchClear-stderr.txt
@@ -0,0 +1,12 @@
+^matches: Some::;Scope
+results from: string\(REGEX MATCHALL\)
+CMAKE_MATCH_0: -->Scope<--
+CMAKE_MATCH_1: -->Scope<--
+CMAKE_MATCH_2: --><--
+CMAKE_MATCH_COUNT: -->1<--
+replace: \[Some\]\[Scope\]
+results from: string\(REGEX REPLACE\)
+CMAKE_MATCH_0: -->Scope<--
+CMAKE_MATCH_1: -->Scope<--
+CMAKE_MATCH_2: --><--
+CMAKE_MATCH_COUNT: -->1<--$
diff --git a/Tests/RunCMake/string/RegexMultiMatchClear.cmake b/Tests/RunCMake/string/RegexMultiMatchClear.cmake
new file mode 100644
index 000000000..80b6b3c7b
--- /dev/null
+++ b/Tests/RunCMake/string/RegexMultiMatchClear.cmake
@@ -0,0 +1,20 @@
+cmake_minimum_required (VERSION 3.0)
+project (RegexClear NONE)
+
+function (output_results msg)
+ message("results from: ${msg}")
+ message("CMAKE_MATCH_0: -->${CMAKE_MATCH_0}<--")
+ message("CMAKE_MATCH_1: -->${CMAKE_MATCH_1}<--")
+ message("CMAKE_MATCH_2: -->${CMAKE_MATCH_2}<--")
+ message("CMAKE_MATCH_COUNT: -->${CMAKE_MATCH_COUNT}<--")
+endfunction ()
+
+set(haystack "Some::Scope")
+
+string(REGEX MATCHALL "^([^:]+)(::)?" matches "${haystack}")
+message("matches: ${matches}")
+output_results("string(REGEX MATCHALL)")
+
+string(REGEX REPLACE "^([^:]+)(::)?" "[\\1]" replace "${haystack}")
+message("replace: ${replace}")
+output_results("string(REGEX REPLACE)")
diff --git a/Tests/RunCMake/string/RunCMakeTest.cmake b/Tests/RunCMake/string/RunCMakeTest.cmake
index 38a77b0d1..513d1e3ae 100644
--- a/Tests/RunCMake/string/RunCMakeTest.cmake
+++ b/Tests/RunCMake/string/RunCMakeTest.cmake
@@ -3,6 +3,9 @@ include(RunCMake)
run_cmake(Append)
run_cmake(AppendNoArgs)
+run_cmake(Prepend)
+run_cmake(PrependNoArgs)
+
run_cmake(Concat)
run_cmake(ConcatNoArgs)
@@ -20,6 +23,7 @@ run_cmake(UuidMissingTypeValue)
run_cmake(UuidBadType)
run_cmake(RegexClear)
+run_cmake(RegexMultiMatchClear)
run_cmake(UTF-16BE)
run_cmake(UTF-16LE)
diff --git a/Tests/RunCMake/string/Timestamp-stderr.txt b/Tests/RunCMake/string/Timestamp-stderr.txt
index 653974c62..cd4dcb37e 100644
--- a/Tests/RunCMake/string/Timestamp-stderr.txt
+++ b/Tests/RunCMake/string/Timestamp-stderr.txt
@@ -1 +1 @@
-RESULT=2005-08-07 23:19:49 Sun Aug 05 day=219 wd=0 week=32 %I=11 epoch=1123456789
+RESULT=2005-08-07 23:19:49 Sunday=Sun August=Aug 05 day=219 wd=0 week=32 %I=11 epoch=1123456789
diff --git a/Tests/RunCMake/string/Timestamp.cmake b/Tests/RunCMake/string/Timestamp.cmake
index d24203942..cba258d12 100644
--- a/Tests/RunCMake/string/Timestamp.cmake
+++ b/Tests/RunCMake/string/Timestamp.cmake
@@ -1,3 +1,3 @@
set(ENV{SOURCE_DATE_EPOCH} "1123456789")
-string(TIMESTAMP RESULT "%Y-%m-%d %H:%M:%S %a %b %y day=%j wd=%w week=%U %%I=%I epoch=%s" UTC)
+string(TIMESTAMP RESULT "%Y-%m-%d %H:%M:%S %A=%a %B=%b %y day=%j wd=%w week=%U %%I=%I epoch=%s" UTC)
message("RESULT=${RESULT}")
diff --git a/Tests/RunCMake/target_link_libraries/RunCMakeTest.cmake b/Tests/RunCMake/target_link_libraries/RunCMakeTest.cmake
index 1466fbf61..b1c943505 100644
--- a/Tests/RunCMake/target_link_libraries/RunCMakeTest.cmake
+++ b/Tests/RunCMake/target_link_libraries/RunCMakeTest.cmake
@@ -10,3 +10,4 @@ run_cmake(SubDirTarget)
run_cmake(SharedDepNotTarget)
run_cmake(StaticPrivateDepNotExported)
run_cmake(StaticPrivateDepNotTarget)
+run_cmake(UNKNOWN-IMPORTED-GLOBAL)
diff --git a/Tests/RunCMake/target_link_libraries/UNKNOWN-IMPORTED-GLOBAL.cmake b/Tests/RunCMake/target_link_libraries/UNKNOWN-IMPORTED-GLOBAL.cmake
new file mode 100644
index 000000000..f52fa30bc
--- /dev/null
+++ b/Tests/RunCMake/target_link_libraries/UNKNOWN-IMPORTED-GLOBAL.cmake
@@ -0,0 +1,4 @@
+enable_language(C)
+add_library(UnknownImportedGlobal UNKNOWN IMPORTED GLOBAL)
+add_library(mylib empty.c)
+target_link_libraries(mylib UnknownImportedGlobal)
diff --git a/Tests/RunCMake/test_include_dirs/CMakeLists.txt b/Tests/RunCMake/test_include_dirs/CMakeLists.txt
new file mode 100644
index 000000000..dc9248697
--- /dev/null
+++ b/Tests/RunCMake/test_include_dirs/CMakeLists.txt
@@ -0,0 +1,3 @@
+cmake_minimum_required(VERSION 3.6)
+project(${RunCMake_TEST} NONE)
+include(${RunCMake_TEST}.cmake)
diff --git a/Tests/RunCMake/test_include_dirs/RunCMakeTest.cmake b/Tests/RunCMake/test_include_dirs/RunCMakeTest.cmake
new file mode 100644
index 000000000..d1633e445
--- /dev/null
+++ b/Tests/RunCMake/test_include_dirs/RunCMakeTest.cmake
@@ -0,0 +1,17 @@
+include(RunCMake)
+
+function(run_TID)
+ # Use a single build tree for a few tests without cleaning.
+ set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/TID-build)
+ set(RunCMake_TEST_NO_CLEAN 1)
+ if(RunCMake_GENERATOR MATCHES "Make|Ninja")
+ set(RunCMake_TEST_OPTIONS -DCMAKE_BUILD_TYPE=Debug)
+ endif()
+ file(REMOVE_RECURSE "${RunCMake_TEST_BINARY_DIR}")
+ file(MAKE_DIRECTORY "${RunCMake_TEST_BINARY_DIR}")
+ run_cmake(TID)
+ run_cmake_command(TID-build ${CMAKE_COMMAND} --build . --config Debug)
+ run_cmake_command(TID-test ${CMAKE_CTEST_COMMAND} -C Debug)
+endfunction()
+
+run_TID()
diff --git a/Tests/RunCMake/test_include_dirs/TID-test-stdout.txt b/Tests/RunCMake/test_include_dirs/TID-test-stdout.txt
new file mode 100644
index 000000000..19bf051fa
--- /dev/null
+++ b/Tests/RunCMake/test_include_dirs/TID-test-stdout.txt
@@ -0,0 +1,17 @@
+Test project .*
+ Start 1: house\.dog
+1/6 Test #1: house\.dog \.+ +Passed +[0-9.]+ sec
+ Start 2: house\.cat
+2/6 Test #2: house\.cat \.+ +Passed +[0-9.]+ sec
+ Start 3: farm\.cow
+3/6 Test #3: farm\.cow \.+ +Passed +[0-9.]+ sec
+ Start 4: farm\.pig
+4/6 Test #4: farm\.pig \.+ +Passed +[0-9.]+ sec
+ Start 5: zoo\.fox
+5/6 Test #5: zoo\.fox \.+ +Passed +[0-9.]+ sec
+ Start 6: zoo\.emu
+6/6 Test #6: zoo\.emu \.+ +Passed +[0-9.]+ sec
+
+100% tests passed, 0 tests failed out of 6
+
+Total Test time \(real\) = +[0-9.]+ sec
diff --git a/Tests/RunCMake/test_include_dirs/TID.cmake b/Tests/RunCMake/test_include_dirs/TID.cmake
new file mode 100644
index 000000000..1e74f90fe
--- /dev/null
+++ b/Tests/RunCMake/test_include_dirs/TID.cmake
@@ -0,0 +1,29 @@
+project(test_include_dirs)
+include(CTest)
+
+enable_testing()
+
+add_executable(dummy dummy.cpp)
+
+function(generate_tests NAME)
+ set(ctest_file "${CMAKE_CURRENT_BINARY_DIR}/${NAME}_tests.cmake")
+ add_custom_command(
+ OUTPUT "${ctest_file}"
+ COMMAND "${CMAKE_COMMAND}"
+ -D "TEST_EXECUTABLE=$<TARGET_FILE:dummy>"
+ -D "TEST_SUITE=${NAME}"
+ -D "TEST_NAMES=${ARGN}"
+ -D "CTEST_FILE=${ctest_file}"
+ -P "${CMAKE_CURRENT_SOURCE_DIR}/add-tests.cmake"
+ VERBATIM
+ )
+ add_custom_target(${NAME}_tests ALL DEPENDS "${ctest_file}")
+endfunction()
+
+generate_tests(house dog cat)
+generate_tests(farm cow pig)
+generate_tests(zoo fox emu)
+
+set_property(DIRECTORY PROPERTY TEST_INCLUDE_FILE "house_tests.cmake")
+set_property(DIRECTORY APPEND PROPERTY TEST_INCLUDE_FILES "farm_tests.cmake")
+set_property(DIRECTORY APPEND PROPERTY TEST_INCLUDE_FILES "zoo_tests.cmake")
diff --git a/Tests/RunCMake/test_include_dirs/add-tests.cmake b/Tests/RunCMake/test_include_dirs/add-tests.cmake
new file mode 100644
index 000000000..e74665acc
--- /dev/null
+++ b/Tests/RunCMake/test_include_dirs/add-tests.cmake
@@ -0,0 +1,8 @@
+set(script)
+
+foreach(TEST_NAME ${TEST_NAMES})
+ set(script "${script}add_test(\"${TEST_SUITE}.${TEST_NAME}\"")
+ set(script "${script} \"${TEST_EXECUTABLE}\")\n")
+endforeach()
+
+file(WRITE "${CTEST_FILE}" "${script}")
diff --git a/Tests/RunCMake/test_include_dirs/dummy.cpp b/Tests/RunCMake/test_include_dirs/dummy.cpp
new file mode 100644
index 000000000..f8b643afb
--- /dev/null
+++ b/Tests/RunCMake/test_include_dirs/dummy.cpp
@@ -0,0 +1,4 @@
+int main()
+{
+ return 0;
+}
diff --git a/Tests/RunCMake/variable_watch/ModifyWatchInCallback.cmake b/Tests/RunCMake/variable_watch/ModifyWatchInCallback.cmake
new file mode 100644
index 000000000..1dee8375a
--- /dev/null
+++ b/Tests/RunCMake/variable_watch/ModifyWatchInCallback.cmake
@@ -0,0 +1,17 @@
+function (watch2)
+
+endfunction ()
+
+function (watch1)
+ variable_watch(watched watch2)
+ variable_watch(watched watch2)
+ variable_watch(watched watch2)
+ variable_watch(watched watch2)
+ variable_watch(watched watch2)
+ variable_watch(watched watch2)
+endfunction ()
+
+variable_watch(watched watch1)
+variable_watch(watched watch2)
+
+set(access "${watched}")
diff --git a/Tests/RunCMake/variable_watch/RunCMakeTest.cmake b/Tests/RunCMake/variable_watch/RunCMakeTest.cmake
index 9becb4cd7..2fa62755d 100644
--- a/Tests/RunCMake/variable_watch/RunCMakeTest.cmake
+++ b/Tests/RunCMake/variable_watch/RunCMakeTest.cmake
@@ -3,3 +3,4 @@ include(RunCMake)
run_cmake(ModifiedAccess)
run_cmake(NoWatcher)
run_cmake(WatchTwice)
+run_cmake(ModifyWatchInCallback)
diff --git a/Tests/SameName/CMakeLists.txt b/Tests/SameName/CMakeLists.txt
deleted file mode 100644
index d78879dd9..000000000
--- a/Tests/SameName/CMakeLists.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-cmake_minimum_required (VERSION 2.6)
-project(SameName C)
-
-add_subdirectory(Lib1)
-
-include_directories(${PROJECT_SOURCE_DIR}/Lib1)
-add_subdirectory(Exe1)
diff --git a/Tests/SameName/Exe1/CMakeLists.txt b/Tests/SameName/Exe1/CMakeLists.txt
deleted file mode 100644
index b9182f209..000000000
--- a/Tests/SameName/Exe1/CMakeLists.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-# a target with the same name as a target in a different dir
-add_executable(mytest_exe conly.c)
-set_target_properties(mytest_exe PROPERTIES OUTPUT_NAME mytest)
-target_link_libraries(mytest_exe mytest)
-
-# and two targets in the same dir with the same name
-add_library(mytest2 ../Lib1/libc1.c)
-
-add_executable(mytest2_exe conly.c)
-set_target_properties(mytest2_exe PROPERTIES OUTPUT_NAME mytest2)
-target_link_libraries(mytest2_exe mytest2)
diff --git a/Tests/SameName/Exe1/conly.c b/Tests/SameName/Exe1/conly.c
deleted file mode 100644
index 8f2ce05f7..000000000
--- a/Tests/SameName/Exe1/conly.c
+++ /dev/null
@@ -1,11 +0,0 @@
-#include "libc1.h"
-#include <stdio.h>
-
-int main()
-{
- if (LibC1Func() != 2.0) {
- printf("Problem with libc1\n");
- return 1;
- }
- return 0;
-}
diff --git a/Tests/SameName/Lib1/CMakeLists.txt b/Tests/SameName/Lib1/CMakeLists.txt
deleted file mode 100644
index 40fa15422..000000000
--- a/Tests/SameName/Lib1/CMakeLists.txt
+++ /dev/null
@@ -1 +0,0 @@
-add_library(mytest libc1.c)
diff --git a/Tests/SameName/Lib1/libc1.c b/Tests/SameName/Lib1/libc1.c
deleted file mode 100644
index b01e1e1b5..000000000
--- a/Tests/SameName/Lib1/libc1.c
+++ /dev/null
@@ -1,4 +0,0 @@
-float LibC1Func()
-{
- return 2.0;
-}
diff --git a/Tests/SameName/Lib1/libc1.h b/Tests/SameName/Lib1/libc1.h
deleted file mode 100644
index 84c94a9cb..000000000
--- a/Tests/SameName/Lib1/libc1.h
+++ /dev/null
@@ -1 +0,0 @@
-extern float LibC1Func();
diff --git a/Tests/Server/CMakeLists.txt b/Tests/Server/CMakeLists.txt
index e7eaa8d72..08bef0c44 100644
--- a/Tests/Server/CMakeLists.txt
+++ b/Tests/Server/CMakeLists.txt
@@ -16,10 +16,11 @@ macro(do_test bsname file)
)
if (NOT test_result EQUAL 0)
- message(SEND_ERROR "TEST FAILED")
+ message(SEND_ERROR "TEST FAILED: ${test_result}")
endif()
endmacro()
+do_test("test_cache" "tc_cache.json")
do_test("test_handshake" "tc_handshake.json")
do_test("test_globalSettings" "tc_globalSettings.json")
do_test("test_buildsystem1" "tc_buildsystem1.json")
diff --git a/Tests/Server/cmakelib.py b/Tests/Server/cmakelib.py
index 78450d5bf..2218e02d2 100644
--- a/Tests/Server/cmakelib.py
+++ b/Tests/Server/cmakelib.py
@@ -95,6 +95,21 @@ def initProc(cmakeCommand):
return cmakeCommand
+def exitProc(cmakeCommand):
+ # Tell the server to exit.
+ cmakeCommand.stdin.close()
+ cmakeCommand.stdout.close()
+
+ # Wait for the server to exit.
+ # If this version of python supports it, terminate the server after a timeout.
+ try:
+ cmakeCommand.wait(timeout=5)
+ except TypeError:
+ cmakeCommand.wait()
+ except:
+ cmakeCommand.terminate()
+ raise
+
def waitForMessage(cmakeCommand, expected):
data = ordered(expected)
packet = ordered(waitForRawMessage(cmakeCommand))
@@ -197,3 +212,27 @@ def validateGlobalSettings(cmakeCommand, cmakeCommandPath, data):
print("Validating", i)
if (packet[i] != data[i]):
sys.exit(1)
+
+def validateCache(cmakeCommand, data):
+ packet = waitForReply(cmakeCommand, 'cache', '', False)
+
+ cache = packet['cache']
+
+ if (data['isEmpty']):
+ if (cache != []):
+ print('Expected empty cache, but got data.\n')
+ sys.exit(1)
+ return;
+
+ if (cache == []):
+ print('Expected cache contents, but got none.\n')
+ sys.exit(1)
+
+ hadHomeDir = False
+ for value in cache:
+ if (value['key'] == 'CMAKE_HOME_DIRECTORY'):
+ hadHomeDir = True
+
+ if (not hadHomeDir):
+ print('No CMAKE_HOME_DIRECTORY found in cache.')
+ sys.exit(1)
diff --git a/Tests/Server/server-test.py b/Tests/Server/server-test.py
index 62d9008b2..938091065 100644
--- a/Tests/Server/server-test.py
+++ b/Tests/Server/server-test.py
@@ -84,7 +84,7 @@ for obj in testData:
if 'extraGenerator' in data: extraGenerator = data['extraGenerator']
if not os.path.isabs(buildDirectory):
buildDirectory = buildDir + "/" + buildDirectory
- if not os.path.isabs(sourceDirectory):
+ if sourceDirectory != '' and not os.path.isabs(sourceDirectory):
sourceDirectory = sourceDir + "/" + sourceDirectory
cmakelib.handshake(proc, major, minor, sourceDirectory, buildDirectory,
generator, extraGenerator)
@@ -95,26 +95,21 @@ for obj in testData:
if not 'generator' in data: data['generator'] = cmakeGenerator
if not 'extraGenerator' in data: data['extraGenerator'] = ''
cmakelib.validateGlobalSettings(proc, cmakeCommand, data)
+ elif 'validateCache' in obj:
+ data = obj['validateCache']
+ if not 'isEmpty' in data: data['isEmpty'] = false
+ cmakelib.validateCache(proc, data)
elif 'message' in obj:
print("MESSAGE:", obj["message"])
+ elif 'reconnect' in obj:
+ cmakelib.exitProc(proc)
+ proc = cmakelib.initProc(cmakeCommand)
else:
print("Unknown command:", json.dumps(obj))
sys.exit(2)
print("Completed")
-# Tell the server to exit.
-proc.stdin.close()
-proc.stdout.close()
-
-# Wait for the server to exit.
-# If this version of python supports it, terminate the server after a timeout.
-try:
- proc.wait(timeout=5)
-except TypeError:
- proc.wait()
-except:
- proc.terminate()
- raise
-
-sys.exit(0)
+cmakelib.exitProc(proc)
+print('cmake-server exited: %d' % proc.returncode)
+sys.exit(proc.returncode)
diff --git a/Tests/Server/tc_cache.json b/Tests/Server/tc_cache.json
new file mode 100644
index 000000000..74af6d93c
--- /dev/null
+++ b/Tests/Server/tc_cache.json
@@ -0,0 +1,24 @@
+[
+{ "message": "Testing cache" },
+
+{ "message": "Cache after first handshake is empty:" },
+{ "handshake": {"major": 1, "sourceDirectory": "buildsystem1", "buildDirectory": "buildsystem1"} },
+{ "send": { "type": "cache" } },
+{ "validateCache": { "isEmpty": true } },
+
+{ "message": "Cache after configure is populated:" },
+{ "send": { "type": "configure" } },
+{ "reply": { "type": "configure", "skipProgress":true } },
+{ "send": { "type": "cache" } },
+{ "validateCache": { "isEmpty": false } },
+
+{ "message": "Handshake for existing cache requires buildDirectory only:" },
+{ "reconnect": {} },
+{ "handshake": {"major": 1, "sourceDirectory": "", "buildDirectory": "buildsystem1"} },
+
+{ "message": "Cache after reconnect is again populated:" },
+{ "send": { "type": "cache" } },
+{ "validateCache": { "isEmpty": false } },
+
+{ "message": "Everything ok." }
+]
diff --git a/Tests/Server/tc_handshake.json b/Tests/Server/tc_handshake.json
index 975bb3d32..4bb7fa7ac 100644
--- a/Tests/Server/tc_handshake.json
+++ b/Tests/Server/tc_handshake.json
@@ -11,6 +11,10 @@
{ "send": {"test": "sometext","cookie":"monster"} },
{ "recv": {"cookie":"monster","errorMessage":"No type given in request.","inReplyTo":"","type":"error"} },
+{ "message": "Testing commands before handshake" },
+{ "send": {"type": "cache","cookie":"monster"} },
+{ "recv": {"cookie":"monster","errorMessage":"Waiting for type \"handshake\".","inReplyTo":"cache","type":"error"} },
+
{ "message": "Testing handshake" },
{ "send": {"type": "sometype","cookie":"monster2"} },
{ "recv": {"cookie":"monster2","errorMessage":"Waiting for type \"handshake\".","inReplyTo":"sometype","type":"error"} },
diff --git a/Tests/SimpleExclude/CMakeLists.txt b/Tests/SimpleExclude/CMakeLists.txt
deleted file mode 100644
index baca23e39..000000000
--- a/Tests/SimpleExclude/CMakeLists.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-cmake_minimum_required (VERSION 2.6)
-project(SimpleExclude C)
-
-set(EXECUTABLE_OUTPUT_PATH "${SimpleExclude_BINARY_DIR}" CACHE INTERNAL "" FORCE)
-set(LIBRARY_OUTPUT_PATH "${SimpleExclude_BINARY_DIR}" CACHE INTERNAL "" FORCE)
-
-add_subdirectory(dirC EXCLUDE_FROM_ALL)
-add_subdirectory(dirD)
-
-configure_file("${CMAKE_CURRENT_SOURCE_DIR}/run.cmake.in"
- "${CMAKE_CURRENT_BINARY_DIR}/run.cmake" @ONLY)
diff --git a/Tests/SimpleExclude/dirC/CMakeLists.txt b/Tests/SimpleExclude/dirC/CMakeLists.txt
deleted file mode 100644
index 9b59fdaff..000000000
--- a/Tests/SimpleExclude/dirC/CMakeLists.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-add_subdirectory(dirA EXCLUDE_FROM_ALL)
-add_subdirectory(dirB)
-
diff --git a/Tests/SimpleExclude/dirC/dirA/CMakeLists.txt b/Tests/SimpleExclude/dirC/dirA/CMakeLists.txt
deleted file mode 100644
index 52fac8183..000000000
--- a/Tests/SimpleExclude/dirC/dirA/CMakeLists.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-add_library(t1 STATIC t1.c)
-
-add_library(t2 STATIC t2.c)
-
-add_executable(t3 t3.c)
-
-add_executable(t4 t4.c)
-
-add_executable(t5 t5.c)
-target_link_libraries(t5 t1)
diff --git a/Tests/SimpleExclude/dirC/dirA/t1.c b/Tests/SimpleExclude/dirC/dirA/t1.c
deleted file mode 100644
index 67fe06fee..000000000
--- a/Tests/SimpleExclude/dirC/dirA/t1.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include <stdio.h>
-
-int tlib1func()
-{
- Should not be build unless target directory A, B, or C are build;
- printf("This is T1\n");
- return 5;
-}
diff --git a/Tests/SimpleExclude/dirC/dirA/t2.c b/Tests/SimpleExclude/dirC/dirA/t2.c
deleted file mode 100644
index 6aaf40675..000000000
--- a/Tests/SimpleExclude/dirC/dirA/t2.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include <stdio.h>
-
-int tlib2func()
-{
- printf("This is T2\n");
- return 2;
-}
diff --git a/Tests/SimpleExclude/dirC/dirA/t3.c b/Tests/SimpleExclude/dirC/dirA/t3.c
deleted file mode 100644
index 1366dc0a6..000000000
--- a/Tests/SimpleExclude/dirC/dirA/t3.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include <stdio.h>
-
-int main(int argc, char* argv[])
-{
- Should not be build unless target directory A, B, or C are build;
- return 0;
-}
diff --git a/Tests/SimpleExclude/dirC/dirA/t4.c b/Tests/SimpleExclude/dirC/dirA/t4.c
deleted file mode 100644
index b0e400014..000000000
--- a/Tests/SimpleExclude/dirC/dirA/t4.c
+++ /dev/null
@@ -1,17 +0,0 @@
-#include <stdio.h>
-
-#ifdef __CLASSIC_C__
-int main()
-{
- int ac;
- char* av[];
-#else
-int main(int ac, char* av[])
-{
-#endif
- if (ac > 1000) {
- return *av[0];
- }
- printf("This is T4. This one should work.\n");
- return 0;
-}
diff --git a/Tests/SimpleExclude/dirC/dirA/t5.c b/Tests/SimpleExclude/dirC/dirA/t5.c
deleted file mode 100644
index 1fba2127c..000000000
--- a/Tests/SimpleExclude/dirC/dirA/t5.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include <stdio.h>
-
-int main(int argc, char* argv[])
-{
- Should not be build unless target directory A, B, or C are build;
- return 5;
-}
diff --git a/Tests/SimpleExclude/dirC/dirB/CMakeLists.txt b/Tests/SimpleExclude/dirC/dirB/CMakeLists.txt
deleted file mode 100644
index ea4650c4a..000000000
--- a/Tests/SimpleExclude/dirC/dirB/CMakeLists.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-add_library(t6 STATIC t6.c)
-
-add_library(t7 STATIC t7.c)
-target_link_libraries(t7 t2)
-
diff --git a/Tests/SimpleExclude/dirC/dirB/t6.c b/Tests/SimpleExclude/dirC/dirB/t6.c
deleted file mode 100644
index e8877df60..000000000
--- a/Tests/SimpleExclude/dirC/dirB/t6.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include <stdio.h>
-
-int tlib6func()
-{
- Should not be build unless target directory B, or C are build;
- printf("This is T6\n");
- return 6;
-}
diff --git a/Tests/SimpleExclude/dirC/dirB/t7.c b/Tests/SimpleExclude/dirC/dirB/t7.c
deleted file mode 100644
index b613e9175..000000000
--- a/Tests/SimpleExclude/dirC/dirB/t7.c
+++ /dev/null
@@ -1,15 +0,0 @@
-#include <stdio.h>
-
-extern int tlib2func();
-
-int tlib7func()
-{
- printf("This is T7\n");
-
- if (tlib2func() != 2) {
- fprintf(stderr, "Something wrong with T2\n");
- return 1;
- }
-
- return 7;
-}
diff --git a/Tests/SimpleExclude/dirD/CMakeLists.txt b/Tests/SimpleExclude/dirD/CMakeLists.txt
deleted file mode 100644
index 44b8c27b6..000000000
--- a/Tests/SimpleExclude/dirD/CMakeLists.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-add_library(t8 STATIC t8.c)
-
-add_executable(t9 t9.c)
-target_link_libraries(t9 t7)
-
-add_custom_target(t4_custom ALL)
-add_dependencies(t4_custom t4)
diff --git a/Tests/SimpleExclude/dirD/t8.c b/Tests/SimpleExclude/dirD/t8.c
deleted file mode 100644
index bddec6f7e..000000000
--- a/Tests/SimpleExclude/dirD/t8.c
+++ /dev/null
@@ -1,7 +0,0 @@
-#include <stdio.h>
-
-int tlib8func()
-{
- printf("This is T8\n");
- return 8;
-}
diff --git a/Tests/SimpleExclude/dirD/t9.c b/Tests/SimpleExclude/dirD/t9.c
deleted file mode 100644
index 9954ea567..000000000
--- a/Tests/SimpleExclude/dirD/t9.c
+++ /dev/null
@@ -1,24 +0,0 @@
-#include <stdio.h>
-
-extern int tlib7func();
-
-#ifdef __CLASSIC_C__
-int main()
-{
- int ac;
- char* av[];
-#else
-int main(int ac, char* av[])
-{
-#endif
- if (ac > 1000) {
- return *av[0];
- }
- printf("This is T9. This one should work.\n");
-
- if (tlib7func() != 7) {
- fprintf(stderr, "Something wrong with T7\n");
- return 1;
- }
- return 0;
-}
diff --git a/Tests/SimpleExclude/run.cmake.in b/Tests/SimpleExclude/run.cmake.in
deleted file mode 100644
index d31d2e51b..000000000
--- a/Tests/SimpleExclude/run.cmake.in
+++ /dev/null
@@ -1,13 +0,0 @@
-set(t4_name "\"@CMAKE_CURRENT_BINARY_DIR@${CFG_DIR}/t4\"")
-exec_program("${t4_name}" RETURN_VALUE "t4_var")
-message("T4 ${t4_name} resulted ${t4_var}")
-
-set(t9_name "\"@CMAKE_CURRENT_BINARY_DIR@${CFG_DIR}/t9\"")
-exec_program("${t9_name}" RETURN_VALUE "t9_var")
-message("T9 ${t9_name} resulted ${t9_var}")
-
-if ( "${t4_var}" EQUAL "0" AND "${t9_var}" EQUAL "0" )
- message("Everything is good, Yoshimi won...")
-else ()
- message(FATAL_ERROR "Yoshimi lost... The evil pink robots will take over the world")
-endif ()
diff --git a/Tests/SimpleInstall/scripts/.gitattributes b/Tests/SimpleInstall/scripts/.gitattributes
deleted file mode 100644
index 5e3db2fb3..000000000
--- a/Tests/SimpleInstall/scripts/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-sample_script crlf=input
diff --git a/Tests/SimpleInstallS2/scripts/.gitattributes b/Tests/SimpleInstallS2/scripts/.gitattributes
deleted file mode 100644
index 5e3db2fb3..000000000
--- a/Tests/SimpleInstallS2/scripts/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-sample_script crlf=input
diff --git a/Tests/TargetName/scripts/.gitattributes b/Tests/TargetName/scripts/.gitattributes
deleted file mode 100644
index 51b8ce901..000000000
--- a/Tests/TargetName/scripts/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-hello_world crlf=input
diff --git a/Tests/VSGNUFortran/runtest.cmake.in b/Tests/VSGNUFortran/runtest.cmake.in
index 987207bc4..fc05715d3 100644
--- a/Tests/VSGNUFortran/runtest.cmake.in
+++ b/Tests/VSGNUFortran/runtest.cmake.in
@@ -14,7 +14,7 @@ file(TO_NATIVE_PATH "${MINGW_PATH}" MINGW_PATH)
string(REPLACE "\\" "\\\\" MINGW_PATH "${MINGW_PATH}")
message("${MINGW_PATH}")
set(test_exe "@VSGNUFortran_BINARY_DIR@/bin/c_using_fortran.exe")
-set(ENV{PATH} "${MINGW_PATH}";$ENV{PATH})
+set(ENV{PATH} "${MINGW_PATH};$ENV{PATH}")
message("run ${test_exe}")
execute_process(COMMAND "${test_exe}"
RESULT_VARIABLE res)
diff --git a/Tests/VSResource/CMakeLists.txt b/Tests/VSResource/CMakeLists.txt
index 718e62441..fb47c7e13 100644
--- a/Tests/VSResource/CMakeLists.txt
+++ b/Tests/VSResource/CMakeLists.txt
@@ -56,3 +56,10 @@ endif()
set_property(TARGET VSResource
PROPERTY VS_GLOBAL_CMakeTestVsGlobalVariable "test val")
+
+if(CMAKE_GENERATOR MATCHES "Ninja|Visual Studio")
+ cmake_policy(PUSH)
+ cmake_policy(SET CMP0037 OLD)
+ add_library("My ResourceLib" lib.cpp lib.rc)
+ cmake_policy(POP)
+endif()
diff --git a/Tests/VSWinStorePhone/CMakeLists.txt b/Tests/VSWinStorePhone/CMakeLists.txt
index 2b0c47806..acda11735 100644
--- a/Tests/VSWinStorePhone/CMakeLists.txt
+++ b/Tests/VSWinStorePhone/CMakeLists.txt
@@ -116,12 +116,14 @@ set_property(SOURCE ${RELEASE_CONTENT_FILES} PROPERTY
set_property(SOURCE ${PIXELSHADER_FILES} PROPERTY VS_SHADER_TYPE Pixel)
set_property(SOURCE ${PIXELSHADER_FILES} PROPERTY VS_SHADER_ENTRYPOINT mainPS)
set_property(SOURCE ${PIXELSHADER_FILES} PROPERTY VS_SHADER_MODEL 4.0_level_9_3)
-set_property(SOURCE ${PIXELSHADER_FILES} PROPERTY VS_SHADER_FLAGS "/DFLAGS_ADDED /Fh \"$(OutDir)%(Filename).h\"")
+set_property(SOURCE ${PIXELSHADER_FILES} PROPERTY VS_SHADER_FLAGS "/DFLAGS_ADDED")
+set_property(SOURCE ${PIXELSHADER_FILES} PROPERTY VS_SHADER_OUTPUT_HEADER_FILE "$(OutDir)%(Filename).h")
set_property(SOURCE ${VERTEXSHADER_FILES} PROPERTY VS_SHADER_TYPE Vertex)
set_property(SOURCE ${VERTEXSHADER_FILES} PROPERTY VS_SHADER_ENTRYPOINT mainVS)
set_property(SOURCE ${VERTEXSHADER_FILES} PROPERTY VS_SHADER_MODEL 4.0_level_9_3)
-set_property(SOURCE ${VERTEXSHADER_FILES} PROPERTY VS_SHADER_FLAGS "/DFLAGS_ADDED /Fh \"$(OutDir)%(Filename).h\"")
+set_property(SOURCE ${VERTEXSHADER_FILES} PROPERTY VS_SHADER_FLAGS "/DFLAGS_ADDED")
+set_property(SOURCE ${VERTEXSHADER_FILES} PROPERTY VS_SHADER_OUTPUT_HEADER_FILE "$(OutDir)%(Filename).h")
source_group("Source Files" FILES ${SOURCE_FILES})
diff --git a/Tests/XCTest/CMakeLists.txt b/Tests/XCTest/CMakeLists.txt
index d40c40e2a..d0b07ea1c 100644
--- a/Tests/XCTest/CMakeLists.txt
+++ b/Tests/XCTest/CMakeLists.txt
@@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.1)
-project(XCTest)
+project(XCTest C)
enable_testing()
find_package(XCTest REQUIRED)
diff --git a/Tests/bootstrap.bat.in b/Tests/bootstrap.bat.in
index aeb24b1ca..85e79ef00 100644
--- a/Tests/bootstrap.bat.in
+++ b/Tests/bootstrap.bat.in
@@ -1,2 +1,2 @@
-@echo off
-sh "@CMake_SOURCE_DIR@/bootstrap" %*
+@echo off
+sh "@CMake_SOURCE_DIR@/bootstrap" %*
diff --git a/Utilities/.gitattributes b/Utilities/.gitattributes
deleted file mode 100644
index bd978021b..000000000
--- a/Utilities/.gitattributes
+++ /dev/null
@@ -1,7 +0,0 @@
-/Git export-ignore
-/GitSetup export-ignore
-SetupForDevelopment.sh export-ignore
-
-# Do not format third-party sources.
-/KWIML/** -format.clang-format
-/cm*/** -format.clang-format
diff --git a/Utilities/Doxygen/CMakeLists.txt b/Utilities/Doxygen/CMakeLists.txt
index f1e8f95e7..6a90c8474 100644
--- a/Utilities/Doxygen/CMakeLists.txt
+++ b/Utilities/Doxygen/CMakeLists.txt
@@ -3,7 +3,7 @@
if(NOT CMake_SOURCE_DIR)
set(CMakeDeveloperReference_STANDALONE 1)
- cmake_minimum_required(VERSION 2.8.12.2 FATAL_ERROR)
+ cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
get_filename_component(tmp "${CMAKE_CURRENT_SOURCE_DIR}" PATH)
get_filename_component(CMake_SOURCE_DIR "${tmp}" PATH)
include(${CMake_SOURCE_DIR}/Modules/CTestUseLaunchers.cmake)
diff --git a/Utilities/GitSetup/.gitattributes b/Utilities/GitSetup/.gitattributes
deleted file mode 100644
index e96d1f8c5..000000000
--- a/Utilities/GitSetup/.gitattributes
+++ /dev/null
@@ -1,6 +0,0 @@
-.git* export-ignore
-
-config* eol=lf whitespace=indent-with-non-tab
-git-* eol=lf whitespace=indent-with-non-tab
-tips eol=lf whitespace=indent-with-non-tab
-setup-* eol=lf whitespace=indent-with-non-tab
diff --git a/Utilities/IWYU/mapping.imp b/Utilities/IWYU/mapping.imp
index fe0f7df71..3240edf31 100644
--- a/Utilities/IWYU/mapping.imp
+++ b/Utilities/IWYU/mapping.imp
@@ -21,6 +21,7 @@
{ include: [ "<wctype.h>", public, "<cwctype>", public ] },
# HACK: check whether this can be removed with next iwyu release.
+ { include: [ "<bits/shared_ptr.h>", private, "<memory>", public ] },
{ include: [ "<bits/std_function.h>", private, "<functional>", public ] },
{ include: [ "<bits/time.h>", private, "<time.h>", public ] },
{ include: [ "<bits/types/clock_t.h>", private, "<time.h>", public ] },
@@ -48,12 +49,6 @@
#{ symbol: [ "std::pair", private, "<map>", public ] },
#{ symbol: [ "std::pair", private, "<set>", public ] },
- # IWYU wrongly suggests to include "cm_auto_ptr.hxx" in some places. This
- # might be a misinterpretation of a template specialization in <utility>.
- # As a workaround, map the symbol auto_ptr to "cmConfigure.h".
- # This will still correctly require "cm_auto_ptr.hxx" for CM_AUTO_PTR.
- { symbol: [ "cm::auto_ptr", private, "\"cmConfigure.h\"", public ] },
-
# __decay_and_strip is used internally in the C++11 standard library.
# IWYU does not classify it as internal and suggests to add <type_traits>.
# To ignore it, we simply map it to a file that is included anyway.
@@ -67,18 +62,6 @@
{ symbol: [ "std::__decay_and_strip<cmFindPackageCommand::PathLabel &>::__type", private, "\"cmConfigure.h\"", public ] },
{ symbol: [ "std::__decay_and_strip<__gnu_cxx::__normal_iterator<const cmCTestTestHandler::cmCTestTestProperties *, std::vector<cmCTestTestHandler::cmCTestTestProperties, std::allocator<cmCTestTestHandler::cmCTestTestProperties> > > &>::__type", private, "\"cmConfigure.h\"", public ] },
- # Wrappers for headers added in TR1 / C++11
- # { include: [ "<array>", public, "\"cm_array.hxx\"", public ] },
- # { include: [ "<functional>", public, "\"cm_functional.hxx\"", public ] },
- # { include: [ "<memory>", public, "\"cm_memory.hxx\"", public ] },
- { include: [ "<unordered_map>", public, "\"cm_unordered_map.hxx\"", public ] },
- { include: [ "<unordered_set>", public, "\"cm_unordered_set.hxx\"", public ] },
- # { include: [ "<tr1/array>", public, "\"cm_array.hxx\"", public ] },
- # { include: [ "<tr1/functional>", public, "\"cm_functional.hxx\"", public ] },
- # { include: [ "<tr1/memory>", public, "\"cm_memory.hxx\"", public ] },
- { include: [ "<tr1/unordered_map>", public, "\"cm_unordered_map.hxx\"", public ] },
- { include: [ "<tr1/unordered_set>", public, "\"cm_unordered_set.hxx\"", public ] },
-
# KWIML
{ include: [ "<stdint.h>", public, "\"cm_kwiml.h\"", public ] },
{ include: [ "<inttypes.h>", public, "\"cm_kwiml.h\"", public ] },
@@ -87,14 +70,6 @@
{ include: [ "<sys/stat.h>", public, "\"cm_sys_stat.h\"", public ] },
{ symbol: [ "mode_t", private, "\"cm_sys_stat.h\"", public ] },
- # TODO: remove once TR1 / C++11 is required.
- { include: [ "\"cmsys/hash_fun.hxx\"", private, "\"cm_unordered_map.hxx\"", public ] },
- { include: [ "\"cmsys/hash_fun.hxx\"", private, "\"cm_unordered_set.hxx\"", public ] },
- { include: [ "\"cmsys/hash_map.hxx\"", private, "\"cm_unordered_map.hxx\"", public ] },
- { include: [ "\"cmsys/hash_set.hxx\"", private, "\"cm_unordered_set.hxx\"", public ] },
- { include: [ "\"cmsys/hashtable.hxx\"", private, "\"cm_unordered_map.hxx\"", public ] },
- { include: [ "\"cmsys/hashtable.hxx\"", private, "\"cm_unordered_set.hxx\"", public ] },
-
# Wrappers for 3rd-party libraries used from the system.
{ include: [ "<archive.h>", private, "\"cm_libarchive.h\"", public ] },
{ include: [ "<archive_entry.h>", private, "\"cm_libarchive.h\"", public ] },
diff --git a/Utilities/KWIML/.gitattributes b/Utilities/KWIML/.gitattributes
deleted file mode 100644
index ecbf2196c..000000000
--- a/Utilities/KWIML/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-*.md conflict-marker-size=78
diff --git a/Utilities/Release/linux64_release.cmake b/Utilities/Release/linux64_release.cmake
index 3d8ddba3c..02742ad0e 100644
--- a/Utilities/Release/linux64_release.cmake
+++ b/Utilities/Release/linux64_release.cmake
@@ -36,7 +36,6 @@ PYTHON_EXECUTABLE:FILEPATH=/usr/bin/python3
CPACK_SYSTEM_NAME:STRING=Linux-x86_64
BUILD_QtDialog:BOOL:=TRUE
CMAKE_SKIP_BOOTSTRAP_TEST:STRING=TRUE
-CMake_ENABLE_SERVER_MODE:BOOL=TRUE
CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3
CMake_INSTALL_DEPENDENCIES:BOOL=ON
CMAKE_PREFIX_PATH:STRING=${qt_prefix}
diff --git a/Utilities/Release/osx_release.cmake b/Utilities/Release/osx_release.cmake
index 36498a7ce..c69eb1187 100644
--- a/Utilities/Release/osx_release.cmake
+++ b/Utilities/Release/osx_release.cmake
@@ -20,7 +20,6 @@ CMAKE_OSX_DEPLOYMENT_TARGET:STRING=10.7
CMAKE_SKIP_BOOTSTRAP_TEST:STRING=TRUE
CPACK_SYSTEM_NAME:STRING=Darwin-x86_64
BUILD_QtDialog:BOOL=TRUE
-CMake_ENABLE_SERVER_MODE:BOOL=TRUE
CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3
CMake_INSTALL_DEPENDENCIES:BOOL=ON
CMAKE_SKIP_RPATH:BOOL=TRUE
diff --git a/Utilities/Release/upload_release.cmake b/Utilities/Release/upload_release.cmake
index 5b2cc5732..3c839578a 100644
--- a/Utilities/Release/upload_release.cmake
+++ b/Utilities/Release/upload_release.cmake
@@ -1,6 +1,6 @@
set(CTEST_RUN_CURRENT_SCRIPT 0)
if(NOT VERSION)
- set(VERSION 3.9)
+ set(VERSION 3.10)
endif()
if(NOT DEFINED PROJECT_PREFIX)
set(PROJECT_PREFIX cmake-${VERSION})
diff --git a/Utilities/Release/win32_release.cmake b/Utilities/Release/win32_release.cmake
index df9fe275b..f54a4ca40 100644
--- a/Utilities/Release/win32_release.cmake
+++ b/Utilities/Release/win32_release.cmake
@@ -15,7 +15,6 @@ CMAKE_SKIP_BOOTSTRAP_TEST:STRING=TRUE
CMAKE_Fortran_COMPILER:FILEPATH=FALSE
CMAKE_GENERATOR:INTERNAL=Ninja
BUILD_QtDialog:BOOL:=TRUE
-CMake_ENABLE_SERVER_MODE:BOOL=TRUE
CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3
CMake_INSTALL_DEPENDENCIES:BOOL=ON
CMAKE_EXE_LINKER_FLAGS:STRING=-machine:x86 -subsystem:console,5.01
diff --git a/Utilities/Release/win64_release.cmake b/Utilities/Release/win64_release.cmake
index ab52d794d..bd2690f4e 100644
--- a/Utilities/Release/win64_release.cmake
+++ b/Utilities/Release/win64_release.cmake
@@ -16,7 +16,6 @@ CMAKE_SKIP_BOOTSTRAP_TEST:STRING=TRUE
CMAKE_Fortran_COMPILER:FILEPATH=FALSE
CMAKE_GENERATOR:INTERNAL=Ninja
BUILD_QtDialog:BOOL:=TRUE
-CMake_ENABLE_SERVER_MODE:BOOL=TRUE
CMake_GUI_DISTRIBUTE_WITH_Qt_LGPL:STRING=3
CMake_INSTALL_DEPENDENCIES:BOOL=ON
CMAKE_EXE_LINKER_FLAGS:STRING=-machine:x64 -subsystem:console,5.02
diff --git a/Utilities/Scripts/BoostScanDeps.cmake b/Utilities/Scripts/BoostScanDeps.cmake
index 2fd8f8633..bd2e6a879 100644
--- a/Utilities/Scripts/BoostScanDeps.cmake
+++ b/Utilities/Scripts/BoostScanDeps.cmake
@@ -39,29 +39,40 @@ function(_Boost_FIND_COMPONENT_DEPENDENCIES component includedir _ret_libs)
# Start by finding all headers for the component; header
# dependencies via #include will be solved by future passes
+ file(GLOB_RECURSE _boost_mpi_python_headers
+ RELATIVE "${includedir}"
+ "${includedir}/boost/mpi/python/*")
+ list(INSERT _boost_mpi_python_headers 0 "boost/mpi/python.hpp")
+
+ file(GLOB_RECURSE _boost_python_numpy_headers
+ RELATIVE "${includedir}"
+ "${includedir}/boost/python/numpy/*")
+ list(INSERT _boost_python_numpy_headers 0 "boost/python/numpy.hpp")
# Special-case since it is part of mpi; look only in boost/mpi/python*
if(component STREQUAL "mpi_python")
set(_boost_DEPS "python")
set(library_component TRUE)
- file(GLOB_RECURSE _boost_unprocessed_headers
- RELATIVE "${includedir}"
- "${includedir}/boost/mpi/python/*")
- list(INSERT _boost_unprocessed_headers 0 "${includedir}/boost/mpi/python.hpp")
+ set(_boost_unprocessed_headers ${_boost_mpi_python_headers})
+ # Special-case since it is part of python; look only in boost/python/numpy*
+ elseif(component STREQUAL "numpy")
+ set(_boost_DEPS "python")
+ set(library_component TRUE)
+ set(_boost_unprocessed_headers ${_boost_python_numpy_headers})
# Special-case since it is a serialization variant; look in boost/serialization
elseif(component STREQUAL "wserialization")
set(library_component TRUE)
file(GLOB_RECURSE _boost_unprocessed_headers
RELATIVE "${includedir}"
"${includedir}/boost/serialization/*")
- list(INSERT _boost_unprocessed_headers 0 "${includedir}/boost/serialization.hpp")
+ list(INSERT _boost_unprocessed_headers 0 "boost/serialization.hpp")
# Not really a library in its own right, but treat it as one
elseif(component STREQUAL "math")
set(library_component TRUE)
file(GLOB_RECURSE _boost_unprocessed_headers
RELATIVE "${includedir}"
"${includedir}/boost/math/*")
- list(INSERT _boost_unprocessed_headers 0 "${includedir}/boost/math.hpp")
+ list(INSERT _boost_unprocessed_headers 0 "boost/math.hpp")
# Single test header
elseif(component STREQUAL "unit_test_framework")
set(library_component TRUE)
@@ -79,7 +90,8 @@ function(_Boost_FIND_COMPONENT_DEPENDENCIES component includedir _ret_libs)
file(GLOB_RECURSE _boost_unprocessed_headers
RELATIVE "${includedir}"
"${includedir}/boost/${component}/*")
- list(INSERT _boost_unprocessed_headers 0 "${includedir}/boost/${component}.hpp")
+ list(INSERT _boost_unprocessed_headers 0 "boost/${component}.hpp")
+ list(REMOVE_ITEM _boost_unprocessed_headers ${_boost_mpi_python_headers} ${_boost_python_numpy_headers})
endif()
while(_boost_unprocessed_headers)
@@ -102,6 +114,8 @@ function(_Boost_FIND_COMPONENT_DEPENDENCIES component includedir _ret_libs)
foreach(line ${_boost_header_deps})
string(REGEX REPLACE "^[ \t]*#[ \t]*define[ \t][ \t]*BOOST_LIB_NAME[ \t][ \t]*boost_([^ \t][^ \t]*).*" "\\1" _boost_component_match "${line}")
+ string(REPLACE "python3" "python" _boost_component_match "${_boost_component_match}")
+ string(REPLACE "numpy3" "numpy" _boost_component_match "${_boost_component_match}")
list(FIND _boost_DEPS "${_boost_component_match}" _boost_dep_found)
if(_boost_component_match STREQUAL "bzip2" OR
_boost_component_match STREQUAL "zlib")
@@ -119,6 +133,12 @@ function(_Boost_FIND_COMPONENT_DEPENDENCIES component includedir _ret_libs)
# hard dependency (handle as special-case for mpi_python).
continue()
endif()
+ if(component STREQUAL "python" AND
+ boost_component_match STREQUAL "numpy")
+ # Optional python dependency; skip to avoid making it a
+ # hard dependency (handle as special-case for numpy).
+ continue()
+ endif()
if (_boost_dep_found EQUAL -1 AND
NOT "${_boost_component_match}" STREQUAL "${component}")
list(APPEND _boost_DEPS "${_boost_component_match}")
@@ -168,6 +188,11 @@ if(IS_DIRECTORY "${BOOST_DIR}/boost/mpi" AND
IS_DIRECTORY "${BOOST_DIR}/boost/python")
list(APPEND boost_components "mpi_python")
endif()
+# Special-case numpy, since it's a part of python
+if(IS_DIRECTORY "${BOOST_DIR}/boost/python" AND
+ IS_DIRECTORY "${BOOST_DIR}/boost/python/numpy")
+ list(APPEND boost_components "numpy")
+endif()
# Special-case wserialization, which is a variant of serialization
if(IS_DIRECTORY "${BOOST_DIR}/boost/serialization")
list(APPEND boost_components "wserialization")
diff --git a/Utilities/Scripts/clang-format.bash b/Utilities/Scripts/clang-format.bash
index edcda77b9..3b331a18f 100755
--- a/Utilities/Scripts/clang-format.bash
+++ b/Utilities/Scripts/clang-format.bash
@@ -92,7 +92,7 @@ fi
# Verify that we have a tool.
if ! type -p "$clang_format" >/dev/null; then
- echo "Unable to locate '$clang_format'"
+ echo "Unable to locate a 'clang-format' tool."
exit 1
fi
@@ -111,7 +111,9 @@ $git_ls |
# Select sources with our attribute.
git check-attr --stdin format.clang-format |
- sed -n '/: format\.clang-format: set$/ {s/:[^:]*:[^:]*$//p}' |
+ grep -e ': format\.clang-format: set$' |
+ sed -n 's/:[^:]*:[^:]*$//p' |
# Update sources in-place.
- xargs -d '\n' "$clang_format" -i
+ tr '\n' '\0' |
+ xargs -0 "$clang_format" -i
diff --git a/Utilities/Scripts/regenerate-lexers.bash b/Utilities/Scripts/regenerate-lexers.bash
new file mode 100755
index 000000000..22b681faa
--- /dev/null
+++ b/Utilities/Scripts/regenerate-lexers.bash
@@ -0,0 +1,33 @@
+#!/usr/bin/env bash
+
+set -e
+
+pushd "${BASH_SOURCE%/*}/../../Source/LexerParser" > /dev/null
+
+for lexer in \
+ CommandArgument \
+ DependsJava \
+ Expr \
+ Fortran
+do
+ echo "Generating Lexer ${lexer}"
+ flex --nounistd -DFLEXINT_H --noline --header-file=cm${lexer}Lexer.h -ocm${lexer}Lexer.cxx cm${lexer}Lexer.in.l
+ sed -i 's/\s*$//' cm${lexer}Lexer.h cm${lexer}Lexer.cxx # remove trailing whitespaces
+ sed -i '${/^$/d;}' cm${lexer}Lexer.h cm${lexer}Lexer.cxx # remove blank line at the end
+ sed -i '1i#include "cmStandardLexer.h"' cm${lexer}Lexer.cxx # add cmStandardLexer.h include
+done
+
+
+# these lexers (at the moment only the ListFileLexer) are compiled as C and do not generate a header
+for lexer in ListFile
+do
+
+ echo "Generating Lexer ${lexer}"
+ flex --nounistd -DFLEXINT_H --noline -ocm${lexer}Lexer.c cm${lexer}Lexer.in.l
+ sed -i 's/\s*$//' cm${lexer}Lexer.c # remove trailing whitespaces
+ sed -i '${/^$/d;}' cm${lexer}Lexer.c # remove blank line at the end
+ sed -i '1i#include "cmStandardLexer.h"' cm${lexer}Lexer.c # add cmStandardLexer.h include
+
+done
+
+popd > /dev/null
diff --git a/Utilities/Scripts/update-curl.bash b/Utilities/Scripts/update-curl.bash
index 465841a02..b24482734 100755
--- a/Utilities/Scripts/update-curl.bash
+++ b/Utilities/Scripts/update-curl.bash
@@ -8,14 +8,13 @@ readonly name="curl"
readonly ownership="Curl Upstream <curl-library@cool.haxx.se>"
readonly subtree="Utilities/cmcurl"
readonly repo="https://github.com/curl/curl.git"
-readonly tag="curl-7_54_1"
+readonly tag="curl-7_56_0"
readonly shortlog=false
readonly paths="
CMake/*
CMakeLists.txt
COPYING
include/curl/*.h
- include/curl/curlbuild.h.cmake
lib/*.c
lib/*.h
lib/CMakeLists.txt
@@ -32,6 +31,15 @@ extract_source () {
git_archive
pushd "${extractdir}/${name}-reduced"
rm lib/config-*.h
+ chmod a-x lib/connect.c
+ for f in \
+ lib/cookie.c \
+ lib/krb5.c \
+ lib/security.c \
+ ; do
+ iconv -f LATIN1 -t UTF8 $f -o $f.utf-8
+ mv $f.utf-8 $f
+ done
echo "* -whitespace" > .gitattributes
popd
}
diff --git a/Utilities/Scripts/update-jsoncpp.bash b/Utilities/Scripts/update-jsoncpp.bash
new file mode 100755
index 000000000..f8fe54462
--- /dev/null
+++ b/Utilities/Scripts/update-jsoncpp.bash
@@ -0,0 +1,33 @@
+#!/usr/bin/env bash
+
+set -e
+set -x
+shopt -s dotglob
+
+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 shortlog=false
+readonly paths="
+ LICENSE
+ include/json
+ src/lib_json
+"
+readonly remove="
+ include/json/autolink.h
+ src/lib_json/CMakeLists.txt
+ src/lib_json/sconscript
+ src/lib_json/version.h.in
+"
+
+extract_source () {
+ git_archive
+ pushd "${extractdir}/${name}-reduced"
+ rm $remove
+ echo "* -whitespace" > .gitattributes
+ popd
+}
+
+. "${BASH_SOURCE%/*}/update-third-party.bash"
diff --git a/Utilities/Scripts/update-libarchive.bash b/Utilities/Scripts/update-libarchive.bash
index 41c6a66d6..7534f9447 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.3.1"
+readonly tag="v3.3.2"
readonly shortlog=false
readonly paths="
CMakeLists.txt
diff --git a/Utilities/Sphinx/.gitignore b/Utilities/Sphinx/.gitignore
deleted file mode 100644
index 0d20b6487..000000000
--- a/Utilities/Sphinx/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-*.pyc
diff --git a/Utilities/Sphinx/CMakeLists.txt b/Utilities/Sphinx/CMakeLists.txt
index a29380c95..2de821c2b 100644
--- a/Utilities/Sphinx/CMakeLists.txt
+++ b/Utilities/Sphinx/CMakeLists.txt
@@ -3,7 +3,7 @@
if(NOT CMake_SOURCE_DIR)
set(CMakeHelp_STANDALONE 1)
- cmake_minimum_required(VERSION 2.8.12.2 FATAL_ERROR)
+ cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
get_filename_component(tmp "${CMAKE_CURRENT_SOURCE_DIR}" PATH)
get_filename_component(CMake_SOURCE_DIR "${tmp}" PATH)
include(${CMake_SOURCE_DIR}/Modules/CTestUseLaunchers.cmake)
diff --git a/Utilities/cmbzip2/dlltest.dsp b/Utilities/cmbzip2/dlltest.dsp
deleted file mode 100644
index 4b1615edc..000000000
--- a/Utilities/cmbzip2/dlltest.dsp
+++ /dev/null
@@ -1,93 +0,0 @@
-# Microsoft Developer Studio Project File - Name="dlltest" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 5.00
-# ** •ÒW‚µ‚È‚¢‚Å‚­‚¾‚³‚¢ **
-
-# TARGTYPE "Win32 (x86) Console Application" 0x0103
-
-CFG=dlltest - Win32 Debug
-!MESSAGE ‚±‚ê‚Í—LŒø‚ÈÒ²¸Ì§²Ù‚Å‚Í‚ ‚è‚Ü‚¹‚ñB ‚±‚ÌÌßÛ¼Þª¸Ä‚ðËÞÙÄÞ‚·‚邽‚ß‚É‚Í NMAKE ‚ðŽg—p‚µ‚Ä‚­‚¾‚³‚¢B
-!MESSAGE [Ò²¸Ì§²Ù‚Ì´¸½Îß°Ä] ºÏÝÄÞ‚ðŽg—p‚µ‚ÄŽÀs‚µ‚Ä‚­‚¾‚³‚¢
-!MESSAGE
-!MESSAGE NMAKE /f "dlltest.mak".
-!MESSAGE
-!MESSAGE NMAKE ‚ÌŽÀsŽž‚É\¬‚ðŽw’è‚Å‚«‚Ü‚·
-!MESSAGE ºÏÝÄÞ ×²Ýã‚ÅϸۂÌÝ’è‚ð’è‹`‚µ‚Ü‚·B—á:
-!MESSAGE
-!MESSAGE NMAKE /f "dlltest.mak" CFG="dlltest - Win32 Debug"
-!MESSAGE
-!MESSAGE ‘I‘ð‰Â”\‚ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE
-!MESSAGE "dlltest - Win32 Release" ("Win32 (x86) Console Application" —p)
-!MESSAGE "dlltest - Win32 Debug" ("Win32 (x86) Console Application" —p)
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-RSC=rc.exe
-
-!IF "$(CFG)" == "dlltest - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
-# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
-# ADD BASE RSC /l 0x411 /d "NDEBUG"
-# ADD RSC /l 0x411 /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 /out:"minibz2.exe"
-
-!ELSEIF "$(CFG)" == "dlltest - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "dlltest_"
-# PROP BASE Intermediate_Dir "dlltest_"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "dlltest_"
-# PROP Intermediate_Dir "dlltest_"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
-# ADD CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
-# ADD BASE RSC /l 0x411 /d "_DEBUG"
-# ADD RSC /l 0x411 /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /out:"minibz2.exe" /pdbtype:sept
-
-!ENDIF
-
-# Begin Target
-
-# Name "dlltest - Win32 Release"
-# Name "dlltest - Win32 Debug"
-# Begin Source File
-
-SOURCE=.\bzlib.h
-# End Source File
-# Begin Source File
-
-SOURCE=.\dlltest.c
-# End Source File
-# End Target
-# End Project
diff --git a/Utilities/cmbzip2/libbz2.dsp b/Utilities/cmbzip2/libbz2.dsp
deleted file mode 100644
index a21a20f75..000000000
--- a/Utilities/cmbzip2/libbz2.dsp
+++ /dev/null
@@ -1,130 +0,0 @@
-# Microsoft Developer Studio Project File - Name="libbz2" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 5.00
-# ** •ÒW‚µ‚È‚¢‚Å‚­‚¾‚³‚¢ **
-
-# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
-
-CFG=libbz2 - Win32 Debug
-!MESSAGE ‚±‚ê‚Í—LŒø‚ÈÒ²¸Ì§²Ù‚Å‚Í‚ ‚è‚Ü‚¹‚ñB ‚±‚ÌÌßÛ¼Þª¸Ä‚ðËÞÙÄÞ‚·‚邽‚ß‚É‚Í NMAKE ‚ðŽg—p‚µ‚Ä‚­‚¾‚³‚¢B
-!MESSAGE [Ò²¸Ì§²Ù‚Ì´¸½Îß°Ä] ºÏÝÄÞ‚ðŽg—p‚µ‚ÄŽÀs‚µ‚Ä‚­‚¾‚³‚¢
-!MESSAGE
-!MESSAGE NMAKE /f "libbz2.mak".
-!MESSAGE
-!MESSAGE NMAKE ‚ÌŽÀsŽž‚É\¬‚ðŽw’è‚Å‚«‚Ü‚·
-!MESSAGE ºÏÝÄÞ ×²Ýã‚ÅϸۂÌÝ’è‚ð’è‹`‚µ‚Ü‚·B—á:
-!MESSAGE
-!MESSAGE NMAKE /f "libbz2.mak" CFG="libbz2 - Win32 Debug"
-!MESSAGE
-!MESSAGE ‘I‘ð‰Â”\‚ÈËÞÙÄÞ Ó°ÄÞ:
-!MESSAGE
-!MESSAGE "libbz2 - Win32 Release" ("Win32 (x86) Dynamic-Link Library" —p)
-!MESSAGE "libbz2 - Win32 Debug" ("Win32 (x86) Dynamic-Link Library" —p)
-!MESSAGE
-
-# Begin Project
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-MTL=midl.exe
-RSC=rc.exe
-
-!IF "$(CFG)" == "libbz2 - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
-# ADD CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c
-# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /o NUL /win32
-# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /o NUL /win32
-# ADD BASE RSC /l 0x411 /d "NDEBUG"
-# ADD RSC /l 0x411 /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386 /out:"libbz2.dll"
-
-!ELSEIF "$(CFG)" == "libbz2 - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c
-# ADD CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c
-# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /o NUL /win32
-# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /o NUL /win32
-# ADD BASE RSC /l 0x411 /d "_DEBUG"
-# ADD RSC /l 0x411 /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /out:"libbz2.dll" /pdbtype:sept
-
-!ENDIF
-
-# Begin Target
-
-# Name "libbz2 - Win32 Release"
-# Name "libbz2 - Win32 Debug"
-# Begin Source File
-
-SOURCE=.\blocksort.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\bzlib.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\bzlib.h
-# End Source File
-# Begin Source File
-
-SOURCE=.\bzlib_private.h
-# End Source File
-# Begin Source File
-
-SOURCE=.\compress.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\crctable.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\decompress.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\huffman.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\libbz2.def
-# End Source File
-# Begin Source File
-
-SOURCE=.\randtable.c
-# End Source File
-# End Target
-# End Project
diff --git a/Utilities/cmcurl/.gitattributes b/Utilities/cmcurl/.gitattributes
deleted file mode 100644
index 562b12e16..000000000
--- a/Utilities/cmcurl/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -whitespace
diff --git a/Utilities/cmcurl/CMake/Macros.cmake b/Utilities/cmcurl/CMake/Macros.cmake
index dab005f73..82aadca9d 100644
--- a/Utilities/cmcurl/CMake/Macros.cmake
+++ b/Utilities/cmcurl/CMake/Macros.cmake
@@ -93,3 +93,32 @@ macro(CURL_INTERNAL_TEST_RUN CURL_TEST)
endif(${CURL_TEST}_COMPILE AND NOT ${CURL_TEST})
endif()
endmacro(CURL_INTERNAL_TEST_RUN)
+
+macro(CURL_NROFF_CHECK)
+ find_program(NROFF NAMES gnroff nroff)
+ if(NROFF)
+ # Need a way to write to stdin, this will do
+ file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/nroff-input.txt" "test")
+ # Tests for a valid nroff option to generate a manpage
+ foreach(_MANOPT "-man" "-mandoc")
+ execute_process(COMMAND "${NROFF}" ${_MANOPT}
+ OUTPUT_VARIABLE NROFF_MANOPT_OUTPUT
+ INPUT_FILE "${CMAKE_CURRENT_BINARY_DIR}/nroff-input.txt"
+ ERROR_QUIET)
+ # Save the option if it was valid
+ if(NROFF_MANOPT_OUTPUT)
+ message("Found *nroff option: -- ${_MANOPT}")
+ set(NROFF_MANOPT ${_MANOPT})
+ set(NROFF_USEFUL ON)
+ break()
+ endif()
+ endforeach()
+ # No need for the temporary file
+ file(REMOVE "${CMAKE_CURRENT_BINARY_DIR}/nroff-input.txt")
+ if(NOT NROFF_USEFUL)
+ message(WARNING "Found no *nroff option to get plaintext from man pages")
+ endif()
+ else()
+ message(WARNING "Found no *nroff program")
+ endif()
+endmacro(CURL_NROFF_CHECK)
diff --git a/Utilities/cmcurl/CMake/OtherTests.cmake b/Utilities/cmcurl/CMake/OtherTests.cmake
index 3b203c538..989f04eb2 100644
--- a/Utilities/cmcurl/CMake/OtherTests.cmake
+++ b/Utilities/cmcurl/CMake/OtherTests.cmake
@@ -32,9 +32,9 @@ int main(void) {
if(curl_cv_recv)
if(NOT DEFINED curl_cv_func_recv_args OR "${curl_cv_func_recv_args}" STREQUAL "unknown")
foreach(recv_retv "int" "ssize_t" )
- foreach(recv_arg1 "int" "ssize_t" "SOCKET")
- foreach(recv_arg2 "void *" "char *")
- foreach(recv_arg3 "size_t" "int" "socklen_t" "unsigned int")
+ foreach(recv_arg1 "SOCKET" "int" )
+ foreach(recv_arg2 "char *" "void *" )
+ foreach(recv_arg3 "int" "size_t" "socklen_t" "unsigned int")
foreach(recv_arg4 "int" "unsigned int")
if(NOT curl_cv_func_recv_done)
unset(curl_cv_func_recv_test CACHE)
@@ -96,9 +96,9 @@ int main(void) {
if(curl_cv_send)
if(NOT DEFINED curl_cv_func_send_args OR "${curl_cv_func_send_args}" STREQUAL "unknown")
foreach(send_retv "int" "ssize_t" )
- foreach(send_arg1 "int" "ssize_t" "SOCKET")
- foreach(send_arg2 "const void *" "void *" "char *" "const char *")
- foreach(send_arg3 "size_t" "int" "socklen_t" "unsigned int")
+ foreach(send_arg1 "SOCKET" "int" "ssize_t" )
+ foreach(send_arg2 "const char *" "const void *" "void *" "char *")
+ foreach(send_arg3 "int" "size_t" "socklen_t" "unsigned int")
foreach(send_arg4 "int" "unsigned int")
if(NOT curl_cv_func_send_done)
unset(curl_cv_func_send_test CACHE)
diff --git a/Utilities/cmcurl/CMake/cmake_uninstall.cmake.in b/Utilities/cmcurl/CMake/cmake_uninstall.cmake.in
new file mode 100644
index 000000000..d00a51665
--- /dev/null
+++ b/Utilities/cmcurl/CMake/cmake_uninstall.cmake.in
@@ -0,0 +1,26 @@
+if(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
+ message(FATAL_ERROR "Cannot find install manifest: @CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
+endif(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
+
+if (NOT DEFINED CMAKE_INSTALL_PREFIX)
+ set (CMAKE_INSTALL_PREFIX "@CMAKE_INSTALL_PREFIX@")
+endif ()
+ message(${CMAKE_INSTALL_PREFIX})
+
+file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files)
+string(REGEX REPLACE "\n" ";" files "${files}")
+foreach(file ${files})
+ message(STATUS "Uninstalling $ENV{DESTDIR}${file}")
+ if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
+ exec_program(
+ "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""
+ OUTPUT_VARIABLE rm_out
+ RETURN_VALUE rm_retval
+ )
+ if(NOT "${rm_retval}" STREQUAL 0)
+ message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}")
+ endif(NOT "${rm_retval}" STREQUAL 0)
+ else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
+ message(STATUS "File $ENV{DESTDIR}${file} does not exist.")
+ endif(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
+endforeach(file)
diff --git a/Utilities/cmcurl/CMakeLists.txt b/Utilities/cmcurl/CMakeLists.txt
index d85f366c0..a831f7f4a 100644
--- a/Utilities/cmcurl/CMakeLists.txt
+++ b/Utilities/cmcurl/CMakeLists.txt
@@ -24,6 +24,7 @@ set(CURL_DISABLE_TFTP ON CACHE INTERNAL "Disable curl tftp protocol?")
set(CURL_DISABLE_VERBOSE_STRINGS OFF CACHE INTERNAL "Do not disable curl verbosity")
set(CURL_HIDDEN_SYMBOLS OFF CACHE INTERNAL "No curl hidden symbols")
set(CURL_STATICLIB ON CACHE INTERNAL "Static curl")
+set(CURL_WERROR OFF CACHE INTERNAL "Turn compiler warnings into errors")
set(DISABLED_THREADSAFE OFF CACHE INTERNAL "Curl can use thread-safe functions")
set(ENABLE_ARES OFF CACHE INTERNAL "No curl c-ares support")
set(ENABLE_CURLDEBUG OFF CACHE INTERNAL "No curl TrackMemory features")
@@ -33,6 +34,7 @@ set(ENABLE_MANUAL OFF CACHE INTERNAL "No curl built-in manual")
set(ENABLE_THREADED_RESOLVER OFF CACHE INTERNAL "No curl POSIX threaded DNS lookup")
set(ENABLE_UNIX_SOCKETS OFF CACHE INTERNAL "No curl Unix domain sockets support")
set(HTTP_ONLY OFF CACHE INTERNAL "Curl is not http-only")
+set(PICKY_COMPILER OFF CACHE INTERNAL "Enable picky compiler options")
set(USE_WIN32_LDAP OFF CACHE INTERNAL "No curl Windows LDAP")
if(CMAKE_USE_OPENSSL)
elseif(WIN32)
@@ -88,7 +90,7 @@ endif()
# | (__| |_| | _ <| |___
# \___|\___/|_| \_\_____|
#
-# Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+# Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
@@ -126,6 +128,7 @@ set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/CMake;${CMAKE_MODULE_PATH}")
include(Utilities)
include(Macros)
include(CMakeDependentOption)
+include(CheckCCompilerFlag)
project( CURL C )
@@ -159,20 +162,36 @@ set(OS "\"${CMAKE_SYSTEM_NAME}\"")
include_directories(${PROJECT_BINARY_DIR}/include/curl)
include_directories( ${CURL_SOURCE_DIR}/include )
+option(CURL_WERROR "Turn compiler warnings into errors" OFF)
+option(PICKY_COMPILER "Enable picky compiler options" ON)
option(BUILD_CURL_EXE "Set to ON to build curl executable." ON)
option(CURL_STATICLIB "Set to ON to build libcurl with static linking." OFF)
option(ENABLE_ARES "Set to ON to enable c-ares support" OFF)
if(WIN32)
- CMAKE_DEPENDENT_OPTION(ENABLE_THREADED_RESOLVER
- "Set to ON to enable threaded DNS lookup"
- ON "NOT ENABLE_ARES"
- OFF)
-else()
- option(ENABLE_THREADED_RESOLVER "Set to ON to enable POSIX threaded DNS lookup" OFF)
+ option(CURL_STATIC_CRT "Set to ON to build libcurl with static CRT on Windows (/MT)." OFF)
+ option(ENABLE_INET_PTON "Set to OFF to prevent usage of inet_pton when building against modern SDKs while still requiring compatibility with older Windows versions, such as Windows XP, Windows Server 2003 etc." ON)
endif()
+
+CMAKE_DEPENDENT_OPTION(ENABLE_THREADED_RESOLVER "Set to ON to enable threaded DNS lookup"
+ ON "NOT ENABLE_ARES"
+ OFF)
+
option(ENABLE_DEBUG "Set to ON to enable curl debug features" OFF)
option(ENABLE_CURLDEBUG "Set to ON to build with TrackMemory feature enabled" OFF)
+if(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_CLANG)
+ if (PICKY_COMPILER)
+ foreach (_CCOPT -pedantic -Wall -W -Wpointer-arith -Wwrite-strings -Wunused -Wshadow -Winline -Wnested-externs -Wmissing-declarations -Wmissing-prototypes -Wno-long-long -Wfloat-equal -Wno-multichar -Wsign-compare -Wundef -Wno-format-nonliteral -Wendif-labels -Wstrict-prototypes -Wdeclaration-after-statement -Wstrict-aliasing=3 -Wcast-align -Wtype-limits -Wold-style-declaration -Wmissing-parameter-type -Wempty-body -Wclobbered -Wignored-qualifiers -Wconversion -Wno-sign-conversion -Wvla -Wdouble-promotion -Wno-system-headers)
+ # surprisingly, CHECK_C_COMPILER_FLAG needs a new variable to store each new
+ # test result in.
+ CHECK_C_COMPILER_FLAG(${_CCOPT} OPT${_CCOPT})
+ if(OPT${_CCOPT})
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${_CCOPT}")
+ endif()
+ endforeach()
+ endif(PICKY_COMPILER)
+endif(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_CLANG)
+
if (ENABLE_DEBUG)
# DEBUGBUILD will be defined only for Debug builds
if(NOT CMAKE_VERSION VERSION_LESS 3.0)
@@ -187,13 +206,14 @@ if (ENABLE_CURLDEBUG)
set_property(DIRECTORY APPEND PROPERTY COMPILE_DEFINITIONS CURLDEBUG)
endif()
+if(0) # This code not needed for building within CMake.
+# For debug libs and exes, add "-d" postfix
+set(CMAKE_DEBUG_POSTFIX "-d" CACHE STRING "Set debug library postfix")
+endif()
+
# initialize CURL_LIBS
set(CURL_LIBS "")
-if(ENABLE_THREADED_RESOLVER AND ENABLE_ARES)
- message(FATAL_ERROR "Options ENABLE_THREADED_RESOLVER and ENABLE_ARES are mutually exclusive")
-endif()
-
if(ENABLE_ARES)
set(USE_ARES 1)
find_package(CARES REQUIRED)
@@ -201,11 +221,6 @@ if(ENABLE_ARES)
set(CURL_LIBS ${CURL_LIBS} ${CARES_LIBRARY})
endif()
-if(MSVC)
- option(BUILD_RELEASE_DEBUG_DIRS "Set OFF to build each configuration to a separate directory" OFF)
- mark_as_advanced(BUILD_RELEASE_DEBUG_DIRS)
-endif()
-
if(0) # This code not needed for building within CMake.
include(CurlSymbolHiding)
endif()
@@ -265,8 +280,6 @@ option(CURL_DISABLE_CRYPTO_AUTH "to disable cryptographic authentication" OFF)
mark_as_advanced(CURL_DISABLE_CRYPTO_AUTH)
option(CURL_DISABLE_VERBOSE_STRINGS "to disable verbose strings" OFF)
mark_as_advanced(CURL_DISABLE_VERBOSE_STRINGS)
-option(DISABLED_THREADSAFE "Set to explicitly specify we don't want to use thread-safe functions" OFF)
-mark_as_advanced(DISABLED_THREADSAFE)
option(ENABLE_IPV6 "Define if you want to enable IPv6 support" ON)
mark_as_advanced(ENABLE_IPV6)
if(ENABLE_IPV6 AND NOT WIN32)
@@ -283,51 +296,48 @@ if(ENABLE_IPV6 AND NOT WIN32)
endif()
endif()
-option(ENABLE_MANUAL "to provide the built-in manual" ON)
-unset(USE_MANUAL CACHE) # TODO: cache NROFF/NROFF_MANOPT/USE_MANUAL vars?
-if(ENABLE_MANUAL)
- find_program(NROFF NAMES gnroff nroff)
- if(NROFF)
- # Need a way to write to stdin, this will do
- file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/nroff-input.txt" "test")
- # Tests for a valid nroff option to generate a manpage
- foreach(_MANOPT "-man" "-mandoc")
- execute_process(COMMAND "${NROFF}" ${_MANOPT}
- OUTPUT_VARIABLE NROFF_MANOPT_OUTPUT
- INPUT_FILE "${CMAKE_CURRENT_BINARY_DIR}/nroff-input.txt"
- ERROR_QUIET)
- # Save the option if it was valid
- if(NROFF_MANOPT_OUTPUT)
- message("Found *nroff option: -- ${_MANOPT}")
- set(NROFF_MANOPT ${_MANOPT})
- set(USE_MANUAL 1)
- break()
- endif()
- endforeach()
- # No need for the temporary file
- file(REMOVE "${CMAKE_CURRENT_BINARY_DIR}/nroff-input.txt")
- if(NOT USE_MANUAL)
- message(WARNING "Found no *nroff option to get plaintext from man pages")
- endif()
- else()
- message(WARNING "Found no *nroff program")
- endif()
-endif()
-
if(0) # This code not needed for building within CMake.
+CURL_NROFF_CHECK()
# Required for building manual, docs, tests
-find_package(Perl REQUIRED)
+find_package(Perl)
+
+CMAKE_DEPENDENT_OPTION(ENABLE_MANUAL "to provide the built-in manual"
+ ON "NROFF_USEFUL;PERL_FOUND"
+ OFF)
+
+if(NOT PERL_FOUND)
+ message(STATUS "Perl not found, testing disabled.")
+ set(BUILD_TESTING OFF)
+endif()
+if(ENABLE_MANUAL)
+ set(USE_MANUAL ON)
+endif()
endif()
# We need ansi c-flags, especially on HP
set(CMAKE_C_FLAGS "${CMAKE_ANSI_CFLAGS} ${CMAKE_C_FLAGS}")
set(CMAKE_REQUIRED_FLAGS ${CMAKE_ANSI_CFLAGS})
+if(CURL_STATIC_CRT)
+ set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /MT")
+ set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /MTd")
+endif()
+
# Disable warnings on Borland to avoid changing 3rd party code.
if(BORLAND)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w-")
endif(BORLAND)
+if(CURL_WERROR)
+ if(MSVC_VERSION)
+ set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /WX")
+ set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /WX")
+ else()
+ # this assumes clang or gcc style options
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror")
+ endif()
+endif(CURL_WERROR)
+
# If we are on AIX, do the _ALL_SOURCE magic
if(${CMAKE_SYSTEM_NAME} MATCHES AIX)
set(_ALL_SOURCE 1)
@@ -349,19 +359,14 @@ if(WIN32)
endif(WIN32)
if(ENABLE_THREADED_RESOLVER)
+ find_package(Threads REQUIRED)
if(WIN32)
set(USE_THREADS_WIN32 ON)
else()
- check_include_file_concat("pthread.h" HAVE_PTHREAD_H)
- if(HAVE_PTHREAD_H)
- set(CMAKE_THREAD_PREFER_PTHREAD 1)
- find_package(Threads)
- if(CMAKE_USE_PTHREADS_INIT)
- set(CURL_LIBS ${CURL_LIBS} ${CMAKE_THREAD_LIBS_INIT})
- set(USE_THREADS_POSIX 1)
- endif()
- endif()
+ set(USE_THREADS_POSIX ${CMAKE_USE_PTHREADS_INIT})
+ set(HAVE_PTHREAD_H ${CMAKE_USE_PTHREADS_INIT})
endif()
+ set(CURL_LIBS ${CURL_LIBS} ${CMAKE_THREAD_LIBS_INIT})
endif()
# Check for all needed libraries
@@ -911,11 +916,6 @@ check_type_size("int" SIZEOF_INT)
check_type_size("__int64" SIZEOF___INT64)
check_type_size("time_t" SIZEOF_TIME_T)
-# Make public versions of some type sizes for curlbuild.h.
-foreach(t INT LONG LONG_LONG SSIZE_T)
- string(REPLACE "SIZEOF_" "CURL_SIZEOF_" CURL_SIZEOF_${t}_CODE "${SIZEOF_${t}_CODE}")
-endforeach()
-
if(HAVE_SIZEOF_LONG_LONG)
set(HAVE_LONGLONG 1)
set(HAVE_LL 1)
@@ -1003,7 +1003,18 @@ check_symbol_exists(ioctl "${CURL_INCLUDES}" HAVE_IOCTL)
check_symbol_exists(setsockopt "${CURL_INCLUDES}" HAVE_SETSOCKOPT)
# symbol exists in win32, but function does not.
-check_function_exists(inet_pton HAVE_INET_PTON)
+if(WIN32)
+ if(ENABLE_INET_PTON)
+ check_function_exists(inet_pton HAVE_INET_PTON)
+ # _WIN32_WINNT_VISTA (0x0600)
+ add_definitions(-D_WIN32_WINNT=0x0600)
+ else()
+ # _WIN32_WINNT_WINXP (0x0501)
+ add_definitions(-D_WIN32_WINNT=0x0501)
+ endif()
+else()
+ check_function_exists(inet_pton HAVE_INET_PTON)
+endif()
check_symbol_exists(fsetxattr "${CURL_INCLUDES}" HAVE_FSETXATTR)
if(HAVE_FSETXATTR)
@@ -1075,6 +1086,13 @@ if(HAVE_FILE_OFFSET_BITS)
set(CMAKE_REQUIRED_FLAGS "-D_FILE_OFFSET_BITS=64")
endif(HAVE_FILE_OFFSET_BITS)
check_type_size("off_t" SIZEOF_OFF_T)
+
+# include this header to get the type
+set(CMAKE_REQUIRED_INCLUDES "${CURL_SOURCE_DIR}/include")
+set(CMAKE_EXTRA_INCLUDE_FILES "curl/system.h")
+check_type_size("curl_off_t" SIZEOF_CURL_OFF_T)
+set(CMAKE_EXTRA_INCLUDE_FILES "")
+
set(CMAKE_REQUIRED_FLAGS)
foreach(CURL_TEST
@@ -1190,7 +1208,7 @@ else()
set(CURL_HAVE_SOCKLEN_T 0)
endif()
-# TODO test which of these headers are required for the typedefs used in curlbuild.h
+# TODO test which of these headers are required
if(WIN32)
set(CURL_PULL_WS2TCPIP_H ${HAVE_WS2TCPIP_H})
else()
@@ -1205,11 +1223,6 @@ include(CMake/OtherTests.cmake)
add_definitions(-DHAVE_CONFIG_H)
-# For windows, do not allow the compiler to use default target (Vista).
-if(WIN32)
- add_definitions(-D_WIN32_WINNT=0x0501)
-endif(WIN32)
-
# For windows, all compilers used by cmake should support large files
if(WIN32)
set(USE_WIN32_LARGE_FILES ON)
@@ -1217,6 +1230,11 @@ endif(WIN32)
if(MSVC)
add_definitions(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE)
+ if(CMAKE_C_FLAGS MATCHES "/W[0-4]")
+ string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}")
+ else(CMAKE_C_FLAGS MATCHES "/W[0-4]")
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W4")
+ endif(CMAKE_C_FLAGS MATCHES "/W[0-4]")
endif(MSVC)
# Ugly (but functional) way to include "Makefile.inc" by transforming it (= regenerate it).
@@ -1235,10 +1253,12 @@ function(TRANSFORM_MAKEFILE_INC INPUT_FILE OUTPUT_FILE)
endfunction()
-if(0) # This code not needed for building within CMake.
-add_subdirectory(docs)
+if(USE_MANUAL)
+ add_subdirectory(docs)
endif()
+
add_subdirectory(lib)
+
if(BUILD_CURL_EXE)
add_subdirectory(src)
endif()
@@ -1355,7 +1375,7 @@ set(LDFLAGS "${CMAKE_SHARED_LINKER_FLAGS}")
set(LIBCURL_LIBS "")
set(libdir "${CMAKE_INSTALL_PREFIX}/lib")
foreach(_lib ${CMAKE_C_IMPLICIT_LINK_LIBRARIES} ${CURL_LIBS})
- if(_lib MATCHES ".*/.*")
+ if(_lib MATCHES ".*/.*" OR _lib MATCHES "^-")
set(LIBCURL_LIBS "${LIBCURL_LIBS} ${_lib}")
else()
set(LIBCURL_LIBS "${LIBCURL_LIBS} -l${_lib}")
@@ -1391,16 +1411,10 @@ if(NOT CURL_CONFIG_HAS_BEEN_RUN_BEFORE)
set(CURL_CONFIG_HAS_BEEN_RUN_BEFORE 1 CACHE INTERNAL "Flag to track whether this is the first time running CMake or if CMake has been configured before")
endif()
-# Installation.
-# First, install generated curlbuild.h
-install(FILES "${CMAKE_CURRENT_BINARY_DIR}/include/curl/curlbuild.h"
- DESTINATION include/curl )
-# Next, install other headers excluding curlbuild.h
+# install headers
install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/curl"
DESTINATION include
- FILES_MATCHING PATTERN "*.h"
- PATTERN "curlbuild.h" EXCLUDE)
-
+ FILES_MATCHING PATTERN "*.h")
# Workaround for MSVS10 to avoid the Dialog Hell
# FIXME: This could be removed with future version of CMake.
@@ -1410,4 +1424,15 @@ if(MSVC_VERSION EQUAL 1600)
file(APPEND "${CURL_SLN_FILENAME}" "\n# This should be regenerated!\n")
endif()
endif()
+
+if(NOT TARGET uninstall)
+ configure_file(
+ ${CMAKE_CURRENT_SOURCE_DIR}/CMake/cmake_uninstall.cmake.in
+ ${CMAKE_CURRENT_BINARY_DIR}/CMake/cmake_uninstall.cmake
+ IMMEDIATE @ONLY)
+
+ add_custom_target(uninstall
+ COMMAND ${CMAKE_COMMAND} -P
+ ${CMAKE_CURRENT_BINARY_DIR}/CMake/cmake_uninstall.cmake)
+endif()
endif()
diff --git a/Utilities/cmcurl/include/curl/curl.h b/Utilities/cmcurl/include/curl/curl.h
index 395521202..5b4fd0f47 100644
--- a/Utilities/cmcurl/include/curl/curl.h
+++ b/Utilities/cmcurl/include/curl/curl.h
@@ -36,8 +36,6 @@
#include "curlver.h" /* libcurl version defines */
#include "system.h" /* determine things run-time */
-#include "cmcurl/include/curl/curlbuild.h" /* libcurl build definitions */
-#include "curlrules.h" /* libcurl rules enforcement */
/*
* Define WIN32 when build target is Win32 API
@@ -76,6 +74,7 @@
#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \
defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \
defined(ANDROID) || defined(__ANDROID__) || defined(__OpenBSD__) || \
+ defined(__CYGWIN__) || \
(defined(__FreeBSD_version) && (__FreeBSD_version < 800000))
#include <sys/select.h>
#endif
@@ -134,6 +133,27 @@ typedef int curl_socket_t;
#define curl_socket_typedef
#endif /* curl_socket_typedef */
+/* enum for the different supported SSL backends */
+typedef enum {
+ CURLSSLBACKEND_NONE = 0,
+ CURLSSLBACKEND_OPENSSL = 1,
+ CURLSSLBACKEND_GNUTLS = 2,
+ CURLSSLBACKEND_NSS = 3,
+ CURLSSLBACKEND_OBSOLETE4 = 4, /* Was QSOSSL. */
+ CURLSSLBACKEND_GSKIT = 5,
+ CURLSSLBACKEND_POLARSSL = 6,
+ CURLSSLBACKEND_WOLFSSL = 7,
+ CURLSSLBACKEND_SCHANNEL = 8,
+ CURLSSLBACKEND_DARWINSSL = 9,
+ CURLSSLBACKEND_AXTLS = 10,
+ CURLSSLBACKEND_MBEDTLS = 11
+} curl_sslbackend;
+
+/* aliases for library clones and renames */
+#define CURLSSLBACKEND_LIBRESSL CURLSSLBACKEND_OPENSSL
+#define CURLSSLBACKEND_BORINGSSL CURLSSLBACKEND_OPENSSL
+#define CURLSSLBACKEND_CYASSL CURLSSLBACKEND_WOLFSSL
+
struct curl_httppost {
struct curl_httppost *next; /* next entry in the list */
char *name; /* pointer to allocated name */
@@ -337,7 +357,7 @@ typedef size_t (*curl_read_callback)(char *buffer,
size_t nitems,
void *instream);
-typedef enum {
+typedef enum {
CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */
CURLSOCKTYPE_ACCEPT, /* socket created by accept() call */
CURLSOCKTYPE_LAST /* never use */
@@ -379,7 +399,7 @@ typedef enum {
CURLIOE_LAST /* never use */
} curlioerr;
-typedef enum {
+typedef enum {
CURLIOCMD_NOP, /* no operation */
CURLIOCMD_RESTARTREAD, /* restart the read stream from start */
CURLIOCMD_LAST /* never use */
@@ -679,6 +699,8 @@ typedef enum {
#define CURLAUTH_NEGOTIATE (((unsigned long)1)<<2)
/* Deprecated since the advent of CURLAUTH_NEGOTIATE */
#define CURLAUTH_GSSNEGOTIATE CURLAUTH_NEGOTIATE
+/* Used for CURLOPT_SOCKS5_AUTH to stay terminologically correct */
+#define CURLAUTH_GSSAPI CURLAUTH_NEGOTIATE
#define CURLAUTH_NTLM (((unsigned long)1)<<3)
#define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4)
#define CURLAUTH_NTLM_WB (((unsigned long)1)<<5)
@@ -1782,6 +1804,18 @@ typedef enum {
/* Suppress proxy CONNECT response headers from user callbacks */
CINIT(SUPPRESS_CONNECT_HEADERS, LONG, 265),
+ /* The request target, instead of extracted from the URL */
+ CINIT(REQUEST_TARGET, STRINGPOINT, 266),
+
+ /* bitmask of allowed auth methods for connections to SOCKS5 proxies */
+ CINIT(SOCKS5_AUTH, LONG, 267),
+
+ /* Enable/disable SSH compression */
+ CINIT(SSH_COMPRESSION, LONG, 268),
+
+ /* Post MIME data. */
+ CINIT(MIMEPOST, OBJECTPOINT, 269),
+
CURLOPT_LASTENTRY /* the last unused */
} CURLoption;
@@ -1928,15 +1962,140 @@ typedef enum {
CURL_TIMECOND_LAST
} curl_TimeCond;
+/* Special size_t value signaling a zero-terminated string. */
+#define CURL_ZERO_TERMINATED ((size_t) -1)
/* curl_strequal() and curl_strnequal() are subject for removal in a future
- libcurl, see lib/README.curlx for details
+ release */
+CURL_EXTERN int curl_strequal(const char *s1, const char *s2);
+CURL_EXTERN int curl_strnequal(const char *s1, const char *s2, size_t n);
+
+/* Mime/form handling support. */
+typedef struct curl_mime_s curl_mime; /* Mime context. */
+typedef struct curl_mimepart_s curl_mimepart; /* Mime part context. */
+
+/*
+ * NAME curl_mime_init()
+ *
+ * DESCRIPTION
+ *
+ * Create a mime context and return its handle. The easy parameter is the
+ * target handle.
+ */
+CURL_EXTERN curl_mime *curl_mime_init(CURL *easy);
+
+/*
+ * NAME curl_mime_free()
+ *
+ * DESCRIPTION
+ *
+ * release a mime handle and its substructures.
+ */
+CURL_EXTERN void curl_mime_free(curl_mime *mime);
+
+/*
+ * NAME curl_mime_addpart()
+ *
+ * DESCRIPTION
+ *
+ * Append a new empty part to the given mime context and return a handle to
+ * the created part.
+ */
+CURL_EXTERN curl_mimepart *curl_mime_addpart(curl_mime *mime);
+
+/*
+ * NAME curl_mime_name()
+ *
+ * DESCRIPTION
+ *
+ * Set mime/form part name.
+ */
+CURL_EXTERN CURLcode curl_mime_name(curl_mimepart *part, const char *name);
+
+/*
+ * NAME curl_mime_filename()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part remote file name.
+ */
+CURL_EXTERN CURLcode curl_mime_filename(curl_mimepart *part,
+ const char *filename);
+
+/*
+ * NAME curl_mime_type()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part type.
+ */
+CURL_EXTERN CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype);
+
+/*
+ * NAME curl_mime_encoder()
+ *
+ * DESCRIPTION
+ *
+ * Set mime data transfer encoder.
+ */
+CURL_EXTERN CURLcode curl_mime_encoder(curl_mimepart *part,
+ const char *encoding);
+
+/*
+ * NAME curl_mime_data()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part data source from memory data,
+ */
+CURL_EXTERN CURLcode curl_mime_data(curl_mimepart *part,
+ const char *data, size_t datasize);
+
+/*
+ * NAME curl_mime_filedata()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part data source from named file.
+ */
+CURL_EXTERN CURLcode curl_mime_filedata(curl_mimepart *part,
+ const char *filename);
+
+/*
+ * NAME curl_mime_data_cb()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part data source from callback function.
+ */
+CURL_EXTERN CURLcode curl_mime_data_cb(curl_mimepart *part,
+ curl_off_t datasize,
+ curl_read_callback readfunc,
+ curl_seek_callback seekfunc,
+ curl_free_callback freefunc,
+ void *arg);
- !checksrc! disable SPACEBEFOREPAREN 2
-*/
-CURL_EXTERN int (curl_strequal)(const char *s1, const char *s2);
-CURL_EXTERN int (curl_strnequal)(const char *s1, const char *s2, size_t n);
+/*
+ * NAME curl_mime_subparts()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part data source from subparts.
+ */
+CURL_EXTERN CURLcode curl_mime_subparts(curl_mimepart *part,
+ curl_mime *subparts);
+/*
+ * NAME curl_mime_headers()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part headers.
+ */
+CURL_EXTERN CURLcode curl_mime_headers(curl_mimepart *part,
+ struct curl_slist *headers,
+ int take_ownership);
+/* Old form API. */
/* name is uppercase CURLFORM_<name> */
#ifdef CFINIT
#undef CFINIT
@@ -2179,6 +2338,47 @@ struct curl_slist {
};
/*
+ * NAME curl_global_sslset()
+ *
+ * DESCRIPTION
+ *
+ * When built with multiple SSL backends, curl_global_sslset() allows to
+ * choose one. This function can only be called once, and it must be called
+ * *before* curl_global_init().
+ *
+ * The backend can be identified by the id (e.g. CURLSSLBACKEND_OPENSSL). The
+ * backend can also be specified via the name parameter (passing -1 as id).
+ * If both id and name are specified, the name will be ignored. If neither id
+ * nor name are specified, the function will fail with
+ * CURLSSLSET_UNKNOWN_BACKEND and set the "avail" pointer to the
+ * NULL-terminated list of available backends.
+ *
+ * Upon success, the function returns CURLSSLSET_OK.
+ *
+ * If the specified SSL backend is not available, the function returns
+ * CURLSSLSET_UNKNOWN_BACKEND and sets the "avail" pointer to a NULL-terminated
+ * list of available SSL backends.
+ *
+ * The SSL backend can be set only once. If it has already been set, a
+ * subsequent attempt to change it will result in a CURLSSLSET_TOO_LATE.
+ */
+
+typedef struct {
+ curl_sslbackend id;
+ const char *name;
+} curl_ssl_backend;
+
+typedef enum {
+ CURLSSLSET_OK = 0,
+ CURLSSLSET_UNKNOWN_BACKEND,
+ CURLSSLSET_TOO_LATE,
+ CURLSSLSET_NO_BACKENDS /* libcurl was built without any SSL support */
+} CURLsslset;
+
+CURL_EXTERN CURLsslset curl_global_sslset(curl_sslbackend id, const char *name,
+ const curl_ssl_backend ***avail);
+
+/*
* NAME curl_slist_append()
*
* DESCRIPTION
@@ -2218,27 +2418,6 @@ struct curl_certinfo {
format "name: value" */
};
-/* enum for the different supported SSL backends */
-typedef enum {
- CURLSSLBACKEND_NONE = 0,
- CURLSSLBACKEND_OPENSSL = 1,
- CURLSSLBACKEND_GNUTLS = 2,
- CURLSSLBACKEND_NSS = 3,
- CURLSSLBACKEND_OBSOLETE4 = 4, /* Was QSOSSL. */
- CURLSSLBACKEND_GSKIT = 5,
- CURLSSLBACKEND_POLARSSL = 6,
- CURLSSLBACKEND_CYASSL = 7,
- CURLSSLBACKEND_SCHANNEL = 8,
- CURLSSLBACKEND_DARWINSSL = 9,
- CURLSSLBACKEND_AXTLS = 10,
- CURLSSLBACKEND_MBEDTLS = 11
-} curl_sslbackend;
-
-/* aliases for library clones and renames */
-#define CURLSSLBACKEND_LIBRESSL 1
-#define CURLSSLBACKEND_BORINGSSL 1
-#define CURLSSLBACKEND_WOLFSSL 6
-
/* Information about the SSL library used and the respective internal SSL
handle, which can be used to obtain further information regarding the
connection. Asked for with CURLINFO_TLS_SSL_PTR or CURLINFO_TLS_SESSION. */
@@ -2253,6 +2432,7 @@ struct curl_tlssessioninfo {
#define CURLINFO_SLIST 0x400000
#define CURLINFO_PTR 0x400000 /* same as SLIST */
#define CURLINFO_SOCKET 0x500000
+#define CURLINFO_OFF_T 0x600000
#define CURLINFO_MASK 0x0fffff
#define CURLINFO_TYPEMASK 0xf00000
@@ -2265,15 +2445,21 @@ typedef enum {
CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5,
CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6,
CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7,
+ CURLINFO_SIZE_UPLOAD_T = CURLINFO_OFF_T + 7,
CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8,
+ CURLINFO_SIZE_DOWNLOAD_T = CURLINFO_OFF_T + 8,
CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9,
+ CURLINFO_SPEED_DOWNLOAD_T = CURLINFO_OFF_T + 9,
CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10,
+ CURLINFO_SPEED_UPLOAD_T = CURLINFO_OFF_T + 10,
CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11,
CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12,
CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13,
CURLINFO_FILETIME = CURLINFO_LONG + 14,
CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15,
+ CURLINFO_CONTENT_LENGTH_DOWNLOAD_T = CURLINFO_OFF_T + 15,
CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16,
+ CURLINFO_CONTENT_LENGTH_UPLOAD_T = CURLINFO_OFF_T + 16,
CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17,
CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18,
CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19,
@@ -2471,6 +2657,7 @@ typedef struct {
#define CURL_VERSION_PSL (1<<20) /* Mozilla's Public Suffix List, used
for cookie domain verification */
#define CURL_VERSION_HTTPS_PROXY (1<<21) /* HTTPS-proxy support built-in */
+#define CURL_VERSION_MULTI_SSL (1<<22) /* Multiple SSL backends available */
/*
* NAME curl_version_info()
diff --git a/Utilities/cmcurl/include/curl/curlbuild.h.cmake b/Utilities/cmcurl/include/curl/curlbuild.h.cmake
deleted file mode 100644
index c8b4f5270..000000000
--- a/Utilities/cmcurl/include/curl/curlbuild.h.cmake
+++ /dev/null
@@ -1,218 +0,0 @@
-#ifndef __CURL_CURLBUILD_H
-#define __CURL_CURLBUILD_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
- * Copyright (C) 1998 - 2008, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
- * are also available at https://curl.haxx.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* ================================================================ */
-/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */
-/* ================================================================ */
-
-/*
- * NOTE 1:
- * -------
- *
- * Nothing in this file is intended to be modified or adjusted by the
- * curl library user nor by the curl library builder.
- *
- * If you think that something actually needs to be changed, adjusted
- * or fixed in this file, then, report it on the libcurl development
- * mailing list: https://cool.haxx.se/mailman/listinfo/curl-library/
- *
- * This header file shall only export symbols which are 'curl' or 'CURL'
- * prefixed, otherwise public name space would be polluted.
- *
- * NOTE 2:
- * -------
- *
- * Right now you might be staring at file include/curl/curlbuild.h.in or
- * at file include/curl/curlbuild.h, this is due to the following reason:
- *
- * On systems capable of running the configure script, the configure process
- * will overwrite the distributed include/curl/curlbuild.h file with one that
- * is suitable and specific to the library being configured and built, which
- * is generated from the include/curl/curlbuild.h.in template file.
- *
- */
-
-/* ================================================================ */
-/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */
-/* ================================================================ */
-
-#ifdef CURL_SIZEOF_LONG
-#error "CURL_SIZEOF_LONG shall not be defined except in curlbuild.h"
- Error Compilation_aborted_CURL_SIZEOF_LONG_already_defined
-#endif
-
-#ifdef CURL_TYPEOF_CURL_SOCKLEN_T
-#error "CURL_TYPEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h"
- Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_already_defined
-#endif
-
-#ifdef CURL_SIZEOF_CURL_SOCKLEN_T
-#error "CURL_SIZEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h"
- Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_already_defined
-#endif
-
-#ifdef CURL_TYPEOF_CURL_OFF_T
-#error "CURL_TYPEOF_CURL_OFF_T shall not be defined except in curlbuild.h"
- Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_already_defined
-#endif
-
-#ifdef CURL_FORMAT_CURL_OFF_T
-#error "CURL_FORMAT_CURL_OFF_T shall not be defined except in curlbuild.h"
- Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_already_defined
-#endif
-
-#ifdef CURL_FORMAT_CURL_OFF_TU
-#error "CURL_FORMAT_CURL_OFF_TU shall not be defined except in curlbuild.h"
- Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_already_defined
-#endif
-
-#ifdef CURL_FORMAT_OFF_T
-#error "CURL_FORMAT_OFF_T shall not be defined except in curlbuild.h"
- Error Compilation_aborted_CURL_FORMAT_OFF_T_already_defined
-#endif
-
-#ifdef CURL_SIZEOF_CURL_OFF_T
-#error "CURL_SIZEOF_CURL_OFF_T shall not be defined except in curlbuild.h"
- Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_already_defined
-#endif
-
-#ifdef CURL_SUFFIX_CURL_OFF_T
-#error "CURL_SUFFIX_CURL_OFF_T shall not be defined except in curlbuild.h"
- Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_already_defined
-#endif
-
-#ifdef CURL_SUFFIX_CURL_OFF_TU
-#error "CURL_SUFFIX_CURL_OFF_TU shall not be defined except in curlbuild.h"
- Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_already_defined
-#endif
-
-/* ================================================================ */
-/* EXTERNAL INTERFACE SETTINGS FOR CONFIGURE CAPABLE SYSTEMS ONLY */
-/* ================================================================ */
-
-/* Configure process defines this to 1 when it finds out that system */
-/* header file ws2tcpip.h must be included by the external interface. */
-#cmakedefine CURL_PULL_WS2TCPIP_H
-#ifdef CURL_PULL_WS2TCPIP_H
-# ifndef WIN32_LEAN_AND_MEAN
-# define WIN32_LEAN_AND_MEAN
-# endif
-# include <windows.h>
-# include <winsock2.h>
-# include <ws2tcpip.h>
-#endif
-
-/* Configure process defines this to 1 when it finds out that system */
-/* header file sys/types.h must be included by the external interface. */
-#cmakedefine CURL_PULL_SYS_TYPES_H
-#ifdef CURL_PULL_SYS_TYPES_H
-# include <sys/types.h>
-#endif
-
-/* Configure process defines this to 1 when it finds out that system */
-/* header file stdint.h must be included by the external interface. */
-#cmakedefine CURL_PULL_STDINT_H
-#ifdef CURL_PULL_STDINT_H
-# include <stdint.h>
-#endif
-
-/* Configure process defines this to 1 when it finds out that system */
-/* header file inttypes.h must be included by the external interface. */
-#cmakedefine CURL_PULL_INTTYPES_H
-#ifdef CURL_PULL_INTTYPES_H
-# include <inttypes.h>
-#endif
-
-/* Configure process defines this to 1 when it finds out that system */
-/* header file sys/socket.h must be included by the external interface. */
-#cmakedefine CURL_PULL_SYS_SOCKET_H
-#ifdef CURL_PULL_SYS_SOCKET_H
-# include <sys/socket.h>
-#endif
-
-/* Configure process defines this to 1 when it finds out that system */
-/* header file sys/poll.h must be included by the external interface. */
-#cmakedefine CURL_PULL_SYS_POLL_H
-#ifdef CURL_PULL_SYS_POLL_H
-# include <sys/poll.h>
-#endif
-
-/* The size of `int', as computed by sizeof. */
-@CURL_SIZEOF_INT_CODE@
-
-/* The size of `long', as computed by sizeof. */
-@CURL_SIZEOF_LONG_CODE@
-
-/* The size of `long long', as computed by sizeof. */
-@CURL_SIZEOF_LONG_LONG_CODE@
-
-/* The size of `ssize_t', as computed by sizeof. */
-@CURL_SIZEOF_SSIZE_T_CODE@
-
-#define CURL_HAVE_SOCKLEN_T @CURL_HAVE_SOCKLEN_T@
-#if CURL_HAVE_SOCKLEN_T
-/* Integral data type used for curl_socklen_t. */
-#define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
-
-/* The size of `curl_socklen_t', as computed by sizeof. */
-@CURL_SIZEOF_CURL_SOCKLEN_T_CODE@
-#else
-# define CURL_TYPEOF_CURL_SOCKLEN_T int
-# define CURL_SIZEOF_CURL_SOCKLEN_T CURL_SIZEOF_INT
-#endif
-
-/* Data type definition of curl_socklen_t. */
-typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t;
-
-#if CURL_SIZEOF_LONG == 8
-# define CURL_TYPEOF_CURL_OFF_T long
-# define CURL_SIZEOF_CURL_OFF_T 8
-# define CURL_FORMAT_CURL_OFF_T "ld"
-# define CURL_FORMAT_CURL_OFF_TU "lu"
-# define CURL_FORMAT_OFF_T "%ld"
-# define CURL_SUFFIX_CURL_OFF_T L
-# define CURL_SUFFIX_CURL_OFF_TU UL
-#elif CURL_SIZEOF_LONG_LONG == 8
-# define CURL_TYPEOF_CURL_OFF_T long long
-# define CURL_SIZEOF_CURL_OFF_T 8
-# define CURL_FORMAT_CURL_OFF_T "lld"
-# define CURL_FORMAT_CURL_OFF_TU "llu"
-# define CURL_FORMAT_OFF_T "%lld"
-# define CURL_SUFFIX_CURL_OFF_T LL
-# define CURL_SUFFIX_CURL_OFF_TU ULL
-#else
-# define CURL_TYPEOF_CURL_OFF_T ssize_t
-# define CURL_SIZEOF_CURL_OFF_T CURL_SIZEOF_SSIZE_T
-/* TODO: need adjustment here. */
-# define CURL_FORMAT_CURL_OFF_T "ld"
-# define CURL_FORMAT_CURL_OFF_TU "lu"
-# define CURL_FORMAT_OFF_T "%ld"
-# define CURL_SUFFIX_CURL_OFF_T L
-# define CURL_SUFFIX_CURL_OFF_TU UL
-#endif
-
-/* Data type definition of curl_off_t. */
-typedef CURL_TYPEOF_CURL_OFF_T curl_off_t;
-
-#endif /* __CURL_CURLBUILD_H */
diff --git a/Utilities/cmcurl/include/curl/curlrules.h b/Utilities/cmcurl/include/curl/curlrules.h
deleted file mode 100644
index 0abd9f71d..000000000
--- a/Utilities/cmcurl/include/curl/curlrules.h
+++ /dev/null
@@ -1,239 +0,0 @@
-#ifndef __CURL_CURLRULES_H
-#define __CURL_CURLRULES_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
- * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
- * are also available at https://curl.haxx.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- ***************************************************************************/
-
-/* ================================================================ */
-/* COMPILE TIME SANITY CHECKS */
-/* ================================================================ */
-
-/*
- * NOTE 1:
- * -------
- *
- * All checks done in this file are intentionally placed in a public
- * header file which is pulled by curl/curl.h when an application is
- * being built using an already built libcurl library. Additionally
- * this file is also included and used when building the library.
- *
- * If compilation fails on this file it is certainly sure that the
- * problem is elsewhere. It could be a problem in the curlbuild.h
- * header file, or simply that you are using different compilation
- * settings than those used to build the library.
- *
- * Nothing in this file is intended to be modified or adjusted by the
- * curl library user nor by the curl library builder.
- *
- * Do not deactivate any check, these are done to make sure that the
- * library is properly built and used.
- *
- * You can find further help on the libcurl development mailing list:
- * https://cool.haxx.se/mailman/listinfo/curl-library/
- *
- * NOTE 2
- * ------
- *
- * Some of the following compile time checks are based on the fact
- * that the dimension of a constant array can not be a negative one.
- * In this way if the compile time verification fails, the compilation
- * will fail issuing an error. The error description wording is compiler
- * dependent but it will be quite similar to one of the following:
- *
- * "negative subscript or subscript is too large"
- * "array must have at least one element"
- * "-1 is an illegal array size"
- * "size of array is negative"
- *
- * If you are building an application which tries to use an already
- * built libcurl library and you are getting this kind of errors on
- * this file, it is a clear indication that there is a mismatch between
- * how the library was built and how you are trying to use it for your
- * application. Your already compiled or binary library provider is the
- * only one who can give you the details you need to properly use it.
- */
-
-/*
- * Verify that some macros are actually defined.
- */
-
-#ifndef CURL_SIZEOF_LONG
-# error "CURL_SIZEOF_LONG definition is missing!"
- Error Compilation_aborted_CURL_SIZEOF_LONG_is_missing
-#endif
-
-#ifndef CURL_TYPEOF_CURL_SOCKLEN_T
-# error "CURL_TYPEOF_CURL_SOCKLEN_T definition is missing!"
- Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_is_missing
-#endif
-
-#ifndef CURL_SIZEOF_CURL_SOCKLEN_T
-# error "CURL_SIZEOF_CURL_SOCKLEN_T definition is missing!"
- Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_is_missing
-#endif
-
-#ifndef CURL_TYPEOF_CURL_OFF_T
-# error "CURL_TYPEOF_CURL_OFF_T definition is missing!"
- Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_is_missing
-#endif
-
-#ifndef CURL_FORMAT_CURL_OFF_T
-# error "CURL_FORMAT_CURL_OFF_T definition is missing!"
- Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_is_missing
-#endif
-
-#ifndef CURL_FORMAT_CURL_OFF_TU
-# error "CURL_FORMAT_CURL_OFF_TU definition is missing!"
- Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_is_missing
-#endif
-
-#ifndef CURL_SIZEOF_CURL_OFF_T
-# error "CURL_SIZEOF_CURL_OFF_T definition is missing!"
- Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_is_missing
-#endif
-
-#ifndef CURL_SUFFIX_CURL_OFF_T
-# error "CURL_SUFFIX_CURL_OFF_T definition is missing!"
- Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_is_missing
-#endif
-
-#ifndef CURL_SUFFIX_CURL_OFF_TU
-# error "CURL_SUFFIX_CURL_OFF_TU definition is missing!"
- Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_is_missing
-#endif
-
-/*
- * Macros private to this header file.
- */
-
-#define CurlchkszEQ(t, s) sizeof(t) == s ? 1 : -1
-
-#define CurlchkszGE(t1, t2) sizeof(t1) >= sizeof(t2) ? 1 : -1
-
-/*
- * Verify that the size previously defined and expected for long
- * is the same as the one reported by sizeof() at compile time.
- */
-
-typedef char
- __curl_rule_01__
- [CurlchkszEQ(long, CURL_SIZEOF_LONG)];
-
-/*
- * Verify that the size previously defined and expected for
- * curl_off_t is actually the the same as the one reported
- * by sizeof() at compile time.
- */
-
-typedef char
- __curl_rule_02__
- [CurlchkszEQ(curl_off_t, CURL_SIZEOF_CURL_OFF_T)];
-
-/*
- * Verify at compile time that the size of curl_off_t as reported
- * by sizeof() is greater or equal than the one reported for long
- * for the current compilation.
- */
-
-typedef char
- __curl_rule_03__
- [CurlchkszGE(curl_off_t, long)];
-
-/*
- * Verify that the size previously defined and expected for
- * curl_socklen_t is actually the the same as the one reported
- * by sizeof() at compile time.
- */
-
-typedef char
- __curl_rule_04__
- [CurlchkszEQ(curl_socklen_t, CURL_SIZEOF_CURL_SOCKLEN_T)];
-
-/*
- * Verify at compile time that the size of curl_socklen_t as reported
- * by sizeof() is greater or equal than the one reported for int for
- * the current compilation.
- */
-
-typedef char
- __curl_rule_05__
- [CurlchkszGE(curl_socklen_t, int)];
-
-/* ================================================================ */
-/* EXTERNALLY AND INTERNALLY VISIBLE DEFINITIONS */
-/* ================================================================ */
-
-/*
- * CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow
- * these to be visible and exported by the external libcurl interface API,
- * while also making them visible to the library internals, simply including
- * curl_setup.h, without actually needing to include curl.h internally.
- * If some day this section would grow big enough, all this should be moved
- * to its own header file.
- */
-
-/*
- * Figure out if we can use the ## preprocessor operator, which is supported
- * by ISO/ANSI C and C++. Some compilers support it without setting __STDC__
- * or __cplusplus so we need to carefully check for them too.
- */
-
-#if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \
- defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \
- defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \
- defined(__ILEC400__)
- /* This compiler is believed to have an ISO compatible preprocessor */
-#define CURL_ISOCPP
-#else
- /* This compiler is believed NOT to have an ISO compatible preprocessor */
-#undef CURL_ISOCPP
-#endif
-
-/*
- * Macros for minimum-width signed and unsigned curl_off_t integer constants.
- */
-
-#if defined(__BORLANDC__) && (__BORLANDC__ == 0x0551)
-# define __CURL_OFF_T_C_HLPR2(x) x
-# define __CURL_OFF_T_C_HLPR1(x) __CURL_OFF_T_C_HLPR2(x)
-# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \
- __CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_T)
-# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \
- __CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_TU)
-#else
-# ifdef CURL_ISOCPP
-# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val ## Suffix
-# else
-# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val/**/Suffix
-# endif
-# define __CURL_OFF_T_C_HLPR1(Val,Suffix) __CURL_OFF_T_C_HLPR2(Val,Suffix)
-# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_T)
-# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_TU)
-#endif
-
-/*
- * Get rid of macros private to this header file.
- */
-
-#undef CurlchkszEQ
-#undef CurlchkszGE
-
-#endif /* __CURL_CURLRULES_H */
diff --git a/Utilities/cmcurl/include/curl/curlver.h b/Utilities/cmcurl/include/curl/curlver.h
index 667b7eb13..18dc356d1 100644
--- a/Utilities/cmcurl/include/curl/curlver.h
+++ b/Utilities/cmcurl/include/curl/curlver.h
@@ -30,13 +30,13 @@
/* This is the version number of the libcurl package from which this header
file origins: */
-#define LIBCURL_VERSION "7.54.1"
+#define LIBCURL_VERSION "7.56.0"
/* The numeric version number is also available "in parts" by using these
defines: */
#define LIBCURL_VERSION_MAJOR 7
-#define LIBCURL_VERSION_MINOR 54
-#define LIBCURL_VERSION_PATCH 1
+#define LIBCURL_VERSION_MINOR 56
+#define LIBCURL_VERSION_PATCH 0
/* This is the numeric version of the libcurl version number, meant for easier
parsing and comparions by programs. The LIBCURL_VERSION_NUM define will
@@ -57,7 +57,7 @@
CURL_VERSION_BITS() macro since curl's own configure script greps for it
and needs it to contain the full number.
*/
-#define LIBCURL_VERSION_NUM 0x073601
+#define LIBCURL_VERSION_NUM 0x073800
/*
* This is the date and time when the full source package was created. The
diff --git a/Utilities/cmcurl/include/curl/multi.h b/Utilities/cmcurl/include/curl/multi.h
index f93e511be..911c91dd1 100644
--- a/Utilities/cmcurl/include/curl/multi.h
+++ b/Utilities/cmcurl/include/curl/multi.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
diff --git a/Utilities/cmcurl/include/curl/system.h b/Utilities/cmcurl/include/curl/system.h
index ed3a55c95..39dae754c 100644
--- a/Utilities/cmcurl/include/curl/system.h
+++ b/Utilities/cmcurl/include/curl/system.h
@@ -23,14 +23,6 @@
***************************************************************************/
/*
- * This header is supposed to eventually replace curlbuild.h. This little one
- * is still learning. During the experimental phase, this header files
- * defines symbols using the prefixes CURLSYS_ or curlsys_. When we feel
- * confident enough, we replace curlbuild.h with this file and rename all
- * prefixes to CURL_ and curl_.
- */
-
-/*
* Try to keep one section per platform, compiler and architecture, otherwise,
* if an existing section is reused for a different one and later on the
* original is adjusted, probably the piggybacking one can be adversely
@@ -60,323 +52,271 @@
#if defined(__DJGPP__) || defined(__GO32__)
# if defined(__DJGPP__) && (__DJGPP__ > 1)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long long
-# define CURLSYS_FORMAT_CURL_OFF_T "lld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "llu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
# else
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 4
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__SALFORDC__)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 4
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__BORLANDC__)
# if (__BORLANDC__ < 0x520)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 4
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
# else
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T __int64
-# define CURLSYS_FORMAT_CURL_OFF_T "I64d"
-# define CURLSYS_FORMAT_CURL_OFF_TU "I64u"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T i64
-# define CURLSYS_SUFFIX_CURL_OFF_TU ui64
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
# endif
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__TURBOC__)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 4
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__WATCOMC__)
# if defined(__386__)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T __int64
-# define CURLSYS_FORMAT_CURL_OFF_T "I64d"
-# define CURLSYS_FORMAT_CURL_OFF_TU "I64u"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T i64
-# define CURLSYS_SUFFIX_CURL_OFF_TU ui64
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
# else
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 4
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__POCC__)
# if (__POCC__ < 280)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 4
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
# elif defined(_MSC_VER)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T __int64
-# define CURLSYS_FORMAT_CURL_OFF_T "I64d"
-# define CURLSYS_FORMAT_CURL_OFF_TU "I64u"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T i64
-# define CURLSYS_SUFFIX_CURL_OFF_TU ui64
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
# else
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long long
-# define CURLSYS_FORMAT_CURL_OFF_T "lld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "llu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
# endif
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__LCC__)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 4
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__SYMBIAN32__)
# if defined(__EABI__) /* Treat all ARM compilers equally */
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long long
-# define CURLSYS_FORMAT_CURL_OFF_T "lld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "llu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(__CW32__)
# pragma longlong on
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long long
-# define CURLSYS_FORMAT_CURL_OFF_T "lld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "llu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(__VC32__)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T __int64
-# define CURLSYS_FORMAT_CURL_OFF_T "lld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "llu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
# endif
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T unsigned int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
#elif defined(__MWERKS__)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long long
-# define CURLSYS_FORMAT_CURL_OFF_T "lld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "llu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(_WIN32_WCE)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T __int64
-# define CURLSYS_FORMAT_CURL_OFF_T "I64d"
-# define CURLSYS_FORMAT_CURL_OFF_TU "I64u"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T i64
-# define CURLSYS_SUFFIX_CURL_OFF_TU ui64
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__MINGW32__)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long long
-# define CURLSYS_FORMAT_CURL_OFF_T "I64d"
-# define CURLSYS_FORMAT_CURL_OFF_TU "I64u"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T socklen_t
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
-# define CURLSYS_PULL_SYS_TYPES_H 1
-# define CURLSYS_PULL_WS2TCPIP_H 1
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_WS2TCPIP_H 1
#elif defined(__VMS)
# if defined(__VAX)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 4
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
# else
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long long
-# define CURLSYS_FORMAT_CURL_OFF_T "lld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "llu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
# endif
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T unsigned int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
#elif defined(__OS400__)
# if defined(__ILEC400__)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long long
-# define CURLSYS_FORMAT_CURL_OFF_T "lld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "llu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T socklen_t
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
-# define CURLSYS_PULL_SYS_TYPES_H 1
-# define CURLSYS_PULL_SYS_SOCKET_H 1
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
# endif
#elif defined(__MVS__)
# if defined(__IBMC__) || defined(__IBMCPP__)
# if defined(_ILP32)
-# define CURLSYS_SIZEOF_LONG 4
# elif defined(_LP64)
-# define CURLSYS_SIZEOF_LONG 8
# endif
# if defined(_LONG_LONG)
-# define CURLSYS_TYPEOF_CURL_OFF_T long long
-# define CURLSYS_FORMAT_CURL_OFF_T "lld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "llu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(_LP64)
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
# else
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 4
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T socklen_t
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
-# define CURLSYS_PULL_SYS_TYPES_H 1
-# define CURLSYS_PULL_SYS_SOCKET_H 1
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
# endif
#elif defined(__370__)
# if defined(__IBMC__) || defined(__IBMCPP__)
# if defined(_ILP32)
-# define CURLSYS_SIZEOF_LONG 4
# elif defined(_LP64)
-# define CURLSYS_SIZEOF_LONG 8
# endif
# if defined(_LONG_LONG)
-# define CURLSYS_TYPEOF_CURL_OFF_T long long
-# define CURLSYS_FORMAT_CURL_OFF_T "lld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "llu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(_LP64)
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
# else
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 4
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T socklen_t
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
-# define CURLSYS_PULL_SYS_TYPES_H 1
-# define CURLSYS_PULL_SYS_SOCKET_H 1
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
# endif
#elif defined(TPF)
-# define CURLSYS_SIZEOF_LONG 8
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
#elif defined(__TINYC__) /* also known as tcc */
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long long
-# define CURLSYS_FORMAT_CURL_OFF_T "lld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "llu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T socklen_t
-# define CURLSYS_PULL_SYS_TYPES_H 1
-# define CURLSYS_PULL_SYS_SOCKET_H 1
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+
+#elif defined(__SUNPRO_C) /* Oracle Solaris Studio */
+# if !defined(__LP64) && (defined(__ILP32) || \
+ defined(__i386) || defined(__sparcv8))
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# elif defined(__LP64) || \
+ defined(__amd64) || defined(__sparcv9)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
/* ===================================== */
/* KEEP MSVC THE PENULTIMATE ENTRY */
@@ -384,101 +324,148 @@
#elif defined(_MSC_VER)
# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T __int64
-# define CURLSYS_FORMAT_CURL_OFF_T "I64d"
-# define CURLSYS_FORMAT_CURL_OFF_TU "I64u"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T i64
-# define CURLSYS_SUFFIX_CURL_OFF_TU ui64
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
# else
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 4
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T int
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
/* ===================================== */
/* KEEP GENERIC GCC THE LAST ENTRY */
/* ===================================== */
#elif defined(__GNUC__)
-# if !defined(__LP64__) && (defined(__ILP32__) || \
- defined(__i386__) || defined(__ppc__) || defined(__arm__) || \
- defined(__sparc__) || defined(__mips__) || defined(__sh__))
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long long
-# define CURLSYS_FORMAT_CURL_OFF_T "lld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "llu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T LL
-# define CURLSYS_SUFFIX_CURL_OFF_TU ULL
+# if !defined(__LP64__) && \
+ (defined(__ILP32__) || defined(__i386__) || defined(__hppa__) || \
+ defined(__ppc__) || defined(__powerpc__) || defined(__arm__) || \
+ defined(__sparc__) || defined(__mips__) || defined(__sh__) || \
+ defined(__XTENSA__) || \
+ (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 4))
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
# elif defined(__LP64__) || \
- defined(__x86_64__) || defined(__ppc64__) || defined(__sparc64__)
-# define CURLSYS_SIZEOF_LONG 8
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SIZEOF_CURL_OFF_T 8
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
+ defined(__x86_64__) || defined(__ppc64__) || defined(__sparc64__) || \
+ (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 8)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
# endif
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T socklen_t
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
-# define CURLSYS_PULL_SYS_TYPES_H 1
-# define CURLSYS_PULL_SYS_SOCKET_H 1
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
#else
/* generic "safe guess" on old 32 bit style */
-# define CURLSYS_SIZEOF_LONG 4
-# define CURLSYS_SIZEOF_CURL_SOCKLEN_T 4
-# define CURLSYS_SIZEOF_CURL_OFF_T 4
-# define CURLSYS_TYPEOF_CURL_OFF_T long
-# define CURLSYS_FORMAT_CURL_OFF_T "ld"
-# define CURLSYS_FORMAT_CURL_OFF_TU "lu"
-# define CURLSYS_SUFFIX_CURL_OFF_T L
-# define CURLSYS_SUFFIX_CURL_OFF_TU UL
-# define CURLSYS_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
#endif
-/* CURLSYS_PULL_WS2TCPIP_H is defined above when inclusion of header file */
+#ifdef _AIX
+/* AIX needs <sys/poll.h> */
+#define CURL_PULL_SYS_POLL_H
+#endif
+
+
+/* CURL_PULL_WS2TCPIP_H is defined above when inclusion of header file */
/* ws2tcpip.h is required here to properly make type definitions below. */
-#ifdef CURLSYS_PULL_WS2TCPIP_H
-# ifndef WIN32_LEAN_AND_MEAN
-# define WIN32_LEAN_AND_MEAN
-# endif
-# include <windows.h>
+#ifdef CURL_PULL_WS2TCPIP_H
# include <winsock2.h>
+# include <windows.h>
# include <ws2tcpip.h>
#endif
-/* CURLSYS_PULL_SYS_TYPES_H is defined above when inclusion of header file */
+/* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file */
/* sys/types.h is required here to properly make type definitions below. */
-#ifdef CURLSYS_PULL_SYS_TYPES_H
+#ifdef CURL_PULL_SYS_TYPES_H
# include <sys/types.h>
#endif
-/* CURLSYS_PULL_SYS_SOCKET_H is defined above when inclusion of header file */
+/* CURL_PULL_SYS_SOCKET_H is defined above when inclusion of header file */
/* sys/socket.h is required here to properly make type definitions below. */
-#ifdef CURLSYS_PULL_SYS_SOCKET_H
+#ifdef CURL_PULL_SYS_SOCKET_H
# include <sys/socket.h>
#endif
+/* CURL_PULL_SYS_POLL_H is defined above when inclusion of header file */
+/* sys/poll.h is required here to properly make type definitions below. */
+#ifdef CURL_PULL_SYS_POLL_H
+# include <sys/poll.h>
+#endif
+
/* Data type definition of curl_socklen_t. */
-#ifdef CURLSYS_TYPEOF_CURL_SOCKLEN_T
- typedef CURLSYS_TYPEOF_CURL_SOCKLEN_T curlsys_socklen_t;
+#ifdef CURL_TYPEOF_CURL_SOCKLEN_T
+ typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t;
#endif
/* Data type definition of curl_off_t. */
-#ifdef CURLSYS_TYPEOF_CURL_OFF_T
- typedef CURLSYS_TYPEOF_CURL_OFF_T curlsys_off_t;
+#ifdef CURL_TYPEOF_CURL_OFF_T
+ typedef CURL_TYPEOF_CURL_OFF_T curl_off_t;
#endif
-#endif /* __CURL_SYSTEM_H */
+/*
+ * CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow
+ * these to be visible and exported by the external libcurl interface API,
+ * while also making them visible to the library internals, simply including
+ * curl_setup.h, without actually needing to include curl.h internally.
+ * If some day this section would grow big enough, all this should be moved
+ * to its own header file.
+ */
+/*
+ * Figure out if we can use the ## preprocessor operator, which is supported
+ * by ISO/ANSI C and C++. Some compilers support it without setting __STDC__
+ * or __cplusplus so we need to carefully check for them too.
+ */
+
+#if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \
+ defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \
+ defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \
+ defined(__ILEC400__)
+ /* This compiler is believed to have an ISO compatible preprocessor */
+#define CURL_ISOCPP
+#else
+ /* This compiler is believed NOT to have an ISO compatible preprocessor */
+#undef CURL_ISOCPP
+#endif
+
+/*
+ * Macros for minimum-width signed and unsigned curl_off_t integer constants.
+ */
+
+#if defined(__BORLANDC__) && (__BORLANDC__ == 0x0551)
+# define __CURL_OFF_T_C_HLPR2(x) x
+# define __CURL_OFF_T_C_HLPR1(x) __CURL_OFF_T_C_HLPR2(x)
+# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \
+ __CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_T)
+# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val) ## \
+ __CURL_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_TU)
+#else
+# ifdef CURL_ISOCPP
+# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val ## Suffix
+# else
+# define __CURL_OFF_T_C_HLPR2(Val,Suffix) Val/**/Suffix
+# endif
+# define __CURL_OFF_T_C_HLPR1(Val,Suffix) __CURL_OFF_T_C_HLPR2(Val,Suffix)
+# define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_T)
+# define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_TU)
+#endif
+
+#endif /* __CURL_SYSTEM_H */
diff --git a/Utilities/cmcurl/include/curl/typecheck-gcc.h b/Utilities/cmcurl/include/curl/typecheck-gcc.h
index 10b5de2ab..10c74c764 100644
--- a/Utilities/cmcurl/include/curl/typecheck-gcc.h
+++ b/Utilities/cmcurl/include/curl/typecheck-gcc.h
@@ -96,6 +96,9 @@ __extension__ ({ \
if((_curl_opt) == CURLOPT_HTTPPOST) \
if(!_curl_is_arr((value), struct curl_httppost)) \
_curl_easy_setopt_err_curl_httpost(); \
+ if((_curl_opt) == CURLOPT_MIMEPOST) \
+ if(!_curl_is_ptr((value), curl_mime)) \
+ _curl_easy_setopt_err_curl_mimepost(); \
if(_curl_is_slist_option(_curl_opt)) \
if(!_curl_is_arr((value), struct curl_slist)) \
_curl_easy_setopt_err_curl_slist(); \
@@ -110,7 +113,7 @@ __extension__ ({ \
/* FIXME: don't allow const pointers */
#define curl_easy_getinfo(handle, info, arg) \
__extension__ ({ \
- __typeof__(info) _curl_info = info; \
+ __typeof__(info) _curl_info = info; \
if(__builtin_constant_p(_curl_info)) { \
if(_curl_is_string_info(_curl_info)) \
if(!_curl_is_arr((arg), char *)) \
@@ -130,9 +133,12 @@ __extension__ ({ \
if(_curl_is_certinfo_info(_curl_info)) \
if(!_curl_is_arr((arg), struct curl_certinfo *)) \
_curl_easy_getinfo_err_curl_certinfo(); \
- if(_curl_is_socket_info(_curl_info)) \
+ if(_curl_is_socket_info(_curl_info)) \
if(!_curl_is_arr((arg), curl_socket_t)) \
_curl_easy_getinfo_err_curl_socket(); \
+ if(_curl_is_off_t_info(_curl_info)) \
+ if(!_curl_is_arr((arg), curl_off_t)) \
+ _curl_easy_getinfo_err_curl_off_t(); \
} \
curl_easy_getinfo(handle, _curl_info, arg); \
})
@@ -197,6 +203,9 @@ _CURL_WARNING(_curl_easy_setopt_err_postfields,
_CURL_WARNING(_curl_easy_setopt_err_curl_httpost,
"curl_easy_setopt expects a 'struct curl_httppost *' "
"argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_curl_mimepost,
+ "curl_easy_setopt expects a 'curl_mime *' "
+ "argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_curl_slist,
"curl_easy_setopt expects a 'struct curl_slist *' argument for this option")
_CURL_WARNING(_curl_easy_setopt_err_CURLSH,
@@ -218,6 +227,8 @@ _CURL_WARNING(_curl_easy_getinfo_err_curl_certinfo,
"'struct curl_certinfo *' for this info")
_CURL_WARNING(_curl_easy_getinfo_err_curl_socket,
"curl_easy_getinfo expects a pointer to curl_socket_t for this info")
+_CURL_WARNING(_curl_easy_getinfo_err_curl_off_t,
+ "curl_easy_getinfo expects a pointer to curl_off_t for this info")
/* groups of curl_easy_setops options that take the same type of argument */
@@ -391,7 +402,11 @@ _CURL_WARNING(_curl_easy_getinfo_err_curl_socket,
/* true if info expects a pointer to struct curl_socket_t argument */
#define _curl_is_socket_info(info) \
- (CURLINFO_SOCKET < (info))
+ (CURLINFO_SOCKET < (info) && (info) < CURLINFO_OFF_T)
+
+/* true if info expects a pointer to curl_off_t argument */
+#define _curl_is_off_t_info(info) \
+ (CURLINFO_OFF_T < (info))
/* typecheck helpers -- check whether given expression has requested type*/
diff --git a/Utilities/cmcurl/lib/CMakeLists.txt b/Utilities/cmcurl/lib/CMakeLists.txt
index 76dd6c63c..f3d9084d8 100644
--- a/Utilities/cmcurl/lib/CMakeLists.txt
+++ b/Utilities/cmcurl/lib/CMakeLists.txt
@@ -1,7 +1,5 @@
set(LIB_NAME cmcurl)
-configure_file(${CURL_SOURCE_DIR}/include/curl/curlbuild.h.cmake
- ${CURL_BINARY_DIR}/include/curl/curlbuild.h)
configure_file(curl_config.h.cmake
${CMAKE_CURRENT_BINARY_DIR}/curl_config.h)
@@ -10,11 +8,11 @@ include(${CMAKE_CURRENT_BINARY_DIR}/Makefile.inc.cmake)
list(APPEND HHEADERS
${CMAKE_CURRENT_BINARY_DIR}/curl_config.h
- ${CURL_BINARY_DIR}/include/curl/curlbuild.h
)
if(MSVC AND NOT CURL_STATICLIB)
list(APPEND CSOURCES libcurl.rc)
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4127")
endif()
# SET(CSOURCES
@@ -124,6 +122,13 @@ if(WIN32)
if(NOT CURL_STATICLIB)
# Add "_imp" as a suffix before the extension to avoid conflicting with the statically linked "libcurl.lib"
set_target_properties(${LIB_NAME} PROPERTIES IMPORT_SUFFIX "_imp.lib")
+
+ set_target_properties (${LIB_NAME} PROPERTIES
+ DEBUG_POSTFIX "-d"
+ # Note: no postfix for release variants, let user choose what style of release he wants
+ # MINSIZEREL_POSTFIX "-z"
+ # RELWITHDEBINFO_POSTFIX "-g"
+ )
endif()
endif()
diff --git a/Utilities/cmcurl/lib/Makefile.inc b/Utilities/cmcurl/lib/Makefile.inc
index 19f58000a..5c0b930cf 100644
--- a/Utilities/cmcurl/lib/Makefile.inc
+++ b/Utilities/cmcurl/lib/Makefile.inc
@@ -53,7 +53,8 @@ LIB_CFILES = file.c timeval.c base64.c hostip.c progress.c formdata.c \
http_proxy.c non-ascii.c asyn-ares.c asyn-thread.c curl_gssapi.c \
http_ntlm.c curl_ntlm_wb.c curl_ntlm_core.c curl_sasl.c rand.c \
curl_multibyte.c hostcheck.c conncache.c pipeline.c dotdot.c \
- x509asn1.c http2.c smb.c curl_endian.c curl_des.c system_win32.c
+ x509asn1.c http2.c smb.c curl_endian.c curl_des.c system_win32.c \
+ mime.c
LIB_HFILES = arpa_telnet.h netrc.h file.h timeval.h hostip.h progress.h \
formdata.h cookie.h http.h sendf.h ftp.h url.h dict.h if2ip.h \
@@ -72,7 +73,7 @@ LIB_HFILES = arpa_telnet.h netrc.h file.h timeval.h hostip.h progress.h \
curl_sasl.h curl_multibyte.h hostcheck.h conncache.h \
curl_setup_once.h multihandle.h setup-vms.h pipeline.h dotdot.h \
x509asn1.h http2.h sigpipe.h smb.h curl_endian.h curl_des.h \
- curl_printf.h system_win32.h rand.h
+ curl_printf.h system_win32.h rand.h mime.h
LIB_RCFILES = libcurl.rc
diff --git a/Utilities/cmcurl/lib/asyn-ares.c b/Utilities/cmcurl/lib/asyn-ares.c
index 11a914f82..87e70b4d9 100644
--- a/Utilities/cmcurl/lib/asyn-ares.c
+++ b/Utilities/cmcurl/lib/asyn-ares.c
@@ -260,7 +260,7 @@ static int waitperform(struct connectdata *conn, int timeout_ms)
bitmask = ares_getsock((ares_channel)data->state.resolver, socks,
ARES_GETSOCK_MAXNUM);
- for(i=0; i < ARES_GETSOCK_MAXNUM; i++) {
+ for(i = 0; i < ARES_GETSOCK_MAXNUM; i++) {
pfd[i].events = 0;
pfd[i].revents = 0;
if(ARES_GETSOCK_READABLE(bitmask, i)) {
@@ -289,7 +289,7 @@ static int waitperform(struct connectdata *conn, int timeout_ms)
ARES_SOCKET_BAD);
else {
/* move through the descriptors and ask for processing on them */
- for(i=0; i < num; i++)
+ for(i = 0; i < num; i++)
ares_process_fd((ares_channel)data->state.resolver,
pfd[i].revents & (POLLRDNORM|POLLIN)?
pfd[i].fd:ARES_SOCKET_BAD,
@@ -355,7 +355,7 @@ CURLcode Curl_resolver_wait_resolv(struct connectdata *conn,
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
long timeout;
- struct timeval now = Curl_tvnow();
+ struct curltime now = Curl_tvnow();
struct Curl_dns_entry *temp_entry;
if(entry)
@@ -400,7 +400,7 @@ CURLcode Curl_resolver_wait_resolv(struct connectdata *conn,
if(Curl_pgrsUpdate(conn))
result = CURLE_ABORTED_BY_CALLBACK;
else {
- struct timeval now2 = Curl_tvnow();
+ struct curltime now2 = Curl_tvnow();
time_t timediff = Curl_tvdiff(now2, now); /* spent time */
if(timediff <= 0)
timeout -= 1; /* always deduct at least 1 */
diff --git a/Utilities/cmcurl/lib/asyn-thread.c b/Utilities/cmcurl/lib/asyn-thread.c
index 65fa6c5be..a86772965 100644
--- a/Utilities/cmcurl/lib/asyn-thread.c
+++ b/Utilities/cmcurl/lib/asyn-thread.c
@@ -210,6 +210,10 @@ int init_thread_sync_data(struct thread_data * td,
tsd->td = td;
tsd->port = port;
+ /* Treat the request as done until the thread actually starts so any early
+ * cleanup gets done properly.
+ */
+ tsd->done = 1;
#ifdef HAVE_GETADDRINFO
DEBUGASSERT(hints);
tsd->hints = *hints;
@@ -380,11 +384,11 @@ static bool init_resolve_thread(struct connectdata *conn,
const struct addrinfo *hints)
{
struct thread_data *td = calloc(1, sizeof(struct thread_data));
- int err = RESOLVER_ENOMEM;
+ int err = ENOMEM;
conn->async.os_specific = (void *)td;
if(!td)
- goto err_exit;
+ goto errno_exit;
conn->async.port = port;
conn->async.done = FALSE;
@@ -392,14 +396,20 @@ static bool init_resolve_thread(struct connectdata *conn,
conn->async.dns = NULL;
td->thread_hnd = curl_thread_t_null;
- if(!init_thread_sync_data(td, hostname, port, hints))
- goto err_exit;
+ if(!init_thread_sync_data(td, hostname, port, hints)) {
+ conn->async.os_specific = NULL;
+ free(td);
+ goto errno_exit;
+ }
free(conn->async.hostname);
conn->async.hostname = strdup(hostname);
if(!conn->async.hostname)
goto err_exit;
+ /* The thread will set this to 1 when complete. */
+ td->tsd.done = 0;
+
#ifdef HAVE_GETADDRINFO
td->thread_hnd = Curl_thread_create(getaddrinfo_thread, &td->tsd);
#else
@@ -407,9 +417,9 @@ static bool init_resolve_thread(struct connectdata *conn,
#endif
if(!td->thread_hnd) {
-#ifndef _WIN32_WCE
+ /* The thread never started, so mark it as done here for proper cleanup. */
+ td->tsd.done = 1;
err = errno;
-#endif
goto err_exit;
}
@@ -418,8 +428,8 @@ static bool init_resolve_thread(struct connectdata *conn,
err_exit:
destroy_async_data(&conn->async);
- SET_ERRNO(err);
-
+ errno_exit:
+ errno = err;
return FALSE;
}
@@ -594,28 +604,29 @@ Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn,
int *waitp)
{
struct addrinfo hints;
- struct in_addr in;
Curl_addrinfo *res;
int error;
char sbuf[12];
int pf = PF_INET;
-#ifdef CURLRES_IPV6
- struct in6_addr in6;
-#endif /* CURLRES_IPV6 */
*waitp = 0; /* default to synchronous response */
#ifndef USE_RESOLVE_ON_IPS
- /* First check if this is an IPv4 address string */
- if(Curl_inet_pton(AF_INET, hostname, &in) > 0)
- /* This is a dotted IP address 123.123.123.123-style */
- return Curl_ip2addr(AF_INET, &in, hostname, port);
-
+ {
+ struct in_addr in;
+ /* First check if this is an IPv4 address string */
+ if(Curl_inet_pton(AF_INET, hostname, &in) > 0)
+ /* This is a dotted IP address 123.123.123.123-style */
+ return Curl_ip2addr(AF_INET, &in, hostname, port);
+ }
#ifdef CURLRES_IPV6
- /* check if this is an IPv6 address string */
- if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0)
- /* This is an IPv6 address literal */
- return Curl_ip2addr(AF_INET6, &in6, hostname, port);
+ {
+ struct in6_addr in6;
+ /* check if this is an IPv6 address string */
+ if(Curl_inet_pton(AF_INET6, hostname, &in6) > 0)
+ /* This is an IPv6 address literal */
+ return Curl_ip2addr(AF_INET6, &in6, hostname, port);
+ }
#endif /* CURLRES_IPV6 */
#endif /* !USE_RESOLVE_ON_IPS */
@@ -654,7 +665,7 @@ Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn,
/* fall-back to blocking version */
infof(conn->data, "init_resolve_thread() failed for %s; %s\n",
- hostname, Curl_strerror(conn, ERRNO));
+ hostname, Curl_strerror(conn, errno));
error = Curl_getaddrinfo_ex(hostname, sbuf, &hints, &res);
if(error) {
diff --git a/Utilities/cmcurl/lib/conncache.h b/Utilities/cmcurl/lib/conncache.h
index f976cfdb4..14be4e8e7 100644
--- a/Utilities/cmcurl/lib/conncache.h
+++ b/Utilities/cmcurl/lib/conncache.h
@@ -27,7 +27,7 @@ struct conncache {
struct curl_hash hash;
size_t num_connections;
long next_connection_id;
- struct timeval last_cleanup;
+ struct curltime last_cleanup;
};
#define BUNDLE_NO_MULTIUSE -1
diff --git a/Utilities/cmcurl/lib/connect.c b/Utilities/cmcurl/lib/connect.c
index d4fd52b99..b7d10af55 100644
--- a/Utilities/cmcurl/lib/connect.c
+++ b/Utilities/cmcurl/lib/connect.c
@@ -180,12 +180,12 @@ singleipconnect(struct connectdata *conn,
* @unittest: 1303
*/
time_t Curl_timeleft(struct Curl_easy *data,
- struct timeval *nowp,
+ struct curltime *nowp,
bool duringconnect)
{
int timeout_set = 0;
time_t timeout_ms = duringconnect?DEFAULT_CONNECT_TIMEOUT:0;
- struct timeval now;
+ struct curltime now;
/* if a timeout is set, use the most restrictive one */
@@ -249,7 +249,7 @@ static CURLcode bindlocal(struct connectdata *conn,
struct sockaddr_in6 *si6 = (struct sockaddr_in6 *)&sa;
#endif
- struct Curl_dns_entry *h=NULL;
+ struct Curl_dns_entry *h = NULL;
unsigned short port = data->set.localport; /* use this port number, 0 for
"random" */
/* how many port numbers to try to bind to, increasing one at a time */
@@ -319,7 +319,7 @@ static CURLcode bindlocal(struct connectdata *conn,
* as a hostname or ip address.
*/
if(setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE,
- dev, (curl_socklen_t)strlen(dev)+1) != 0) {
+ dev, (curl_socklen_t)strlen(dev) + 1) != 0) {
error = SOCKERRNO;
infof(data, "SO_BINDTODEVICE %s failed with errno %d: %s;"
" will do regular bind\n",
@@ -607,7 +607,8 @@ void Curl_persistconninfo(struct connectdata *conn)
conn->data->info.conn_local_port = conn->local_port;
}
-/* retrieves ip address and port from a sockaddr structure */
+/* retrieves ip address and port from a sockaddr structure.
+ note it calls Curl_inet_ntop which sets errno on fail, not SOCKERRNO. */
static bool getaddressinfo(struct sockaddr *sa, char *addr,
long *port)
{
@@ -654,7 +655,7 @@ static bool getaddressinfo(struct sockaddr *sa, char *addr,
addr[0] = '\0';
*port = 0;
-
+ errno = EAFNOSUPPORT;
return FALSE;
}
@@ -672,11 +673,9 @@ void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd)
return;
if(!conn->bits.reuse && !conn->bits.tcp_fastopen) {
- int error;
-
len = sizeof(struct Curl_sockaddr_storage);
if(getpeername(sockfd, (struct sockaddr*) &ssrem, &len)) {
- error = SOCKERRNO;
+ int error = SOCKERRNO;
failf(data, "getpeername() failed with errno %d: %s",
error, Curl_strerror(conn, error));
return;
@@ -685,7 +684,7 @@ void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd)
len = sizeof(struct Curl_sockaddr_storage);
memset(&ssloc, 0, sizeof(ssloc));
if(getsockname(sockfd, (struct sockaddr*) &ssloc, &len)) {
- error = SOCKERRNO;
+ int error = SOCKERRNO;
failf(data, "getsockname() failed with errno %d: %s",
error, Curl_strerror(conn, error));
return;
@@ -693,18 +692,16 @@ void Curl_updateconninfo(struct connectdata *conn, curl_socket_t sockfd)
if(!getaddressinfo((struct sockaddr*)&ssrem,
conn->primary_ip, &conn->primary_port)) {
- error = ERRNO;
failf(data, "ssrem inet_ntop() failed with errno %d: %s",
- error, Curl_strerror(conn, error));
+ errno, Curl_strerror(conn, errno));
return;
}
memcpy(conn->ip_addr_str, conn->primary_ip, MAX_IPADR_LEN);
if(!getaddressinfo((struct sockaddr*)&ssloc,
conn->local_ip, &conn->local_port)) {
- error = ERRNO;
failf(data, "ssloc inet_ntop() failed with errno %d: %s",
- error, Curl_strerror(conn, error));
+ errno, Curl_strerror(conn, errno));
return;
}
@@ -726,7 +723,7 @@ CURLcode Curl_is_connected(struct connectdata *conn,
CURLcode result = CURLE_OK;
time_t allow;
int error = 0;
- struct timeval now;
+ struct curltime now;
int rc;
int i;
@@ -751,7 +748,7 @@ CURLcode Curl_is_connected(struct connectdata *conn,
return CURLE_OPERATION_TIMEDOUT;
}
- for(i=0; i<2; i++) {
+ for(i = 0; i<2; i++) {
const int other = i ^ 1;
if(conn->tempsock[i] == CURL_SOCKET_BAD)
continue;
@@ -879,19 +876,6 @@ void Curl_tcpnodelay(struct connectdata *conn, curl_socket_t sockfd)
curl_socklen_t onoff = (curl_socklen_t) 1;
int level = IPPROTO_TCP;
-#if 0
- /* The use of getprotobyname() is disabled since it isn't thread-safe on
- numerous systems. On these getprotobyname_r() should be used instead, but
- that exists in at least one 4 arg version and one 5 arg version, and
- since the proto number rarely changes anyway we now just use the hard
- coded number. The "proper" fix would need a configure check for the
- correct function much in the same style the gethostbyname_r versions are
- detected. */
- struct protoent *pe = getprotobyname("tcp");
- if(pe)
- level = pe->p_proto;
-#endif
-
#if defined(CURL_DISABLE_VERBOSE_STRINGS)
(void) conn;
#endif
@@ -916,7 +900,7 @@ void Curl_tcpnodelay(struct connectdata *conn, curl_socket_t sockfd)
static void nosigpipe(struct connectdata *conn,
curl_socket_t sockfd)
{
- struct Curl_easy *data= conn->data;
+ struct Curl_easy *data = conn->data;
int onoff = 1;
if(setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&onoff,
sizeof(onoff)) < 0)
@@ -1008,9 +992,8 @@ static CURLcode singleipconnect(struct connectdata *conn,
if(!getaddressinfo((struct sockaddr*)&addr.sa_addr,
ipaddress, &port)) {
/* malformed address or bug in inet_ntop, try next address */
- error = ERRNO;
failf(data, "sa_addr inet_ntop() failed with errno %d: %s",
- error, Curl_strerror(conn, error));
+ errno, Curl_strerror(conn, errno));
Curl_closesocket(conn, sockfd);
return CURLE_OK;
}
@@ -1076,16 +1059,25 @@ static CURLcode singleipconnect(struct connectdata *conn,
if(!isconnected && (conn->socktype == SOCK_STREAM)) {
if(conn->bits.tcp_fastopen) {
#if defined(CONNECT_DATA_IDEMPOTENT) /* OS X */
- sa_endpoints_t endpoints;
- endpoints.sae_srcif = 0;
- endpoints.sae_srcaddr = NULL;
- endpoints.sae_srcaddrlen = 0;
- endpoints.sae_dstaddr = &addr.sa_addr;
- endpoints.sae_dstaddrlen = addr.addrlen;
-
- rc = connectx(sockfd, &endpoints, SAE_ASSOCID_ANY,
- CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT,
- NULL, 0, NULL, NULL);
+#ifdef HAVE_BUILTIN_AVAILABLE
+ if(__builtin_available(macOS 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *)) {
+#endif /* HAVE_BUILTIN_AVAILABLE */
+ sa_endpoints_t endpoints;
+ endpoints.sae_srcif = 0;
+ endpoints.sae_srcaddr = NULL;
+ endpoints.sae_srcaddrlen = 0;
+ endpoints.sae_dstaddr = &addr.sa_addr;
+ endpoints.sae_dstaddrlen = addr.addrlen;
+
+ rc = connectx(sockfd, &endpoints, SAE_ASSOCID_ANY,
+ CONNECT_RESUME_ON_READ_WRITE | CONNECT_DATA_IDEMPOTENT,
+ NULL, 0, NULL, NULL);
+#ifdef HAVE_BUILTIN_AVAILABLE
+ }
+ else {
+ rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
+ }
+#endif /* HAVE_BUILTIN_AVAILABLE */
#elif defined(MSG_FASTOPEN) /* Linux */
if(conn->given->flags & PROTOPT_SSL)
rc = connect(sockfd, &addr.sa_addr, addr.addrlen);
@@ -1153,7 +1145,7 @@ CURLcode Curl_connecthost(struct connectdata *conn, /* context */
const struct Curl_dns_entry *remotehost)
{
struct Curl_easy *data = conn->data;
- struct timeval before = Curl_tvnow();
+ struct curltime before = Curl_tvnow();
CURLcode result = CURLE_COULDNT_CONNECT;
time_t timeout_ms = Curl_timeleft(data, &before, TRUE);
@@ -1169,7 +1161,6 @@ CURLcode Curl_connecthost(struct connectdata *conn, /* context */
conn->tempaddr[1] = NULL;
conn->tempsock[0] = CURL_SOCKET_BAD;
conn->tempsock[1] = CURL_SOCKET_BAD;
- Curl_expire(conn->data, HAPPY_EYEBALLS_TIMEOUT, EXPIRE_HAPPY_EYEBALLS);
/* Max time for the next connection attempt */
conn->timeoutms_per_addr =
@@ -1190,6 +1181,7 @@ CURLcode Curl_connecthost(struct connectdata *conn, /* context */
}
data->info.numconnects++; /* to track the number of connections made */
+ Curl_expire(conn->data, HAPPY_EYEBALLS_TIMEOUT, EXPIRE_HAPPY_EYEBALLS);
return CURLE_OK;
}
@@ -1341,7 +1333,7 @@ CURLcode Curl_socket(struct connectdata *conn,
addr->family = ai->ai_family;
addr->socktype = conn->socktype;
- addr->protocol = conn->socktype==SOCK_DGRAM?IPPROTO_UDP:ai->ai_protocol;
+ addr->protocol = conn->socktype == SOCK_DGRAM?IPPROTO_UDP:ai->ai_protocol;
addr->addrlen = ai->ai_addrlen;
if(addr->addrlen > sizeof(struct Curl_sockaddr_storage))
diff --git a/Utilities/cmcurl/lib/connect.h b/Utilities/cmcurl/lib/connect.h
index 44bdb1051..3f05c3978 100644
--- a/Utilities/cmcurl/lib/connect.h
+++ b/Utilities/cmcurl/lib/connect.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -36,7 +36,7 @@ CURLcode Curl_connecthost(struct connectdata *conn,
/* generic function that returns how much time there's left to run, according
to the timeouts set */
time_t Curl_timeleft(struct Curl_easy *data,
- struct timeval *nowp,
+ struct curltime *nowp,
bool duringconnect);
#define DEFAULT_CONNECT_TIMEOUT 300000 /* milliseconds == five minutes */
diff --git a/Utilities/cmcurl/lib/content_encoding.c b/Utilities/cmcurl/lib/content_encoding.c
index 652ed9764..110226034 100644
--- a/Utilities/cmcurl/lib/content_encoding.c
+++ b/Utilities/cmcurl/lib/content_encoding.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -227,7 +227,7 @@ static enum {
extra_len = (data[1] << 8) | data[0];
- if(len < (extra_len+2))
+ if(len < (extra_len + 2))
return GZIP_UNDERFLOW;
len -= (extra_len + 2);
@@ -288,7 +288,7 @@ Curl_unencode_gzip_write(struct connectdata *conn,
if(strcmp(zlibVersion(), "1.2.0.4") >= 0) {
/* zlib ver. >= 1.2.0.4 supports transparent gzip decompressing */
- if(inflateInit2(z, MAX_WBITS+32) != Z_OK) {
+ if(inflateInit2(z, MAX_WBITS + 32) != Z_OK) {
return process_zlib_error(conn, z);
}
k->zlib_init = ZLIB_INIT_GZIP; /* Transparent gzip decompress state */
diff --git a/Utilities/cmcurl/lib/cookie.c b/Utilities/cmcurl/lib/cookie.c
index 6b678aeb8..7fb596af4 100644
--- a/Utilities/cmcurl/lib/cookie.c
+++ b/Utilities/cmcurl/lib/cookie.c
@@ -125,7 +125,7 @@ static bool tailmatch(const char *cooke_domain, const char *hostname)
if(hostname_len < cookie_domain_len)
return FALSE;
- if(!strcasecompare(cooke_domain, hostname+hostname_len-cookie_domain_len))
+ if(!strcasecompare(cooke_domain, hostname + hostname_len-cookie_domain_len))
return FALSE;
/* A lead char of cookie_domain is not '.'.
@@ -375,9 +375,8 @@ Curl_cookie_add(struct Curl_easy *data,
unless set */
{
struct Cookie *clist;
- char name[MAX_NAME];
struct Cookie *co;
- struct Cookie *lastc=NULL;
+ struct Cookie *lastc = NULL;
time_t now = time(NULL);
bool replace_old = FALSE;
bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */
@@ -397,17 +396,19 @@ Curl_cookie_add(struct Curl_easy *data,
if(httpheader) {
/* This line was read off a HTTP-header */
+ char name[MAX_NAME];
+ char what[MAX_NAME];
const char *ptr;
const char *semiptr;
- char *what;
- what = malloc(MAX_COOKIE_LINE);
- if(!what) {
+ size_t linelength = strlen(lineptr);
+ if(linelength > MAX_COOKIE_LINE) {
+ /* discard overly long lines at once */
free(co);
return NULL;
}
- semiptr=strchr(lineptr, ';'); /* first, find a semicolon */
+ semiptr = strchr(lineptr, ';'); /* first, find a semicolon */
while(*lineptr && ISBLANK(*lineptr))
lineptr++;
@@ -415,9 +416,9 @@ Curl_cookie_add(struct Curl_easy *data,
ptr = lineptr;
do {
/* we have a <what>=<this> pair or a stand-alone word here */
- name[0]=what[0]=0; /* init the buffers */
+ name[0] = what[0] = 0; /* init the buffers */
if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n=] =%"
- MAX_COOKIE_LINE_TXT "[^;\r\n]",
+ MAX_NAME_TXT "[^;\r\n]",
name, what)) {
/* Use strstore() below to properly deal with received cookie
headers that have the same string property set more than once,
@@ -425,10 +426,24 @@ Curl_cookie_add(struct Curl_easy *data,
const char *whatptr;
bool done = FALSE;
bool sep;
- size_t len=strlen(what);
+ size_t len = strlen(what);
size_t nlen = strlen(name);
const char *endofn = &ptr[ nlen ];
+ infof(data, "cookie size: name/val %d + %d bytes\n",
+ nlen, len);
+
+ if(nlen >= (MAX_NAME-1) || len >= (MAX_NAME-1) ||
+ ((nlen + len) > MAX_NAME)) {
+ /* too long individual name or contents, or too long combination of
+ name + contents. Chrome and Firefox support 4095 or 4096 bytes
+ combo. */
+ freecookie(co);
+ infof(data, "oversized cookie dropped, name/val %d + %d bytes\n",
+ nlen, len);
+ return NULL;
+ }
+
/* name ends with a '=' ? */
sep = (*endofn == '=')?TRUE:FALSE;
@@ -440,18 +455,18 @@ Curl_cookie_add(struct Curl_easy *data,
endofn--;
nlen--;
}
- name[nlen]=0; /* new end of name */
+ name[nlen] = 0; /* new end of name */
}
}
/* Strip off trailing whitespace from the 'what' */
while(len && ISBLANK(what[len-1])) {
- what[len-1]=0;
+ what[len-1] = 0;
len--;
}
/* Skip leading whitespace from the 'what' */
- whatptr=what;
+ whatptr = what;
while(*whatptr && ISBLANK(*whatptr))
whatptr++;
@@ -484,6 +499,7 @@ Curl_cookie_add(struct Curl_easy *data,
badcookie = TRUE; /* out of memory bad */
break;
}
+ free(co->spath); /* if this is set again */
co->spath = sanitize_cookie_path(co->path);
if(!co->spath) {
badcookie = TRUE; /* out of memory bad */
@@ -510,7 +526,7 @@ Curl_cookie_add(struct Curl_easy *data,
/* check for more dots */
dotp = strchr(whatptr, '.');
if(!dotp && !strcasecompare("localhost", whatptr))
- domain=":";
+ domain = ":";
}
#endif
@@ -525,14 +541,14 @@ Curl_cookie_add(struct Curl_easy *data,
break;
}
if(!is_ip)
- co->tailmatch=TRUE; /* we always do that if the domain name was
- given */
+ co->tailmatch = TRUE; /* we always do that if the domain name was
+ given */
}
else {
/* we did not get a tailmatch and then the attempted set domain
is not a domain to which the current host belongs. Mark as
bad. */
- badcookie=TRUE;
+ badcookie = TRUE;
infof(data, "skipped cookie with bad tailmatch domain: %s\n",
whatptr);
}
@@ -581,26 +597,32 @@ Curl_cookie_add(struct Curl_easy *data,
continue;
}
- ptr=semiptr+1;
+ ptr = semiptr + 1;
while(*ptr && ISBLANK(*ptr))
ptr++;
- semiptr=strchr(ptr, ';'); /* now, find the next semicolon */
+ semiptr = strchr(ptr, ';'); /* now, find the next semicolon */
if(!semiptr && *ptr)
/* There are no more semicolons, but there's a final name=value pair
coming up */
- semiptr=strchr(ptr, '\0');
+ semiptr = strchr(ptr, '\0');
} while(semiptr);
if(co->maxage) {
- co->expires =
- curlx_strtoofft((*co->maxage=='\"')?
- &co->maxage[1]:&co->maxage[0], NULL, 10);
- if(CURL_OFF_T_MAX - now < co->expires)
- /* avoid overflow */
+ CURLofft offt;
+ offt = curlx_strtoofft((*co->maxage == '\"')?
+ &co->maxage[1]:&co->maxage[0], NULL, 10,
+ &co->expires);
+ if(offt == CURL_OFFT_FLOW)
+ /* overflow, used max value */
co->expires = CURL_OFF_T_MAX;
- else
- co->expires += now;
+ else if(!offt) {
+ if(CURL_OFF_T_MAX - now < co->expires)
+ /* would overflow */
+ co->expires = CURL_OFF_T_MAX;
+ else
+ co->expires += now;
+ }
}
else if(co->expirestr) {
/* Note that if the date couldn't get parsed for whatever reason,
@@ -619,7 +641,7 @@ Curl_cookie_add(struct Curl_easy *data,
if(!badcookie && !co->domain) {
if(domain) {
/* no domain was given in the header line, set the default */
- co->domain=strdup(domain);
+ co->domain = strdup(domain);
if(!co->domain)
badcookie = TRUE;
}
@@ -639,11 +661,11 @@ Curl_cookie_add(struct Curl_easy *data,
else
endslash = memrchr(path, '/', (size_t)(queryp - path));
if(endslash) {
- size_t pathlen = (size_t)(endslash-path+1); /* include ending slash */
- co->path=malloc(pathlen+1); /* one extra for the zero byte */
+ size_t pathlen = (size_t)(endslash-path + 1); /* include end slash */
+ co->path = malloc(pathlen + 1); /* one extra for the zero byte */
if(co->path) {
memcpy(co->path, path, pathlen);
- co->path[pathlen]=0; /* zero terminate */
+ co->path[pathlen] = 0; /* zero terminate */
co->spath = sanitize_cookie_path(co->path);
if(!co->spath)
badcookie = TRUE; /* out of memory bad */
@@ -653,8 +675,6 @@ Curl_cookie_add(struct Curl_easy *data,
}
}
- free(what);
-
if(badcookie || !co->name) {
/* we didn't get a cookie name or a bad one,
this is an illegal line, bail out */
@@ -668,7 +688,7 @@ Curl_cookie_add(struct Curl_easy *data,
reading the odd netscape cookies-file format here */
char *ptr;
char *firstptr;
- char *tok_buf=NULL;
+ char *tok_buf = NULL;
int fields;
/* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies
@@ -689,19 +709,19 @@ Curl_cookie_add(struct Curl_easy *data,
return NULL;
}
/* strip off the possible end-of-line characters */
- ptr=strchr(lineptr, '\r');
+ ptr = strchr(lineptr, '\r');
if(ptr)
- *ptr=0; /* clear it */
- ptr=strchr(lineptr, '\n');
+ *ptr = 0; /* clear it */
+ ptr = strchr(lineptr, '\n');
if(ptr)
- *ptr=0; /* clear it */
+ *ptr = 0; /* clear it */
- firstptr=strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */
+ firstptr = strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */
/* Now loop through the fields and init the struct we already have
allocated */
- for(ptr=firstptr, fields=0; ptr && !badcookie;
- ptr=strtok_r(NULL, "\t", &tok_buf), fields++) {
+ for(ptr = firstptr, fields = 0; ptr && !badcookie;
+ ptr = strtok_r(NULL, "\t", &tok_buf), fields++) {
switch(fields) {
case 0:
if(ptr[0]=='.') /* skip preceding dots */
@@ -712,7 +732,7 @@ Curl_cookie_add(struct Curl_easy *data,
break;
case 1:
/* This field got its explanation on the 23rd of May 2001 by
- Andrés García:
+ Andrés García:
flag: A TRUE/FALSE value indicating if all machines within a given
domain can access the variable. This value is set automatically by
@@ -726,7 +746,7 @@ Curl_cookie_add(struct Curl_easy *data,
case 2:
/* It turns out, that sometimes the file format allows the path
field to remain not filled in, we try to detect this and work
- around it! Andrés García made us aware of this... */
+ around it! Andrés García made us aware of this... */
if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) {
/* only if the path doesn't look like a boolean option! */
co->path = strdup(ptr);
@@ -753,7 +773,8 @@ Curl_cookie_add(struct Curl_easy *data,
co->secure = strcasecompare(ptr, "TRUE")?TRUE:FALSE;
break;
case 4:
- co->expires = curlx_strtoofft(ptr, NULL, 10);
+ if(curlx_strtoofft(ptr, NULL, 10, &co->expires))
+ badcookie = TRUE;
break;
case 5:
co->name = strdup(ptr);
@@ -828,7 +849,7 @@ Curl_cookie_add(struct Curl_easy *data,
if(strcasecompare(clist->domain, co->domain) &&
(clist->tailmatch == co->tailmatch))
/* The domains are identical */
- replace_old=TRUE;
+ replace_old = TRUE;
}
else if(!clist->domain && !co->domain)
replace_old = TRUE;
@@ -957,7 +978,7 @@ struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
{
struct CookieInfo *c;
FILE *fp = NULL;
- bool fromfile=TRUE;
+ bool fromfile = TRUE;
char *line = NULL;
if(NULL == inc) {
@@ -977,7 +998,7 @@ struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
if(file && !strcmp(file, "-")) {
fp = stdin;
- fromfile=FALSE;
+ fromfile = FALSE;
}
else if(file && !*file) {
/* points to a "" string */
@@ -998,12 +1019,12 @@ struct CookieInfo *Curl_cookie_init(struct Curl_easy *data,
while(get_line(line, MAX_COOKIE_LINE, fp)) {
if(checkprefix("Set-Cookie:", line)) {
/* This is a cookie line, get it! */
- lineptr=&line[11];
- headerline=TRUE;
+ lineptr = &line[11];
+ headerline = TRUE;
}
else {
- lineptr=line;
- headerline=FALSE;
+ lineptr = line;
+ headerline = FALSE;
}
while(*lineptr && ISBLANK(*lineptr))
lineptr++;
@@ -1113,7 +1134,7 @@ struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
struct Cookie *newco;
struct Cookie *co;
time_t now = time(NULL);
- struct Cookie *mainco=NULL;
+ struct Cookie *mainco = NULL;
size_t matches = 0;
bool is_ip;
@@ -1185,7 +1206,7 @@ struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
co = mainco;
- for(i=0; co; co = co->next)
+ for(i = 0; co; co = co->next)
array[i++] = co;
/* now sort the cookie pointers in path length order */
@@ -1194,8 +1215,8 @@ struct Cookie *Curl_cookie_getlist(struct CookieInfo *c,
/* remake the linked list order according to the new order */
mainco = array[0]; /* start here */
- for(i=0; i<matches-1; i++)
- array[i]->next = array[i+1];
+ for(i = 0; i<matches-1; i++)
+ array[i]->next = array[i + 1];
array[matches-1]->next = NULL; /* terminate the list */
free(array); /* remove the temporary data again */
@@ -1335,7 +1356,7 @@ static int cookie_output(struct CookieInfo *c, const char *dumphere)
{
struct Cookie *co;
FILE *out;
- bool use_stdout=FALSE;
+ bool use_stdout = FALSE;
char *format_ptr;
if((NULL == c) || (0 == c->numcookies))
@@ -1349,7 +1370,7 @@ static int cookie_output(struct CookieInfo *c, const char *dumphere)
if(!strcmp("-", dumphere)) {
/* use stdout */
out = stdout;
- use_stdout=TRUE;
+ use_stdout = TRUE;
}
else {
out = fopen(dumphere, FOPEN_WRITETEXT);
@@ -1382,7 +1403,7 @@ static int cookie_output(struct CookieInfo *c, const char *dumphere)
return 0;
}
-struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
+static struct curl_slist *cookie_list(struct Curl_easy *data)
{
struct curl_slist *list = NULL;
struct curl_slist *beg;
@@ -1413,6 +1434,15 @@ struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
return list;
}
+struct curl_slist *Curl_cookie_list(struct Curl_easy *data)
+{
+ struct curl_slist *list;
+ Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
+ list = cookie_list(data);
+ Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
+ return list;
+}
+
void Curl_flush_cookies(struct Curl_easy *data, int cleanup)
{
if(data->set.str[STRING_COOKIEJAR]) {
diff --git a/Utilities/cmcurl/lib/cookie.h b/Utilities/cmcurl/lib/cookie.h
index a9a45785c..cb50b71c6 100644
--- a/Utilities/cmcurl/lib/cookie.h
+++ b/Utilities/cmcurl/lib/cookie.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -62,13 +62,16 @@ struct CookieInfo {
that comprise the cookie non-terminal in the syntax description of the
Set-Cookie header)"
+ We allow max 5000 bytes cookie header. Max 4095 bytes length per cookie
+ name and value. Name + value may not exceed 4096 bytes.
+
*/
#define MAX_COOKIE_LINE 5000
#define MAX_COOKIE_LINE_TXT "4999"
-/* This is the maximum length of a cookie name we deal with: */
-#define MAX_NAME 1024
-#define MAX_NAME_TXT "1023"
+/* This is the maximum length of a cookie name or content we deal with: */
+#define MAX_NAME 4096
+#define MAX_NAME_TXT "4095"
struct Curl_easy;
/*
diff --git a/Utilities/cmcurl/lib/curl_addrinfo.c b/Utilities/cmcurl/lib/curl_addrinfo.c
index 1adf3198a..6eb28bbcb 100644
--- a/Utilities/cmcurl/lib/curl_addrinfo.c
+++ b/Utilities/cmcurl/lib/curl_addrinfo.c
@@ -286,7 +286,7 @@ Curl_he2ai(const struct hostent *he, int port)
DEBUGASSERT((he->h_name != NULL) && (he->h_addr_list != NULL));
- for(i=0; (curr = he->h_addr_list[i]) != NULL; i++) {
+ for(i = 0; (curr = he->h_addr_list[i]) != NULL; i++) {
size_t ss_size;
#ifdef ENABLE_IPV6
@@ -570,9 +570,9 @@ curl_dogetaddrinfo(const char *hostname,
int line, const char *source)
{
#ifdef USE_LWIPSOCK
- int res=lwip_getaddrinfo(hostname, service, hints, result);
+ int res = lwip_getaddrinfo(hostname, service, hints, result);
#else
- int res=(getaddrinfo)(hostname, service, hints, result);
+ int res = (getaddrinfo)(hostname, service, hints, result);
#endif
if(0 == res)
/* success */
diff --git a/Utilities/cmcurl/lib/curl_config.h.cmake b/Utilities/cmcurl/lib/curl_config.h.cmake
index f9d54b4bd..abe9ffe0e 100644
--- a/Utilities/cmcurl/lib/curl_config.h.cmake
+++ b/Utilities/cmcurl/lib/curl_config.h.cmake
@@ -42,9 +42,6 @@
/* to disable RTSP */
#cmakedefine CURL_DISABLE_RTSP 1
-/* to disable RTMP */
-#cmakedefine CURL_DISABLE_RTMP 1
-
/* to disable SMB */
#cmakedefine CURL_DISABLE_SMB 1
@@ -73,9 +70,6 @@
/* when not building a shared library */
#cmakedefine CURL_STATICLIB 1
-/* Set to explicitly specify we don't want to use thread-safe functions */
-#cmakedefine DISABLED_THREADSAFE 1
-
/* your Entropy Gathering Daemon socket pathname */
#cmakedefine EGD_SOCKET ${EGD_SOCKET}
@@ -885,6 +879,9 @@
/* The size of `off_t', as computed by sizeof. */
@SIZEOF_OFF_T_CODE@
+/* The size of `curl_off_t', as computed by sizeof. */
+@SIZEOF_CURL_OFF_T_CODE@
+
/* The size of `size_t', as computed by sizeof. */
@SIZEOF_SIZE_T_CODE@
@@ -960,9 +957,6 @@
/* Version number of package */
#cmakedefine VERSION ${VERSION}
-/* Define to avoid automatic inclusion of winsock.h */
-#cmakedefine WIN32_LEAN_AND_MEAN 1
-
/* Define to 1 if OS is AIX. */
#ifndef _ALL_SOURCE
# undef _ALL_SOURCE
diff --git a/Utilities/cmcurl/lib/curl_fnmatch.c b/Utilities/cmcurl/lib/curl_fnmatch.c
index 46d3ada1e..631268bc1 100644
--- a/Utilities/cmcurl/lib/curl_fnmatch.c
+++ b/Utilities/cmcurl/lib/curl_fnmatch.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -151,7 +151,7 @@ static int setcharset(unsigned char **p, unsigned char *charset)
(*p)++;
}
else if(c == '[') {
- char c2 = *((*p)+1);
+ char c2 = *((*p) + 1);
if(c2 == ':') { /* there has to be a keyword */
(*p) += 2;
if(parsekeyword(p, charset)) {
@@ -319,9 +319,9 @@ static int loop(const unsigned char *pattern, const unsigned char *string)
switch(state) {
case CURLFNM_LOOP_DEFAULT:
if(*p == '*') {
- while(*(p+1) == '*') /* eliminate multiple stars */
+ while(*(p + 1) == '*') /* eliminate multiple stars */
p++;
- if(*s == '\0' && *(p+1) == '\0')
+ if(*s == '\0' && *(p + 1) == '\0')
return CURL_FNMATCH_MATCH;
rc = loop(p + 1, s); /* *.txt matches .txt <=> .txt matches .txt */
if(rc == CURL_FNMATCH_MATCH)
@@ -351,7 +351,7 @@ static int loop(const unsigned char *pattern, const unsigned char *string)
p++;
}
else if(*p == '[') {
- unsigned char *pp = p+1; /* cannot handle with pointer to register */
+ unsigned char *pp = p + 1; /* cannot handle with pointer to register */
if(setcharset(&pp, charset)) {
int found = FALSE;
if(charset[(unsigned int)*s])
@@ -381,7 +381,7 @@ static int loop(const unsigned char *pattern, const unsigned char *string)
found = !found;
if(found) {
- p = pp+1;
+ p = pp + 1;
s++;
memset(charset, 0, CURLFNM_CHSET_SIZE);
}
diff --git a/Utilities/cmcurl/lib/curl_ntlm_core.c b/Utilities/cmcurl/lib/curl_ntlm_core.c
index aea545295..5154949e6 100644
--- a/Utilities/cmcurl/lib/curl_ntlm_core.c
+++ b/Utilities/cmcurl/lib/curl_ntlm_core.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -31,6 +31,25 @@
* https://www.innovation.ch/java/ntlm.html
*/
+/* Please keep the SSL backend-specific #if branches in this order:
+
+ 1. USE_OPENSSL
+ 2. USE_GNUTLS_NETTLE
+ 3. USE_GNUTLS
+ 4. USE_NSS
+ 5. USE_MBEDTLS
+ 6. USE_DARWINSSL
+ 7. USE_OS400CRYPTO
+ 8. USE_WIN32_CRYPTO
+
+ This ensures that:
+ - the same SSL branch gets activated throughout this source
+ file even if multiple backends are enabled at the same time.
+ - OpenSSL and NSS have higher priority than Windows Crypt, due
+ to issues with the latter supporting NTLM2Session responses
+ in NTLM type-3 messages.
+ */
+
#if !defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO)
#ifdef USE_OPENSSL
@@ -76,14 +95,6 @@
# define MD5_DIGEST_LENGTH 16
# define MD4_DIGEST_LENGTH 16
-#elif defined(USE_MBEDTLS)
-
-# include <mbedtls/des.h>
-# include <mbedtls/md4.h>
-# if !defined(MBEDTLS_MD4_C)
-# include "curl_md4.h"
-# endif
-
#elif defined(USE_NSS)
# include <nss.h>
@@ -92,6 +103,14 @@
# include "curl_md4.h"
# define MD5_DIGEST_LENGTH MD5_LENGTH
+#elif defined(USE_MBEDTLS)
+
+# include <mbedtls/des.h>
+# include <mbedtls/md4.h>
+# if !defined(MBEDTLS_MD4_C)
+# include "curl_md4.h"
+# endif
+
#elif defined(USE_DARWINSSL)
# include <CommonCrypto/CommonCryptor.h>
@@ -196,26 +215,6 @@ static void setup_des_key(const unsigned char *key_56,
gcry_cipher_setkey(*des, key, sizeof(key));
}
-#elif defined(USE_MBEDTLS)
-
-static bool encrypt_des(const unsigned char *in, unsigned char *out,
- const unsigned char *key_56)
-{
- mbedtls_des_context ctx;
- char key[8];
-
- /* Expand the 56-bit key to 64-bits */
- extend_key_56_to_64(key_56, key);
-
- /* Set the key parity to odd */
- mbedtls_des_key_set_parity((unsigned char *) key);
-
- /* Perform the encryption */
- mbedtls_des_init(&ctx);
- mbedtls_des_setkey_enc(&ctx, (unsigned char *) key);
- return mbedtls_des_crypt_ecb(&ctx, in, out) == 0;
-}
-
#elif defined(USE_NSS)
/*
@@ -281,6 +280,26 @@ fail:
return rv;
}
+#elif defined(USE_MBEDTLS)
+
+static bool encrypt_des(const unsigned char *in, unsigned char *out,
+ const unsigned char *key_56)
+{
+ mbedtls_des_context ctx;
+ char key[8];
+
+ /* Expand the 56-bit key to 64-bits */
+ extend_key_56_to_64(key_56, key);
+
+ /* Set the key parity to odd */
+ mbedtls_des_key_set_parity((unsigned char *) key);
+
+ /* Perform the encryption */
+ mbedtls_des_init(&ctx);
+ mbedtls_des_setkey_enc(&ctx, (unsigned char *) key);
+ return mbedtls_des_crypt_ecb(&ctx, in, out) == 0;
+}
+
#elif defined(USE_DARWINSSL)
static bool encrypt_des(const unsigned char *in, unsigned char *out,
@@ -428,7 +447,7 @@ void Curl_ntlm_core_lm_resp(const unsigned char *keys,
setup_des_key(keys + 14, &des);
gcry_cipher_encrypt(des, results + 16, 8, plaintext, 8);
gcry_cipher_close(des);
-#elif defined(USE_MBEDTLS) || defined(USE_NSS) || defined(USE_DARWINSSL) \
+#elif defined(USE_NSS) || defined(USE_MBEDTLS) || defined(USE_DARWINSSL) \
|| defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO)
encrypt_des(plaintext, results, keys);
encrypt_des(plaintext, results + 8, keys + 7);
@@ -492,7 +511,7 @@ CURLcode Curl_ntlm_core_mk_lm_hash(struct Curl_easy *data,
setup_des_key(pw + 7, &des);
gcry_cipher_encrypt(des, lmbuffer + 8, 8, magic, 8);
gcry_cipher_close(des);
-#elif defined(USE_MBEDTLS) || defined(USE_NSS) || defined(USE_DARWINSSL) \
+#elif defined(USE_NSS) || defined(USE_MBEDTLS) || defined(USE_DARWINSSL) \
|| defined(USE_OS400CRYPTO) || defined(USE_WIN32_CRYPTO)
encrypt_des(magic, lmbuffer, pw);
encrypt_des(magic, lmbuffer + 8, pw + 7);
@@ -571,13 +590,18 @@ CURLcode Curl_ntlm_core_mk_nt_hash(struct Curl_easy *data,
gcry_md_write(MD4pw, pw, 2 * len);
memcpy(ntbuffer, gcry_md_read(MD4pw, 0), MD4_DIGEST_LENGTH);
gcry_md_close(MD4pw);
-#elif defined(USE_NSS) || defined(USE_OS400CRYPTO) || \
- (defined(USE_MBEDTLS) && !defined(MBEDTLS_MD4_C))
+#elif defined(USE_NSS)
Curl_md4it(ntbuffer, pw, 2 * len);
#elif defined(USE_MBEDTLS)
+#if defined(MBEDTLS_MD4_C)
mbedtls_md4(pw, 2 * len, ntbuffer);
+#else
+ Curl_md4it(ntbuffer, pw, 2 * len);
+#endif
#elif defined(USE_DARWINSSL)
(void)CC_MD4(pw, (CC_LONG)(2 * len), ntbuffer);
+#elif defined(USE_OS400CRYPTO)
+ Curl_md4it(ntbuffer, pw, 2 * len);
#elif defined(USE_WIN32_CRYPTO)
HCRYPTPROV hprov;
if(CryptAcquireContext(&hprov, NULL, NULL, PROV_RSA_FULL,
@@ -780,7 +804,7 @@ CURLcode Curl_ntlm_core_mk_lmv2_resp(unsigned char *ntlmv2hash,
/* Concatenate the HMAC MD5 output with the client nonce */
memcpy(lmresp, hmac_output, 16);
- memcpy(lmresp+16, challenge_client, 8);
+ memcpy(lmresp + 16, challenge_client, 8);
return result;
}
diff --git a/Utilities/cmcurl/lib/curl_ntlm_core.h b/Utilities/cmcurl/lib/curl_ntlm_core.h
index 4a83d40bc..07ef5deae 100644
--- a/Utilities/cmcurl/lib/curl_ntlm_core.h
+++ b/Utilities/cmcurl/lib/curl_ntlm_core.h
@@ -26,13 +26,19 @@
#if defined(USE_NTLM)
+/* If NSS is the first available SSL backend (see order in curl_ntlm_core.c)
+ then it must be initialized to be used by NTLM. */
+#if !defined(USE_OPENSSL) && \
+ !defined(USE_GNUTLS_NETTLE) && \
+ !defined(USE_GNUTLS) && \
+ defined(USE_NSS)
+#define NTLM_NEEDS_NSS_INIT
+#endif
+
#if !defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO)
#ifdef USE_OPENSSL
-# if !defined(OPENSSL_VERSION_NUMBER) && \
- !defined(HEADER_SSL_H) && !defined(HEADER_MD5_H)
-# error "curl_ntlm_core.h shall not be included before OpenSSL headers."
-# endif
+# include <openssl/ssl.h>
#endif
/* Define USE_NTRESPONSES in order to make the type-3 message include
diff --git a/Utilities/cmcurl/lib/curl_ntlm_wb.c b/Utilities/cmcurl/lib/curl_ntlm_wb.c
index 9f5b87bc3..03f47a3a5 100644
--- a/Utilities/cmcurl/lib/curl_ntlm_wb.c
+++ b/Utilities/cmcurl/lib/curl_ntlm_wb.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -48,6 +48,7 @@
#include "sendf.h"
#include "select.h"
#include "vauth/ntlm.h"
+#include "curl_ntlm_core.h"
#include "curl_ntlm_wb.h"
#include "url.h"
#include "strerror.h"
@@ -123,7 +124,6 @@ static CURLcode ntlm_wb_init(struct connectdata *conn, const char *userp)
struct passwd pw, *pw_res;
char pwbuf[1024];
#endif
- int error;
/* Return if communication with ntlm_auth already set up */
if(conn->ntlm_auth_hlpr_socket != CURL_SOCKET_BAD ||
@@ -178,26 +178,23 @@ static CURLcode ntlm_wb_init(struct connectdata *conn, const char *userp)
ntlm_auth = NTLM_WB_FILE;
if(access(ntlm_auth, X_OK) != 0) {
- error = ERRNO;
failf(conn->data, "Could not access ntlm_auth: %s errno %d: %s",
- ntlm_auth, error, Curl_strerror(conn, error));
+ ntlm_auth, errno, Curl_strerror(conn, errno));
goto done;
}
if(socketpair(AF_UNIX, SOCK_STREAM, 0, sockfds)) {
- error = ERRNO;
failf(conn->data, "Could not open socket pair. errno %d: %s",
- error, Curl_strerror(conn, error));
+ errno, Curl_strerror(conn, errno));
goto done;
}
child_pid = fork();
if(child_pid == -1) {
- error = ERRNO;
sclose(sockfds[0]);
sclose(sockfds[1]);
failf(conn->data, "Could not fork. errno %d: %s",
- error, Curl_strerror(conn, error));
+ errno, Curl_strerror(conn, errno));
goto done;
}
else if(!child_pid) {
@@ -208,16 +205,14 @@ static CURLcode ntlm_wb_init(struct connectdata *conn, const char *userp)
/* Don't use sclose in the child since it fools the socket leak detector */
sclose_nolog(sockfds[0]);
if(dup2(sockfds[1], STDIN_FILENO) == -1) {
- error = ERRNO;
failf(conn->data, "Could not redirect child stdin. errno %d: %s",
- error, Curl_strerror(conn, error));
+ errno, Curl_strerror(conn, errno));
exit(1);
}
if(dup2(sockfds[1], STDOUT_FILENO) == -1) {
- error = ERRNO;
failf(conn->data, "Could not redirect child stdout. errno %d: %s",
- error, Curl_strerror(conn, error));
+ errno, Curl_strerror(conn, errno));
exit(1);
}
@@ -235,10 +230,9 @@ static CURLcode ntlm_wb_init(struct connectdata *conn, const char *userp)
"--username", username,
NULL);
- error = ERRNO;
sclose_nolog(sockfds[1]);
failf(conn->data, "Could not execl(). errno %d: %s",
- error, Curl_strerror(conn, error));
+ errno, Curl_strerror(conn, errno));
exit(1);
}
@@ -364,7 +358,7 @@ CURLcode Curl_output_ntlm_wb(struct connectdata *conn,
/* not set means empty */
if(!userp)
- userp="";
+ userp = "";
switch(ntlm->state) {
case NTLMSTATE_TYPE1:
@@ -420,7 +414,7 @@ CURLcode Curl_output_ntlm_wb(struct connectdata *conn,
/* connection is already authenticated,
* don't send a header in future requests */
free(*allocuserpwd);
- *allocuserpwd=NULL;
+ *allocuserpwd = NULL;
authp->done = TRUE;
break;
}
diff --git a/Utilities/cmcurl/lib/curl_rtmp.c b/Utilities/cmcurl/lib/curl_rtmp.c
index 87a6caf9e..97430647b 100644
--- a/Utilities/cmcurl/lib/curl_rtmp.c
+++ b/Utilities/cmcurl/lib/curl_rtmp.c
@@ -74,6 +74,7 @@ const struct Curl_handler Curl_handler_rtmp = {
ZERO_NULL, /* perform_getsock */
rtmp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_RTMP, /* defport */
CURLPROTO_RTMP, /* protocol */
PROTOPT_NONE /* flags*/
@@ -94,6 +95,7 @@ const struct Curl_handler Curl_handler_rtmpt = {
ZERO_NULL, /* perform_getsock */
rtmp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_RTMPT, /* defport */
CURLPROTO_RTMPT, /* protocol */
PROTOPT_NONE /* flags*/
@@ -114,6 +116,7 @@ const struct Curl_handler Curl_handler_rtmpe = {
ZERO_NULL, /* perform_getsock */
rtmp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_RTMP, /* defport */
CURLPROTO_RTMPE, /* protocol */
PROTOPT_NONE /* flags*/
@@ -134,6 +137,7 @@ const struct Curl_handler Curl_handler_rtmpte = {
ZERO_NULL, /* perform_getsock */
rtmp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_RTMPT, /* defport */
CURLPROTO_RTMPTE, /* protocol */
PROTOPT_NONE /* flags*/
@@ -154,6 +158,7 @@ const struct Curl_handler Curl_handler_rtmps = {
ZERO_NULL, /* perform_getsock */
rtmp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_RTMPS, /* defport */
CURLPROTO_RTMPS, /* protocol */
PROTOPT_NONE /* flags*/
@@ -174,6 +179,7 @@ const struct Curl_handler Curl_handler_rtmpts = {
ZERO_NULL, /* perform_getsock */
rtmp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_RTMPS, /* defport */
CURLPROTO_RTMPTS, /* protocol */
PROTOPT_NONE /* flags*/
@@ -200,7 +206,7 @@ static CURLcode rtmp_connect(struct connectdata *conn, bool *done)
RTMP *r = conn->proto.generic;
SET_RCVTIMEO(tv, 10);
- r->m_sb.sb_socket = conn->sock[FIRSTSOCKET];
+ r->m_sb.sb_socket = (int)conn->sock[FIRSTSOCKET];
/* We have to know if it's a write before we send the
* connect request packet
diff --git a/Utilities/cmcurl/lib/curl_sasl.c b/Utilities/cmcurl/lib/curl_sasl.c
index bd574b5e2..550433d67 100644
--- a/Utilities/cmcurl/lib/curl_sasl.c
+++ b/Utilities/cmcurl/lib/curl_sasl.c
@@ -331,7 +331,8 @@ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn,
sasl->authused = SASL_MECH_NTLM;
if(force_ir || data->set.sasl_ir)
- result = Curl_auth_create_ntlm_type1_message(conn->user, conn->passwd,
+ result = Curl_auth_create_ntlm_type1_message(data,
+ conn->user, conn->passwd,
&conn->ntlm, &resp, &len);
}
else
@@ -493,7 +494,8 @@ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn,
#ifdef USE_NTLM
case SASL_NTLM:
/* Create the type-1 message */
- result = Curl_auth_create_ntlm_type1_message(conn->user, conn->passwd,
+ result = Curl_auth_create_ntlm_type1_message(data,
+ conn->user, conn->passwd,
&conn->ntlm, &resp, &len);
newstate = SASL_NTLM_TYPE2MSG;
break;
diff --git a/Utilities/cmcurl/lib/curl_setup.h b/Utilities/cmcurl/lib/curl_setup.h
index a6268adf2..5880dc0c4 100644
--- a/Utilities/cmcurl/lib/curl_setup.h
+++ b/Utilities/cmcurl/lib/curl_setup.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -22,6 +22,10 @@
*
***************************************************************************/
+#if defined(BUILDING_LIBCURL) && !defined(CURL_NO_OLDIES)
+#define CURL_NO_OLDIES
+#endif
+
/*
* Define WIN32 when build target is Win32 API
*/
@@ -31,6 +35,17 @@
#define WIN32
#endif
+#ifdef WIN32
+/*
+ * Don't include unneeded stuff in Windows headers to avoid compiler
+ * warnings and macro clashes.
+ * Make sure to define this macro before including any Windows headers.
+ */
+# ifndef WIN32_LEAN_AND_MEAN
+# define WIN32_LEAN_AND_MEAN
+# endif
+#endif
+
/*
* Include configuration script results or hand-crafted
* configuration file for platforms which lack config tool.
@@ -130,14 +145,7 @@
#include <curl/curl.h>
-/*
- * Ensure that no one is using the old SIZEOF_CURL_OFF_T macro
- */
-
-#ifdef SIZEOF_CURL_OFF_T
-# error "SIZEOF_CURL_OFF_T shall not be defined!"
- Error Compilation_aborted_SIZEOF_CURL_OFF_T_shall_not_be_defined
-#endif
+#define CURL_SIZEOF_CURL_OFF_T SIZEOF_CURL_OFF_T
/*
* Disable other protocols when http is the only one desired.
@@ -174,9 +182,6 @@
# ifndef CURL_DISABLE_SMTP
# define CURL_DISABLE_SMTP
# endif
-# ifndef CURL_DISABLE_RTMP
-# define CURL_DISABLE_RTMP
-# endif
# ifndef CURL_DISABLE_GOPHER
# define CURL_DISABLE_GOPHER
# endif
@@ -195,7 +200,7 @@
/* ================================================================ */
/* No system header file shall be included in this file before this */
-/* point. The only allowed ones are those included from curlbuild.h */
+/* point. The only allowed ones are those included from curl/system.h */
/* ================================================================ */
/*
@@ -241,9 +246,6 @@
# if defined(_UNICODE) && !defined(UNICODE)
# define UNICODE
# endif
-# ifndef WIN32_LEAN_AND_MEAN
-# define WIN32_LEAN_AND_MEAN
-# endif
# include <windows.h>
# ifdef HAVE_WINSOCK2_H
# include <winsock2.h>
@@ -655,9 +657,8 @@ int netware_init(void);
#endif
#endif
-/* non-configure builds may define CURL_WANTS_CA_BUNDLE_ENV */
-#if defined(CURL_WANTS_CA_BUNDLE_ENV) && !defined(CURL_CA_BUNDLE)
-#define CURL_CA_BUNDLE getenv("CURL_CA_BUNDLE")
+#ifdef CURL_WANTS_CA_BUNDLE_ENV
+#error "No longer supported. Set CURLOPT_CAINFO at runtime instead."
#endif
/*
@@ -731,6 +732,7 @@ Therefore we specify it explicitly. https://github.com/curl/curl/pull/258
#if defined(WIN32) || defined(MSDOS)
#define FOPEN_READTEXT "rt"
#define FOPEN_WRITETEXT "wt"
+#define FOPEN_APPENDTEXT "at"
#elif defined(__CYGWIN__)
/* Cygwin has specific behavior we need to address when WIN32 is not defined.
https://cygwin.com/cygwin-ug-net/using-textbinary.html
@@ -740,9 +742,11 @@ endings either CRLF or LF so 't' is appropriate.
*/
#define FOPEN_READTEXT "rt"
#define FOPEN_WRITETEXT "w"
+#define FOPEN_APPENDTEXT "a"
#else
#define FOPEN_READTEXT "r"
#define FOPEN_WRITETEXT "w"
+#define FOPEN_APPENDTEXT "a"
#endif
/* WinSock destroys recv() buffer when send() failed.
diff --git a/Utilities/cmcurl/lib/curl_setup_once.h b/Utilities/cmcurl/lib/curl_setup_once.h
index 684187cae..a5b542c6e 100644
--- a/Utilities/cmcurl/lib/curl_setup_once.h
+++ b/Utilities/cmcurl/lib/curl_setup_once.h
@@ -436,20 +436,6 @@ typedef int sig_atomic_t;
/*
- * Macro ERRNO / SET_ERRNO() returns / sets the NOT *socket-related* errno
- * (or equivalent) on this platform to hide platform details to code using it.
- */
-
-#if defined(WIN32) && !defined(USE_LWIPSOCK)
-#define ERRNO ((int)GetLastError())
-#define SET_ERRNO(x) (SetLastError((DWORD)(x)))
-#else
-#define ERRNO (errno)
-#define SET_ERRNO(x) (errno = (x))
-#endif
-
-
-/*
* Portable error number symbolic names defined to Winsock error codes.
*/
diff --git a/Utilities/cmcurl/lib/curl_threads.c b/Utilities/cmcurl/lib/curl_threads.c
index a78eff5c2..c1624a913 100644
--- a/Utilities/cmcurl/lib/curl_threads.c
+++ b/Utilities/cmcurl/lib/curl_threads.c
@@ -104,15 +104,22 @@ int Curl_thread_join(curl_thread_t *hnd)
curl_thread_t Curl_thread_create(unsigned int (CURL_STDCALL *func) (void *),
void *arg)
{
+ curl_thread_t t;
#ifdef _WIN32_WCE
- return CreateThread(NULL, 0, func, arg, 0, NULL);
+ t = CreateThread(NULL, 0, func, arg, 0, NULL);
#else
- curl_thread_t t;
t = (curl_thread_t)_beginthreadex(NULL, 0, func, arg, 0, NULL);
- if((t == 0) || (t == (curl_thread_t)-1L))
+#endif
+ if((t == 0) || (t == LongToHandle(-1L))) {
+#ifdef _WIN32_WCE
+ DWORD gle = GetLastError();
+ errno = ((gle == ERROR_ACCESS_DENIED ||
+ gle == ERROR_NOT_ENOUGH_MEMORY) ?
+ EACCES : EINVAL);
+#endif
return curl_thread_t_null;
+ }
return t;
-#endif
}
void Curl_thread_destroy(curl_thread_t hnd)
diff --git a/Utilities/cmcurl/lib/dict.c b/Utilities/cmcurl/lib/dict.c
index 451ec389a..4fc85521d 100644
--- a/Utilities/cmcurl/lib/dict.c
+++ b/Utilities/cmcurl/lib/dict.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -85,6 +85,7 @@ const struct Curl_handler Curl_handler_dict = {
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_DICT, /* defport */
CURLPROTO_DICT, /* protocol */
PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */
@@ -97,7 +98,7 @@ static char *unescape_word(struct Curl_easy *data, const char *inputbuff)
char *ptr;
size_t len;
char ch;
- int olen=0;
+ int olen = 0;
CURLcode result = Curl_urldecode(data, inputbuff, 0, &newp, &len, FALSE);
if(!newp || result)
@@ -116,7 +117,7 @@ static char *unescape_word(struct Curl_easy *data, const char *inputbuff)
}
dictp[olen++] = ch;
}
- dictp[olen]=0;
+ dictp[olen] = 0;
}
free(newp);
return dictp;
@@ -131,8 +132,8 @@ static CURLcode dict_do(struct connectdata *conn, bool *done)
char *strategy = NULL;
char *nthdef = NULL; /* This is not part of the protocol, but required
by RFC 2229 */
- CURLcode result=CURLE_OK;
- struct Curl_easy *data=conn->data;
+ CURLcode result = CURLE_OK;
+ struct Curl_easy *data = conn->data;
curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
char *path = data->state.path;
@@ -167,7 +168,7 @@ static CURLcode dict_do(struct connectdata *conn, bool *done)
if((word == NULL) || (*word == (char)0)) {
infof(data, "lookup word is missing\n");
- word=(char *)"default";
+ word = (char *)"default";
}
if((database == NULL) || (*database == (char)0)) {
database = (char *)"!";
@@ -221,7 +222,7 @@ static CURLcode dict_do(struct connectdata *conn, bool *done)
if((word == NULL) || (*word == (char)0)) {
infof(data, "lookup word is missing\n");
- word=(char *)"default";
+ word = (char *)"default";
}
if((database == NULL) || (*database == (char)0)) {
database = (char *)"!";
diff --git a/Utilities/cmcurl/lib/dotdot.c b/Utilities/cmcurl/lib/dotdot.c
index 20603bcab..cbb308d78 100644
--- a/Utilities/cmcurl/lib/dotdot.c
+++ b/Utilities/cmcurl/lib/dotdot.c
@@ -55,7 +55,7 @@ char *Curl_dedotdotify(const char *input)
size_t inlen = strlen(input);
char *clone;
size_t clen = inlen; /* the length of the cloned input */
- char *out = malloc(inlen+1);
+ char *out = malloc(inlen + 1);
char *outptr;
char *orgclone;
char *queryp;
@@ -92,25 +92,25 @@ char *Curl_dedotdotify(const char *input)
remove that prefix from the input buffer; otherwise, */
if(!strncmp("./", clone, 2)) {
- clone+=2;
- clen-=2;
+ clone += 2;
+ clen -= 2;
}
else if(!strncmp("../", clone, 3)) {
- clone+=3;
- clen-=3;
+ clone += 3;
+ clen -= 3;
}
/* B. if the input buffer begins with a prefix of "/./" or "/.", where
"." is a complete path segment, then replace that prefix with "/" in
the input buffer; otherwise, */
else if(!strncmp("/./", clone, 3)) {
- clone+=2;
- clen-=2;
+ clone += 2;
+ clen -= 2;
}
else if(!strcmp("/.", clone)) {
clone[1]='/';
clone++;
- clen-=1;
+ clen -= 1;
}
/* C. if the input buffer begins with a prefix of "/../" or "/..", where
@@ -119,8 +119,8 @@ char *Curl_dedotdotify(const char *input)
any) from the output buffer; otherwise, */
else if(!strncmp("/../", clone, 4)) {
- clone+=3;
- clen-=3;
+ clone += 3;
+ clen -= 3;
/* remove the last segment from the output buffer */
while(outptr > out) {
outptr--;
@@ -131,8 +131,8 @@ char *Curl_dedotdotify(const char *input)
}
else if(!strcmp("/..", clone)) {
clone[2]='/';
- clone+=2;
- clen-=2;
+ clone += 2;
+ clen -= 2;
/* remove the last segment from the output buffer */
while(outptr > out) {
outptr--;
@@ -146,8 +146,8 @@ char *Curl_dedotdotify(const char *input)
that from the input buffer; otherwise, */
else if(!strcmp(".", clone) || !strcmp("..", clone)) {
- *clone=0;
- *out=0;
+ *clone = 0;
+ *out = 0;
}
else {
@@ -172,7 +172,7 @@ char *Curl_dedotdotify(const char *input)
from the correct index. */
size_t oindex = queryp - orgclone;
qlen = strlen(&input[oindex]);
- memcpy(outptr, &input[oindex], qlen+1); /* include the ending zero byte */
+ memcpy(outptr, &input[oindex], qlen + 1); /* include the end zero byte */
}
free(orgclone);
diff --git a/Utilities/cmcurl/lib/easy.c b/Utilities/cmcurl/lib/easy.c
index 2b1ce9e8a..5328f9c2d 100644
--- a/Utilities/cmcurl/lib/easy.c
+++ b/Utilities/cmcurl/lib/easy.c
@@ -433,7 +433,7 @@ static int events_timer(struct Curl_multi *multi, /* multi handle */
*/
static int poll2cselect(int pollmask)
{
- int omask=0;
+ int omask = 0;
if(pollmask & POLLIN)
omask |= CURL_CSELECT_IN;
if(pollmask & POLLOUT)
@@ -450,7 +450,7 @@ static int poll2cselect(int pollmask)
*/
static short socketcb2poll(int pollmask)
{
- short omask=0;
+ short omask = 0;
if(pollmask & CURL_POLL_IN)
omask |= POLLIN;
if(pollmask & CURL_POLL_OUT)
@@ -473,7 +473,7 @@ static int events_socket(struct Curl_easy *easy, /* easy handle */
{
struct events *ev = userp;
struct socketmonitor *m;
- struct socketmonitor *prev=NULL;
+ struct socketmonitor *prev = NULL;
#if defined(CURL_DISABLE_VERBOSE_STRINGS)
(void) easy;
@@ -569,14 +569,14 @@ static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev)
struct socketmonitor *m;
struct pollfd *f;
struct pollfd fds[4];
- int numfds=0;
+ int numfds = 0;
int pollrc;
int i;
- struct timeval before;
- struct timeval after;
+ struct curltime before;
+ struct curltime after;
/* populate the fds[] array */
- for(m = ev->list, f=&fds[0]; m; m = m->next) {
+ for(m = ev->list, f = &fds[0]; m; m = m->next) {
f->fd = m->socket.fd;
f->events = m->socket.events;
f->revents = 0;
@@ -653,7 +653,9 @@ static CURLcode wait_or_timeout(struct Curl_multi *multi, struct events *ev)
*/
static CURLcode easy_events(struct Curl_multi *multi)
{
- struct events evs= {2, FALSE, 0, NULL, 0};
+ /* this struct is made static to allow it to be used after this function
+ returns and curl_multi_remove_handle() is called */
+ static struct events evs = {2, FALSE, 0, NULL, 0};
/* if running event-based, do some further multi inits */
events_setup(multi, &evs);
@@ -670,7 +672,7 @@ static CURLcode easy_transfer(struct Curl_multi *multi)
bool done = FALSE;
CURLMcode mcode = CURLM_OK;
CURLcode result = CURLE_OK;
- struct timeval before;
+ struct curltime before;
int without_fds = 0; /* count number of consecutive returns from
curl_multi_wait() without any filedescriptors */
@@ -683,7 +685,7 @@ static CURLcode easy_transfer(struct Curl_multi *multi)
if(!mcode) {
if(!rc) {
- struct timeval after = curlx_tvnow();
+ struct curltime after = curlx_tvnow();
/* If it returns without any filedescriptor instantly, we need to
avoid busy-looping during periods where it has nothing particular
@@ -1025,13 +1027,13 @@ CURLcode curl_easy_pause(struct Curl_easy *data, int action)
struct tempbuf writebuf[3]; /* there can only be three */
/* copy the structs to allow for immediate re-pausing */
- for(i=0; i < data->state.tempcount; i++) {
+ for(i = 0; i < data->state.tempcount; i++) {
writebuf[i] = data->state.tempwrite[i];
data->state.tempwrite[i].buf = NULL;
}
data->state.tempcount = 0;
- for(i=0; i < count; i++) {
+ for(i = 0; i < count; i++) {
/* even if one function returns error, this loops through and frees all
buffers */
if(!result)
diff --git a/Utilities/cmcurl/lib/escape.c b/Utilities/cmcurl/lib/escape.c
index 973aeb6ea..b7e2d32a6 100644
--- a/Utilities/cmcurl/lib/escape.c
+++ b/Utilities/cmcurl/lib/escape.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -84,14 +84,14 @@ char *curl_easy_escape(struct Curl_easy *data, const char *string,
char *testing_ptr = NULL;
unsigned char in; /* we need to treat the characters unsigned */
size_t newlen;
- size_t strindex=0;
+ size_t strindex = 0;
size_t length;
CURLcode result;
if(inlength < 0)
return NULL;
- alloc = (inlength?(size_t)inlength:strlen(string))+1;
+ alloc = (inlength?(size_t)inlength:strlen(string)) + 1;
newlen = alloc;
ns = malloc(alloc);
@@ -104,7 +104,7 @@ char *curl_easy_escape(struct Curl_easy *data, const char *string,
if(Curl_isunreserved(in))
/* just copy this */
- ns[strindex++]=in;
+ ns[strindex++] = in;
else {
/* encode it */
newlen += 2; /* the size grows with two, since this'll become a %XX */
@@ -116,7 +116,7 @@ char *curl_easy_escape(struct Curl_easy *data, const char *string,
ns = testing_ptr;
}
- result = Curl_convert_to_network(data, &in, 1);
+ result = Curl_convert_to_network(data, (char *)&in, 1);
if(result) {
/* Curl_convert_to_network calls failf if unsuccessful */
free(ns);
@@ -125,11 +125,11 @@ char *curl_easy_escape(struct Curl_easy *data, const char *string,
snprintf(&ns[strindex], 4, "%%%02X", in);
- strindex+=3;
+ strindex += 3;
}
string++;
}
- ns[strindex]=0; /* terminate it */
+ ns[strindex] = 0; /* terminate it */
return ns;
}
@@ -148,10 +148,10 @@ CURLcode Curl_urldecode(struct Curl_easy *data,
char **ostring, size_t *olen,
bool reject_ctrl)
{
- size_t alloc = (length?length:strlen(string))+1;
+ size_t alloc = (length?length:strlen(string)) + 1;
char *ns = malloc(alloc);
unsigned char in;
- size_t strindex=0;
+ size_t strindex = 0;
unsigned long hex;
CURLcode result;
@@ -173,15 +173,15 @@ CURLcode Curl_urldecode(struct Curl_easy *data,
in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */
- result = Curl_convert_from_network(data, &in, 1);
+ result = Curl_convert_from_network(data, (char *)&in, 1);
if(result) {
/* Curl_convert_from_network calls failf if unsuccessful */
free(ns);
return result;
}
- string+=2;
- alloc-=2;
+ string += 2;
+ alloc -= 2;
}
if(reject_ctrl && (in < 0x20)) {
@@ -192,7 +192,7 @@ CURLcode Curl_urldecode(struct Curl_easy *data,
ns[strindex++] = in;
string++;
}
- ns[strindex]=0; /* terminate it */
+ ns[strindex] = 0; /* terminate it */
if(olen)
/* store output size */
diff --git a/Utilities/cmcurl/lib/file.c b/Utilities/cmcurl/lib/file.c
index c804d75e1..7cfdab19f 100644
--- a/Utilities/cmcurl/lib/file.c
+++ b/Utilities/cmcurl/lib/file.c
@@ -108,6 +108,7 @@ const struct Curl_handler Curl_handler_file = {
ZERO_NULL, /* perform_getsock */
file_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
0, /* defport */
CURLPROTO_FILE, /* protocol */
PROTOPT_NONETWORK | PROTOPT_NOURLQUERY /* flags */
@@ -132,37 +133,42 @@ static CURLcode file_setup_connection(struct connectdata *conn)
static CURLcode file_range(struct connectdata *conn)
{
curl_off_t from, to;
- curl_off_t totalsize=-1;
+ curl_off_t totalsize = -1;
char *ptr;
char *ptr2;
struct Curl_easy *data = conn->data;
if(data->state.use_range && data->state.range) {
- from=curlx_strtoofft(data->state.range, &ptr, 0);
- while(*ptr && (ISSPACE(*ptr) || (*ptr=='-')))
+ CURLofft from_t;
+ CURLofft to_t;
+ from_t = curlx_strtoofft(data->state.range, &ptr, 0, &from);
+ if(from_t == CURL_OFFT_FLOW)
+ return CURLE_RANGE_ERROR;
+ while(*ptr && (ISSPACE(*ptr) || (*ptr == '-')))
ptr++;
- to=curlx_strtoofft(ptr, &ptr2, 0);
- if(ptr == ptr2) {
- /* we didn't get any digit */
- to=-1;
- }
- if((-1 == to) && (from>=0)) {
+ to_t = curlx_strtoofft(ptr, &ptr2, 0, &to);
+ if(to_t == CURL_OFFT_FLOW)
+ return CURLE_RANGE_ERROR;
+ if((to_t == CURL_OFFT_INVAL) && !from_t) {
/* X - */
data->state.resume_from = from;
DEBUGF(infof(data, "RANGE %" CURL_FORMAT_CURL_OFF_T " to end of file\n",
from));
}
- else if(from < 0) {
+ else if((from_t == CURL_OFFT_INVAL) && !to_t) {
/* -Y */
- data->req.maxdownload = -from;
- data->state.resume_from = from;
+ data->req.maxdownload = to;
+ data->state.resume_from = -to;
DEBUGF(infof(data, "RANGE the last %" CURL_FORMAT_CURL_OFF_T " bytes\n",
- -from));
+ to));
}
else {
/* X-Y */
totalsize = to-from;
- data->req.maxdownload = totalsize+1; /* include last byte */
+ if(totalsize == CURL_OFF_T_MAX)
+ /* this is too big to increase, so bail out */
+ return CURLE_RANGE_ERROR;
+ data->req.maxdownload = totalsize + 1; /* include last byte */
data->state.resume_from = from;
DEBUGF(infof(data, "RANGE from %" CURL_FORMAT_CURL_OFF_T
" getting %" CURL_FORMAT_CURL_OFF_T " bytes\n",
@@ -225,7 +231,7 @@ static CURLcode file_connect(struct connectdata *conn, bool *done)
}
/* change path separators from '/' to '\\' for DOS, Windows and OS/2 */
- for(i=0; i < real_path_len; ++i)
+ for(i = 0; i < real_path_len; ++i)
if(actual_path[i] == '/')
actual_path[i] = '\\';
else if(!actual_path[i]) { /* binary zero */
@@ -427,9 +433,9 @@ static CURLcode file_do(struct connectdata *conn, bool *done)
struct_stat statbuf; /* struct_stat instead of struct stat just to allow the
Windows version to have a different struct without
having to redefine the simple word 'stat' */
- curl_off_t expected_size=0;
+ curl_off_t expected_size = 0;
bool size_known;
- bool fstated=FALSE;
+ bool fstated = FALSE;
ssize_t nread;
struct Curl_easy *data = conn->data;
char *buf = data->state.buffer;
@@ -500,7 +506,7 @@ static CURLcode file_do(struct connectdata *conn, bool *done)
tm->tm_hour,
tm->tm_min,
tm->tm_sec);
- result = Curl_client_write(conn, CLIENTWRITE_BOTH, buf, 0);
+ result = Curl_client_write(conn, CLIENTWRITE_BOTH, header, 0);
if(!result)
/* set the file size to make it available post transfer */
Curl_pgrsSetDownloadSize(data, expected_size);
diff --git a/Utilities/cmcurl/lib/formdata.c b/Utilities/cmcurl/lib/formdata.c
index e48a6276c..3568ac579 100644
--- a/Utilities/cmcurl/lib/formdata.c
+++ b/Utilities/cmcurl/lib/formdata.c
@@ -32,6 +32,8 @@
#include "urldata.h" /* for struct Curl_easy */
#include "formdata.h"
+#include "mime.h"
+#include "non-ascii.h"
#include "vtls/vtls.h"
#include "strcase.h"
#include "sendf.h"
@@ -42,13 +44,6 @@
#include "curl_memory.h"
#include "memdebug.h"
-#ifndef HAVE_BASENAME
-static char *Curl_basename(char *path);
-#define basename(x) Curl_basename((x))
-#endif
-
-static size_t readfromfile(struct Form *form, char *buffer, size_t size);
-static CURLcode formboundary(struct Curl_easy *data, char *buffer, size_t len);
/* What kind of Content-Type to use on un-specified files with unrecognized
extensions. */
@@ -197,7 +192,7 @@ static const char *ContentTypeForFilename(const char *filename,
contenttype = HTTPPOST_CONTENTTYPE_DEFAULT;
if(filename) { /* in case a NULL was passed in */
- for(i=0; i<sizeof(ctts)/sizeof(ctts[0]); i++) {
+ for(i = 0; i<sizeof(ctts)/sizeof(ctts[0]); i++) {
if(strlen(filename) >= strlen(ctts[i].extension)) {
if(strcasecompare(filename +
strlen(filename) - strlen(ctts[i].extension),
@@ -272,7 +267,7 @@ CURLFORMcode FormAdd(struct curl_httppost **httppost,
struct curl_httppost *post = NULL;
CURLformoption option;
struct curl_forms *forms = NULL;
- char *array_value=NULL; /* value read from an array */
+ char *array_value = NULL; /* value read from an array */
/* This is a state variable, that if TRUE means that we're parsing an
array that we got passed to us. If FALSE we're parsing the input
@@ -641,15 +636,26 @@ CURLFORMcode FormAdd(struct curl_httppost **httppost,
}
form->contenttype_alloc = TRUE;
}
+ if(form->name && form->namelength) {
+ /* Name should not contain nul bytes. */
+ size_t i;
+ for(i = 0; i < form->namelength; i++)
+ if(!form->name[i]) {
+ return_value = CURL_FORMADD_NULL;
+ break;
+ }
+ if(return_value != CURL_FORMADD_OK)
+ break;
+ }
if(!(form->flags & HTTPPOST_PTRNAME) &&
(form == first_form) ) {
/* Note that there's small risk that form->name is NULL here if the
app passed in a bad combo, so we better check for that first. */
if(form->name) {
- /* copy name (without strdup; possibly contains null characters) */
+ /* copy name (without strdup; possibly not nul-terminated) */
form->name = Curl_memdup(form->name, form->namelength?
form->namelength:
- strlen(form->name)+1);
+ strlen(form->name) + 1);
}
if(!form->name) {
return_value = CURL_FORMADD_MEMORY;
@@ -663,7 +669,7 @@ CURLFORMcode FormAdd(struct curl_httppost **httppost,
/* copy value (without strdup; possibly contains null characters) */
size_t clen = (size_t) form->contentslength;
if(!clen)
- clen = strlen(form->value)+1;
+ clen = strlen(form->value) + 1;
form->value = Curl_memdup(form->value, clen);
@@ -746,211 +752,6 @@ CURLFORMcode curl_formadd(struct curl_httppost **httppost,
return result;
}
-#ifdef __VMS
-#include <fabdef.h>
-/*
- * get_vms_file_size does what it takes to get the real size of the file
- *
- * For fixed files, find out the size of the EOF block and adjust.
- *
- * For all others, have to read the entire file in, discarding the contents.
- * Most posted text files will be small, and binary files like zlib archives
- * and CD/DVD images should be either a STREAM_LF format or a fixed format.
- *
- */
-curl_off_t VmsRealFileSize(const char *name,
- const struct_stat *stat_buf)
-{
- char buffer[8192];
- curl_off_t count;
- int ret_stat;
- FILE * file;
-
- file = fopen(name, FOPEN_READTEXT); /* VMS */
- if(file == NULL)
- return 0;
-
- count = 0;
- ret_stat = 1;
- while(ret_stat > 0) {
- ret_stat = fread(buffer, 1, sizeof(buffer), file);
- if(ret_stat != 0)
- count += ret_stat;
- }
- fclose(file);
-
- return count;
-}
-
-/*
- *
- * VmsSpecialSize checks to see if the stat st_size can be trusted and
- * if not to call a routine to get the correct size.
- *
- */
-static curl_off_t VmsSpecialSize(const char *name,
- const struct_stat *stat_buf)
-{
- switch(stat_buf->st_fab_rfm) {
- case FAB$C_VAR:
- case FAB$C_VFC:
- return VmsRealFileSize(name, stat_buf);
- break;
- default:
- return stat_buf->st_size;
- }
-}
-
-#endif
-
-#ifndef __VMS
-#define filesize(name, stat_data) (stat_data.st_size)
-#else
- /* Getting the expected file size needs help on VMS */
-#define filesize(name, stat_data) VmsSpecialSize(name, &stat_data)
-#endif
-
-/*
- * AddFormData() adds a chunk of data to the FormData linked list.
- *
- * size is incremented by the chunk length, unless it is NULL
- */
-static CURLcode AddFormData(struct FormData **formp,
- enum formtype type,
- const void *line,
- curl_off_t length,
- curl_off_t *size)
-{
- struct FormData *newform;
- char *alloc2 = NULL;
- CURLcode result = CURLE_OK;
- if(length < 0 || (size && *size < 0))
- return CURLE_BAD_FUNCTION_ARGUMENT;
-
- newform = malloc(sizeof(struct FormData));
- if(!newform)
- return CURLE_OUT_OF_MEMORY;
- newform->next = NULL;
-
- if(type <= FORM_CONTENT) {
- /* we make it easier for plain strings: */
- if(!length)
- length = strlen((char *)line);
-#if (SIZEOF_SIZE_T < CURL_SIZEOF_CURL_OFF_T)
- else if(length >= (curl_off_t)(size_t)-1) {
- result = CURLE_BAD_FUNCTION_ARGUMENT;
- goto error;
- }
-#endif
- if(type != FORM_DATAMEM) {
- newform->line = malloc((size_t)length+1);
- if(!newform->line) {
- result = CURLE_OUT_OF_MEMORY;
- goto error;
- }
- alloc2 = newform->line;
- memcpy(newform->line, line, (size_t)length);
-
- /* zero terminate for easier debugging */
- newform->line[(size_t)length]=0;
- }
- else {
- newform->line = (char *)line;
- type = FORM_DATA; /* in all other aspects this is just FORM_DATA */
- }
- newform->length = (size_t)length;
- }
- else
- /* For callbacks and files we don't have any actual data so we just keep a
- pointer to whatever this points to */
- newform->line = (char *)line;
-
- newform->type = type;
-
- if(size) {
- if(type != FORM_FILE)
- /* for static content as well as callback data we add the size given
- as input argument */
- *size += length;
- else {
- /* Since this is a file to be uploaded here, add the size of the actual
- file */
- if(strcmp("-", newform->line)) {
- struct_stat file;
- if(!stat(newform->line, &file) && !S_ISDIR(file.st_mode))
- *size += filesize(newform->line, file);
- else {
- result = CURLE_BAD_FUNCTION_ARGUMENT;
- goto error;
- }
- }
- }
- }
-
- if(*formp) {
- (*formp)->next = newform;
- *formp = newform;
- }
- else
- *formp = newform;
-
- return CURLE_OK;
- error:
- if(newform)
- free(newform);
- if(alloc2)
- free(alloc2);
- return result;
-}
-
-/*
- * AddFormDataf() adds printf()-style formatted data to the formdata chain.
- */
-
-static CURLcode AddFormDataf(struct FormData **formp,
- curl_off_t *size,
- const char *fmt, ...)
-{
- char *s;
- CURLcode result;
- va_list ap;
- va_start(ap, fmt);
- s = curl_mvaprintf(fmt, ap);
- va_end(ap);
-
- if(!s)
- return CURLE_OUT_OF_MEMORY;
-
- result = AddFormData(formp, FORM_DATAMEM, s, 0, size);
- if(result)
- free(s);
-
- return result;
-}
-
-/*
- * Curl_formclean() is used from http.c, this cleans a built FormData linked
- * list
- */
-void Curl_formclean(struct FormData **form_ptr)
-{
- struct FormData *next, *form;
-
- form = *form_ptr;
- if(!form)
- return;
-
- do {
- next=form->next; /* the following form line */
- if(form->type <= FORM_CONTENT)
- free(form->line); /* free the line */
- free(form); /* free the struct */
- form = next;
- } while(form); /* continue */
-
- *form_ptr = NULL;
-}
-
/*
* curl_formget()
* Serialize a curl_httppost struct.
@@ -962,42 +763,34 @@ int curl_formget(struct curl_httppost *form, void *arg,
curl_formget_callback append)
{
CURLcode result;
- curl_off_t size;
- struct FormData *data, *ptr;
+ curl_mimepart toppart;
- result = Curl_getformdata(NULL, &data, form, NULL, &size);
- if(result)
- return (int)result;
-
- for(ptr = data; ptr; ptr = ptr->next) {
- if((ptr->type == FORM_FILE) || (ptr->type == FORM_CALLBACK)) {
- char buffer[8192];
- size_t nread;
- struct Form temp;
-
- Curl_FormInit(&temp, ptr);
-
- do {
- nread = readfromfile(&temp, buffer, sizeof(buffer));
- if((nread == (size_t) -1) ||
- (nread > sizeof(buffer)) ||
- (nread != append(arg, buffer, nread))) {
- if(temp.fp)
- fclose(temp.fp);
- Curl_formclean(&data);
- return -1;
- }
- } while(nread);
- }
- else {
- if(ptr->length != append(arg, ptr->line, ptr->length)) {
- Curl_formclean(&data);
- return -1;
- }
+ Curl_mime_initpart(&toppart, NULL); /* default form is empty */
+ result = Curl_getformdata(NULL, &toppart, form, NULL);
+ if(!result)
+ result = Curl_mime_prepare_headers(&toppart, "multipart/form-data",
+ NULL, MIMESTRATEGY_FORM);
+
+ while(!result) {
+ char buffer[8192];
+ size_t nread = Curl_mime_read(buffer, 1, sizeof buffer, &toppart);
+
+ if(!nread)
+ break;
+
+ switch(nread) {
+ default:
+ if(append(arg, buffer, nread) != nread)
+ result = CURLE_READ_ERROR;
+ break;
+ case CURL_READFUNC_ABORT:
+ case CURL_READFUNC_PAUSE:
+ break;
}
}
- Curl_formclean(&data);
- return 0;
+
+ Curl_mime_cleanpart(&toppart);
+ return (int) result;
}
/*
@@ -1013,7 +806,7 @@ void curl_formfree(struct curl_httppost *form)
return;
do {
- next=form->next; /* the following form line */
+ next = form->next; /* the following form line */
/* recurse to sub-contents */
curl_formfree(form->more);
@@ -1031,118 +824,29 @@ void curl_formfree(struct curl_httppost *form)
} while(form); /* continue */
}
-#ifndef HAVE_BASENAME
-/*
- (Quote from The Open Group Base Specifications Issue 6 IEEE Std 1003.1, 2004
- Edition)
-
- The basename() function shall take the pathname pointed to by path and
- return a pointer to the final component of the pathname, deleting any
- trailing '/' characters.
-
- If the string pointed to by path consists entirely of the '/' character,
- basename() shall return a pointer to the string "/". If the string pointed
- to by path is exactly "//", it is implementation-defined whether '/' or "//"
- is returned.
- If path is a null pointer or points to an empty string, basename() shall
- return a pointer to the string ".".
-
- The basename() function may modify the string pointed to by path, and may
- return a pointer to static storage that may then be overwritten by a
- subsequent call to basename().
-
- The basename() function need not be reentrant. A function that is not
- required to be reentrant is not required to be thread-safe.
-
-*/
-static char *Curl_basename(char *path)
+/* Set mime part name, taking care of non nul-terminated name string. */
+static CURLcode setname(curl_mimepart *part, const char *name, size_t len)
{
- /* Ignore all the details above for now and make a quick and simple
- implementaion here */
- char *s1;
- char *s2;
-
- s1=strrchr(path, '/');
- s2=strrchr(path, '\\');
+ char *zname;
+ CURLcode res;
- if(s1 && s2) {
- path = (s1 > s2? s1 : s2)+1;
- }
- else if(s1)
- path = s1 + 1;
- else if(s2)
- path = s2 + 1;
-
- return path;
-}
-#endif
-
-static char *strippath(const char *fullfile)
-{
- char *filename;
- char *base;
- filename = strdup(fullfile); /* duplicate since basename() may ruin the
- buffer it works on */
- if(!filename)
- return NULL;
- base = strdup(basename(filename));
-
- free(filename); /* free temporary buffer */
-
- return base; /* returns an allocated string or NULL ! */
-}
-
-static CURLcode formdata_add_filename(const struct curl_httppost *file,
- struct FormData **form,
- curl_off_t *size)
-{
- CURLcode result = CURLE_OK;
- char *filename = file->showfilename;
- char *filebasename = NULL;
- char *filename_escaped = NULL;
-
- if(!filename) {
- filebasename = strippath(file->contents);
- if(!filebasename)
- return CURLE_OUT_OF_MEMORY;
- filename = filebasename;
- }
-
- if(strchr(filename, '\\') || strchr(filename, '"')) {
- char *p0, *p1;
-
- /* filename need be escaped */
- filename_escaped = malloc(strlen(filename)*2+1);
- if(!filename_escaped) {
- free(filebasename);
- return CURLE_OUT_OF_MEMORY;
- }
- p0 = filename_escaped;
- p1 = filename;
- while(*p1) {
- if(*p1 == '\\' || *p1 == '"')
- *p0++ = '\\';
- *p0++ = *p1++;
- }
- *p0 = '\0';
- filename = filename_escaped;
- }
- result = AddFormDataf(form, size,
- "; filename=\"%s\"",
- filename);
- free(filename_escaped);
- free(filebasename);
- return result;
+ if(!name || !len)
+ return curl_mime_name(part, name);
+ zname = malloc(len + 1);
+ if(!zname)
+ return CURLE_OUT_OF_MEMORY;
+ memcpy(zname, name, len);
+ zname[len] = '\0';
+ res = curl_mime_name(part, zname);
+ free(zname);
+ return res;
}
/*
- * Curl_getformdata() converts a linked list of "meta data" into a complete
- * (possibly huge) multipart formdata. The input list is in 'post', while the
- * output resulting linked lists gets stored in '*finalform'. *sizep will get
- * the total size of the whole POST.
- * A multipart/form_data content-type is built, unless a custom content-type
- * is passed in 'custom_content_type'.
+ * Curl_getformdata() converts a linked list of "meta data" into a mime
+ * structure. The input list is in 'post', while the output is stored in
+ * mime part at '*finalform'.
*
* This function will not do a failf() for the potential memory failures but
* should for all other errors it spots. Just note that this function MAY get
@@ -1150,422 +854,123 @@ static CURLcode formdata_add_filename(const struct curl_httppost *file,
*/
CURLcode Curl_getformdata(struct Curl_easy *data,
- struct FormData **finalform,
+ curl_mimepart *finalform,
struct curl_httppost *post,
- const char *custom_content_type,
- curl_off_t *sizep)
+ curl_read_callback fread_func)
{
- struct FormData *form = NULL;
- struct FormData *firstform;
- struct curl_httppost *file;
CURLcode result = CURLE_OK;
- curl_off_t size = 0; /* support potentially ENORMOUS formposts */
- char fileboundary[42];
- struct curl_slist *curList;
- char boundary[42];
+ curl_mime *form = NULL;
+ curl_mime *multipart;
+ curl_mimepart *part;
+ struct curl_httppost *file;
- *finalform = NULL; /* default form is empty */
+ Curl_mime_cleanpart(finalform); /* default form is empty */
if(!post)
return result; /* no input => no output! */
- result = formboundary(data, boundary, sizeof(boundary));
- if(result)
- return result;
-
- /* Make the first line of the output */
- result = AddFormDataf(&form, NULL,
- "%s; boundary=%s\r\n",
- custom_content_type?custom_content_type:
- "Content-Type: multipart/form-data",
- boundary);
-
- if(result) {
- return result;
- }
- /* we DO NOT include that line in the total size of the POST, since it'll be
- part of the header! */
-
- firstform = form;
-
- do {
-
- if(size) {
- result = AddFormDataf(&form, &size, "\r\n");
- if(result)
- break;
- }
-
- /* boundary */
- result = AddFormDataf(&form, &size, "--%s\r\n", boundary);
- if(result)
- break;
-
- /* Maybe later this should be disabled when a custom_content_type is
- passed, since Content-Disposition is not meaningful for all multipart
- types.
- */
- result = AddFormDataf(&form, &size,
- "Content-Disposition: form-data; name=\"");
- if(result)
- break;
-
- result = AddFormData(&form, FORM_DATA, post->name, post->namelength,
- &size);
- if(result)
- break;
+ form = curl_mime_init(data);
+ if(!form)
+ result = CURLE_OUT_OF_MEMORY;
- result = AddFormDataf(&form, &size, "\"");
- if(result)
- break;
+ if(!result)
+ result = curl_mime_subparts(finalform, form);
+ /* Process each top part. */
+ for(; !result && post; post = post->next) {
+ /* If we have more than a file here, create a mime subpart and fill it. */
+ multipart = form;
if(post->more) {
- /* If used, this is a link to more file names, we must then do
- the magic to include several files with the same field name */
-
- result = formboundary(data, fileboundary, sizeof(fileboundary));
- if(result) {
- break;
+ part = curl_mime_addpart(form);
+ if(!part)
+ result = CURLE_OUT_OF_MEMORY;
+ if(!result)
+ result = setname(part, post->name, post->namelength);
+ if(!result) {
+ multipart = curl_mime_init(data);
+ if(!multipart)
+ result = CURLE_OUT_OF_MEMORY;
}
-
- result = AddFormDataf(&form, &size,
- "\r\nContent-Type: multipart/mixed;"
- " boundary=%s\r\n",
- fileboundary);
- if(result)
- break;
+ if(!result)
+ result = curl_mime_subparts(part, multipart);
}
- file = post;
-
- do {
-
- /* If 'showfilename' is set, that is a faked name passed on to us
- to use to in the formpost. If that is not set, the actually used
- local file name should be added. */
-
- if(post->more) {
- /* if multiple-file */
- result = AddFormDataf(&form, &size,
- "\r\n--%s\r\nContent-Disposition: "
- "attachment",
- fileboundary);
- if(result)
- break;
- result = formdata_add_filename(file, &form, &size);
- if(result)
- break;
- }
- else if(post->flags & (HTTPPOST_FILENAME|HTTPPOST_BUFFER|
- HTTPPOST_CALLBACK)) {
- /* it should be noted that for the HTTPPOST_FILENAME and
- HTTPPOST_CALLBACK cases the ->showfilename struct member is always
- assigned at this point */
- if(post->showfilename || (post->flags & HTTPPOST_FILENAME)) {
- result = formdata_add_filename(post, &form, &size);
- }
+ /* Generate all the part contents. */
+ for(file = post; !result && file; file = file->more) {
+ /* Create the part. */
+ part = curl_mime_addpart(multipart);
+ if(!part)
+ result = CURLE_OUT_OF_MEMORY;
- if(result)
- break;
- }
+ /* Set the headers. */
+ if(!result)
+ result = curl_mime_headers(part, file->contentheader, 0);
- if(file->contenttype) {
- /* we have a specified type */
- result = AddFormDataf(&form, &size,
- "\r\nContent-Type: %s",
- file->contenttype);
- if(result)
- break;
- }
+ /* Set the content type. */
+ if(!result &&file->contenttype)
+ result = curl_mime_type(part, file->contenttype);
- curList = file->contentheader;
- while(curList) {
- /* Process the additional headers specified for this form */
- result = AddFormDataf(&form, &size, "\r\n%s", curList->data);
- if(result)
- break;
- curList = curList->next;
- }
- if(result)
- break;
+ /* Set field name. */
+ if(!result && !post->more)
+ result = setname(part, post->name, post->namelength);
- result = AddFormDataf(&form, &size, "\r\n\r\n");
- if(result)
- break;
+ /* Process contents. */
+ if(!result) {
+ curl_off_t clen = post->contentslength;
- if((post->flags & HTTPPOST_FILENAME) ||
- (post->flags & HTTPPOST_READFILE)) {
- /* we should include the contents from the specified file */
- FILE *fileread;
-
- fileread = !strcmp("-", file->contents)?
- stdin:fopen(file->contents, "rb"); /* binary read for win32 */
-
- /*
- * VMS: This only allows for stream files on VMS. Stream files are
- * OK, as are FIXED & VAR files WITHOUT implied CC For implied CC,
- * every record needs to have a \n appended & 1 added to SIZE
- */
-
- if(fileread) {
- if(fileread != stdin) {
- /* close the file */
- fclose(fileread);
- /* add the file name only - for later reading from this */
- result = AddFormData(&form, FORM_FILE, file->contents, 0, &size);
- }
- else {
- /* When uploading from stdin, we can't know the size of the file,
- * thus must read the full file as before. We *could* use chunked
- * transfer-encoding, but that only works for HTTP 1.1 and we
- * can't be sure we work with such a server.
- */
- size_t nread;
- char buffer[512];
- while((nread = fread(buffer, 1, sizeof(buffer), fileread)) != 0) {
- result = AddFormData(&form, FORM_CONTENT, buffer, nread, &size);
- if(result || feof(fileread) || ferror(fileread))
- break;
- }
+ if(post->flags & CURL_HTTPPOST_LARGE)
+ clen = post->contentlen;
+ if(!clen)
+ clen = -1;
+
+ if(post->flags & (HTTPPOST_FILENAME | HTTPPOST_READFILE)) {
+ if(!strcmp(file->contents, "-")) {
+ /* There are a few cases where the code below won't work; in
+ particular, freopen(stdin) by the caller is not guaranteed
+ to result as expected. This feature has been kept for backward
+ compatibility: use of "-" pseudo file name should be avoided. */
+ result = curl_mime_data_cb(part, (curl_off_t) -1,
+ (curl_read_callback) fread,
+ (curl_seek_callback) fseek,
+ NULL, (void *) stdin);
}
+ else
+ result = curl_mime_filedata(part, file->contents);
+ if(!result && (post->flags & HTTPPOST_READFILE))
+ result = curl_mime_filename(part, NULL);
}
+ else if(post->flags & HTTPPOST_BUFFER)
+ result = curl_mime_data(part, post->buffer,
+ post->bufferlength? post->bufferlength: -1);
+ else if(post->flags & HTTPPOST_CALLBACK)
+ /* the contents should be read with the callback and the size is set
+ with the contentslength */
+ result = curl_mime_data_cb(part, clen,
+ fread_func, NULL, NULL, post->userp);
else {
- if(data)
- failf(data, "couldn't open file \"%s\"", file->contents);
- *finalform = NULL;
- result = CURLE_READ_ERROR;
+ result = curl_mime_data(part, post->contents, (ssize_t) clen);
+#ifdef CURL_DOES_CONVERSIONS
+ /* Convert textual contents now. */
+ if(!result && data && part->datasize)
+ result = Curl_convert_to_network(data, part->data, part->datasize);
+#endif
}
}
- else if(post->flags & HTTPPOST_BUFFER)
- /* include contents of buffer */
- result = AddFormData(&form, FORM_CONTENT, post->buffer,
- post->bufferlength, &size);
- else if(post->flags & HTTPPOST_CALLBACK)
- /* the contents should be read with the callback and the size is set
- with the contentslength */
- result = AddFormData(&form, FORM_CALLBACK, post->userp,
- post->flags&CURL_HTTPPOST_LARGE?
- post->contentlen:post->contentslength, &size);
- else
- /* include the contents we got */
- result = AddFormData(&form, FORM_CONTENT, post->contents,
- post->flags&CURL_HTTPPOST_LARGE?
- post->contentlen:post->contentslength, &size);
- file = file->more;
- } while(file && !result); /* for each specified file for this field */
-
- if(result)
- break;
- if(post->more) {
- /* this was a multiple-file inclusion, make a termination file
- boundary: */
- result = AddFormDataf(&form, &size,
- "\r\n--%s--",
- fileboundary);
- if(result)
- break;
+ /* Set fake file name. */
+ if(!result && post->showfilename)
+ if(post->more || (post->flags & (HTTPPOST_FILENAME | HTTPPOST_BUFFER |
+ HTTPPOST_CALLBACK)))
+ result = curl_mime_filename(part, post->showfilename);
}
- post = post->next;
- } while(post); /* for each field */
-
- /* end-boundary for everything */
- if(!result)
- result = AddFormDataf(&form, &size, "\r\n--%s--\r\n", boundary);
-
- if(result) {
- Curl_formclean(&firstform);
- return result;
}
- *sizep = size;
- *finalform = firstform;
+ if(result)
+ Curl_mime_cleanpart(finalform);
return result;
}
-/*
- * Curl_FormInit() inits the struct 'form' points to with the 'formdata'
- * and resets the 'sent' counter.
- */
-int Curl_FormInit(struct Form *form, struct FormData *formdata)
-{
- if(!formdata)
- return 1; /* error */
-
- form->data = formdata;
- form->sent = 0;
- form->fp = NULL;
- form->fread_func = ZERO_NULL;
-
- return 0;
-}
-
-#ifndef __VMS
-# define fopen_read fopen
-#else
- /*
- * vmsfopenread
- *
- * For upload to work as expected on VMS, different optional
- * parameters must be added to the fopen command based on
- * record format of the file.
- *
- */
-# define fopen_read vmsfopenread
-static FILE * vmsfopenread(const char *file, const char *mode)
-{
- struct_stat statbuf;
- int result;
-
- result = stat(file, &statbuf);
-
- switch(statbuf.st_fab_rfm) {
- case FAB$C_VAR:
- case FAB$C_VFC:
- case FAB$C_STMCR:
- return fopen(file, FOPEN_READTEXT); /* VMS */
- break;
- default:
- return fopen(file, FOPEN_READTEXT, "rfm=stmlf", "ctx=stm");
- }
-}
-#endif
-
-/*
- * readfromfile()
- *
- * The read callback that this function may use can return a value larger than
- * 'size' (which then this function returns) that indicates a problem and it
- * must be properly dealt with
- */
-static size_t readfromfile(struct Form *form, char *buffer,
- size_t size)
-{
- size_t nread;
- bool callback = (form->data->type == FORM_CALLBACK)?TRUE:FALSE;
-
- if(callback) {
- if(form->fread_func == ZERO_NULL)
- return 0;
- nread = form->fread_func(buffer, 1, size, form->data->line);
- }
- else {
- if(!form->fp) {
- /* this file hasn't yet been opened */
- form->fp = fopen_read(form->data->line, "rb"); /* b is for binary */
- if(!form->fp)
- return (size_t)-1; /* failure */
- }
- nread = fread(buffer, 1, size, form->fp);
- }
- if(!nread) {
- /* this is the last chunk from the file, move on */
- if(form->fp) {
- fclose(form->fp);
- form->fp = NULL;
- }
- form->data = form->data->next;
- }
-
- return nread;
-}
-
-/*
- * Curl_FormReader() is the fread() emulation function that will be used to
- * deliver the formdata to the transfer loop and then sent away to the peer.
- */
-size_t Curl_FormReader(char *buffer,
- size_t size,
- size_t nitems,
- FILE *mydata)
-{
- struct Form *form;
- size_t wantedsize;
- size_t gotsize = 0;
-
- form=(struct Form *)mydata;
-
- wantedsize = size * nitems;
-
- if(!form->data)
- return 0; /* nothing, error, empty */
-
- if((form->data->type == FORM_FILE) ||
- (form->data->type == FORM_CALLBACK)) {
- gotsize = readfromfile(form, buffer, wantedsize);
-
- if(gotsize)
- /* If positive or -1, return. If zero, continue! */
- return gotsize;
- }
- do {
-
- if((form->data->length - form->sent) > wantedsize - gotsize) {
-
- memcpy(buffer + gotsize, form->data->line + form->sent,
- wantedsize - gotsize);
-
- form->sent += wantedsize-gotsize;
-
- return wantedsize;
- }
-
- memcpy(buffer+gotsize,
- form->data->line + form->sent,
- (form->data->length - form->sent) );
- gotsize += form->data->length - form->sent;
-
- form->sent = 0;
-
- form->data = form->data->next; /* advance */
-
- } while(form->data && (form->data->type < FORM_CALLBACK));
- /* If we got an empty line and we have more data, we proceed to the next
- line immediately to avoid returning zero before we've reached the end. */
-
- return gotsize;
-}
-
-/*
- * Curl_formpostheader() returns the first line of the formpost, the
- * request-header part (which is not part of the request-body like the rest of
- * the post).
- */
-char *Curl_formpostheader(void *formp, size_t *len)
-{
- char *header;
- struct Form *form=(struct Form *)formp;
-
- if(!form->data)
- return NULL; /* nothing, ERROR! */
-
- header = form->data->line;
- *len = form->data->length;
-
- form->data = form->data->next; /* advance */
-
- return header;
-}
-
-/*
- * formboundary() creates a suitable boundary string and returns an allocated
- * one.
- */
-static CURLcode formboundary(struct Curl_easy *data,
- char *buffer, size_t buflen)
-{
- /* 24 dashes and 16 hexadecimal digits makes 64 bit (18446744073709551615)
- combinations */
- if(buflen < 41)
- return CURLE_BAD_FUNCTION_ARGUMENT;
-
- memset(buffer, '-', 24);
- Curl_rand_hex(data, (unsigned char *)&buffer[24], 17);
-
- return CURLE_OK;
-}
-
#else /* CURL_DISABLE_HTTP */
CURLFORMcode curl_formadd(struct curl_httppost **httppost,
struct curl_httppost **last_post,
diff --git a/Utilities/cmcurl/lib/formdata.h b/Utilities/cmcurl/lib/formdata.h
index 69629f628..1246c2bc8 100644
--- a/Utilities/cmcurl/lib/formdata.h
+++ b/Utilities/cmcurl/lib/formdata.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -22,32 +22,6 @@
*
***************************************************************************/
-enum formtype {
- FORM_DATAMEM, /* already allocated FORM_DATA memory */
- FORM_DATA, /* form metadata (convert to network encoding if necessary) */
- FORM_CONTENT, /* form content (never convert) */
- FORM_CALLBACK, /* 'line' points to the custom pointer we pass to the callback
- */
- FORM_FILE /* 'line' points to a file name we should read from
- to create the form data (never convert) */
-};
-
-/* plain and simple linked list with lines to send */
-struct FormData {
- struct FormData *next;
- enum formtype type;
- char *line;
- size_t length;
-};
-
-struct Form {
- struct FormData *data; /* current form line to send */
- size_t sent; /* number of bytes of the current line that has
- already been sent in a previous invoke */
- FILE *fp; /* file to read from */
- curl_read_callback fread_func; /* fread callback pointer */
-};
-
/* used by FormAdd for temporary storage */
typedef struct FormInfo {
char *name;
@@ -69,31 +43,9 @@ typedef struct FormInfo {
struct FormInfo *more;
} FormInfo;
-int Curl_FormInit(struct Form *form, struct FormData *formdata);
-
CURLcode Curl_getformdata(struct Curl_easy *data,
- struct FormData **,
+ curl_mimepart *,
struct curl_httppost *post,
- const char *custom_contenttype,
- curl_off_t *size);
-
-/* fread() emulation */
-size_t Curl_FormReader(char *buffer,
- size_t size,
- size_t nitems,
- FILE *mydata);
-
-/*
- * Curl_formpostheader() returns the first line of the formpost, the
- * request-header part (which is not part of the request-body like the rest of
- * the post).
- */
-char *Curl_formpostheader(void *formp, size_t *len);
-
-char *Curl_FormBoundary(void);
-
-void Curl_formclean(struct FormData **);
-
-CURLcode Curl_formconvert(struct Curl_easy *, struct FormData *);
+ curl_read_callback fread_func);
#endif /* HEADER_CURL_FORMDATA_H */
diff --git a/Utilities/cmcurl/lib/ftp.c b/Utilities/cmcurl/lib/ftp.c
index 783dbe124..84ae37b2f 100644
--- a/Utilities/cmcurl/lib/ftp.c
+++ b/Utilities/cmcurl/lib/ftp.c
@@ -178,10 +178,11 @@ const struct Curl_handler Curl_handler_ftp = {
ZERO_NULL, /* perform_getsock */
ftp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_FTP, /* defport */
CURLPROTO_FTP, /* protocol */
- PROTOPT_DUAL | PROTOPT_CLOSEACTION | PROTOPT_NEEDSPWD
- | PROTOPT_NOURLQUERY /* flags */
+ PROTOPT_DUAL | PROTOPT_CLOSEACTION | PROTOPT_NEEDSPWD |
+ PROTOPT_NOURLQUERY | PROTOPT_PROXY_AS_HTTP /* flags */
};
@@ -205,6 +206,7 @@ const struct Curl_handler Curl_handler_ftps = {
ZERO_NULL, /* perform_getsock */
ftp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_FTPS, /* defport */
CURLPROTO_FTPS, /* protocol */
PROTOPT_SSL | PROTOPT_DUAL | PROTOPT_CLOSEACTION |
@@ -212,59 +214,6 @@ const struct Curl_handler Curl_handler_ftps = {
};
#endif
-#ifndef CURL_DISABLE_HTTP
-/*
- * HTTP-proxyed FTP protocol handler.
- */
-
-static const struct Curl_handler Curl_handler_ftp_proxy = {
- "FTP", /* scheme */
- Curl_http_setup_conn, /* setup_connection */
- Curl_http, /* do_it */
- Curl_http_done, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
- PORT_FTP, /* defport */
- CURLPROTO_HTTP, /* protocol */
- PROTOPT_NONE /* flags */
-};
-
-
-#ifdef USE_SSL
-/*
- * HTTP-proxyed FTPS protocol handler.
- */
-
-static const struct Curl_handler Curl_handler_ftps_proxy = {
- "FTPS", /* scheme */
- Curl_http_setup_conn, /* setup_connection */
- Curl_http, /* do_it */
- Curl_http_done, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
- PORT_FTPS, /* defport */
- CURLPROTO_HTTP, /* protocol */
- PROTOPT_NONE /* flags */
-};
-#endif
-#endif
-
static void close_secondarysocket(struct connectdata *conn)
{
if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET]) {
@@ -272,7 +221,6 @@ static void close_secondarysocket(struct connectdata *conn)
conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD;
}
conn->bits.tcpconnect[SECONDARYSOCKET] = FALSE;
- conn->tunnel_state[SECONDARYSOCKET] = TUNNEL_INIT;
}
/*
@@ -291,9 +239,9 @@ static void freedirs(struct ftp_conn *ftpc)
{
int i;
if(ftpc->dirs) {
- for(i=0; i < ftpc->dirdepth; i++) {
+ for(i = 0; i < ftpc->dirdepth; i++) {
free(ftpc->dirs[i]);
- ftpc->dirs[i]=NULL;
+ ftpc->dirs[i] = NULL;
}
free(ftpc->dirs);
ftpc->dirs = NULL;
@@ -340,7 +288,7 @@ static CURLcode AcceptServerConnect(struct connectdata *conn)
if(0 == getsockname(sock, (struct sockaddr *) &add, &size)) {
size = sizeof(add);
- s=accept(sock, (struct sockaddr *) &add, &size);
+ s = accept(sock, (struct sockaddr *) &add, &size);
}
Curl_closesocket(conn, sock); /* close the first socket */
@@ -388,7 +336,7 @@ static time_t ftp_timeleft_accept(struct Curl_easy *data)
{
time_t timeout_ms = DEFAULT_ACCEPT_TIMEOUT;
time_t other;
- struct timeval now;
+ struct curltime now;
if(data->set.accepttimeout > 0)
timeout_ms = data->set.accepttimeout;
@@ -509,7 +457,7 @@ static CURLcode InitiateTransfer(struct connectdata *conn)
}
if(conn->proto.ftpc.state_saved == FTP_STOR) {
- *(ftp->bytecountp)=0;
+ *(ftp->bytecountp) = 0;
/* When we know we're uploading a specified file, we can get the file
size prior to the actual upload. */
@@ -644,7 +592,7 @@ static CURLcode ftp_readresp(curl_socket_t sockfd,
#endif
/* store the latest code for later retrieval */
- data->info.httpcode=code;
+ data->info.httpcode = code;
if(ftpcode)
*ftpcode = code;
@@ -692,8 +640,8 @@ CURLcode Curl_GetFTPResponse(ssize_t *nreadp, /* return number of bytes read */
struct ftp_conn *ftpc = &conn->proto.ftpc;
struct pingpong *pp = &ftpc->pp;
size_t nread;
- int cache_skip=0;
- int value_to_be_ignored=0;
+ int cache_skip = 0;
+ int value_to_be_ignored = 0;
if(ftpcode)
*ftpcode = 0; /* 0 for errors */
@@ -701,13 +649,13 @@ CURLcode Curl_GetFTPResponse(ssize_t *nreadp, /* return number of bytes read */
/* make the pointer point to something for the rest of this function */
ftpcode = &value_to_be_ignored;
- *nreadp=0;
+ *nreadp = 0;
while(!*ftpcode && !result) {
/* check and reset timeout value every lap */
timeout = Curl_pp_state_timeout(pp);
- if(timeout <=0) {
+ if(timeout <= 0) {
failf(data, "FTP response timeout");
return CURLE_OPERATION_TIMEDOUT; /* already too little time */
}
@@ -765,7 +713,7 @@ CURLcode Curl_GetFTPResponse(ssize_t *nreadp, /* return number of bytes read */
else
/* when we got data or there is no cache left, we reset the cache skip
counter */
- cache_skip=0;
+ cache_skip = 0;
*nreadp += nread;
@@ -900,7 +848,7 @@ static int ftp_domore_getsock(struct connectdata *conn, curl_socket_t *socks,
int i;
/* PORT is used to tell the server to connect to us, and during that we
don't do happy eyeballs, but we do if we connect to the server */
- for(s=1, i=0; i<2; i++) {
+ for(s = 1, i = 0; i<2; i++) {
if(conn->tempsock[i] != CURL_SOCKET_BAD) {
socks[s] = conn->tempsock[i];
bits |= GETSOCK_WRITESOCK(s++);
@@ -937,23 +885,26 @@ static CURLcode ftp_state_cwd(struct connectdata *conn)
/* count3 is set to allow a MKD to fail once. In the case when first CWD
fails and then MKD fails (due to another session raced it to create the
dir) this then allows for a second try to CWD to it */
- ftpc->count3 = (conn->data->set.ftp_create_missing_dirs==2)?1:0;
+ ftpc->count3 = (conn->data->set.ftp_create_missing_dirs == 2)?1:0;
- if(conn->bits.reuse && ftpc->entrypath) {
+ if((conn->data->set.ftp_filemethod == FTPFILE_NOCWD) && !ftpc->cwdcount)
+ /* No CWD necessary */
+ result = ftp_state_mdtm(conn);
+ else if(conn->bits.reuse && ftpc->entrypath) {
/* This is a re-used connection. Since we change directory to where the
transfer is taking place, we must first get back to the original dir
where we ended up after login: */
- ftpc->count1 = 0; /* we count this as the first path, then we add one
- for all upcoming ones in the ftp->dirs[] array */
+ ftpc->cwdcount = 0; /* we count this as the first path, then we add one
+ for all upcoming ones in the ftp->dirs[] array */
PPSENDF(&conn->proto.ftpc.pp, "CWD %s", ftpc->entrypath);
state(conn, FTP_CWD);
}
else {
if(ftpc->dirdepth) {
- ftpc->count1 = 1;
+ ftpc->cwdcount = 1;
/* issue the first CWD, the rest is sent when the CWD responses are
received... */
- PPSENDF(&conn->proto.ftpc.pp, "CWD %s", ftpc->dirs[ftpc->count1 -1]);
+ PPSENDF(&conn->proto.ftpc.pp, "CWD %s", ftpc->dirs[ftpc->cwdcount -1]);
state(conn, FTP_CWD);
}
else {
@@ -977,15 +928,15 @@ static CURLcode ftp_state_use_port(struct connectdata *conn,
{
CURLcode result = CURLE_OK;
struct ftp_conn *ftpc = &conn->proto.ftpc;
- struct Curl_easy *data=conn->data;
- curl_socket_t portsock= CURL_SOCKET_BAD;
+ struct Curl_easy *data = conn->data;
+ curl_socket_t portsock = CURL_SOCKET_BAD;
char myhost[256] = "";
struct Curl_sockaddr_storage ss;
Curl_addrinfo *res, *ai;
curl_socklen_t sslen;
char hbuf[NI_MAXHOST];
- struct sockaddr *sa=(struct sockaddr *)&ss;
+ struct sockaddr *sa = (struct sockaddr *)&ss;
struct sockaddr_in * const sa4 = (void *)sa;
#ifdef ENABLE_IPV6
struct sockaddr_in6 * const sa6 = (void *)sa;
@@ -996,7 +947,7 @@ static CURLcode ftp_state_use_port(struct connectdata *conn,
int error;
char *host = NULL;
char *string_ftpport = data->set.str[STRING_FTPPORT];
- struct Curl_dns_entry *h=NULL;
+ struct Curl_dns_entry *h = NULL;
unsigned short port_min = 0;
unsigned short port_max = 0;
unsigned short port;
@@ -1024,7 +975,7 @@ static CURLcode ftp_state_use_port(struct connectdata *conn,
char *port_start = NULL;
char *port_sep = NULL;
- addr = calloc(addrlen+1, 1);
+ addr = calloc(addrlen + 1, 1);
if(!addr)
return CURLE_OUT_OF_MEMORY;
@@ -1067,7 +1018,7 @@ static CURLcode ftp_state_use_port(struct connectdata *conn,
if(ip_end != NULL) {
port_start = strchr(ip_end, ':');
if(port_start) {
- port_min = curlx_ultous(strtoul(port_start+1, NULL, 10));
+ port_min = curlx_ultous(strtoul(port_start + 1, NULL, 10));
port_sep = strchr(port_start, '-');
if(port_sep) {
port_max = curlx_ultous(strtoul(port_sep + 1, NULL, 10));
@@ -1311,7 +1262,7 @@ static CURLcode ftp_state_use_port(struct connectdata *conn,
/* translate x.x.x.x to x,x,x,x */
while(source && *source) {
if(*source == '.')
- *dest=',';
+ *dest = ',';
else
*dest = *source;
dest++;
@@ -1518,12 +1469,12 @@ static CURLcode ftp_state_list(struct connectdata *conn)
return CURLE_OUT_OF_MEMORY;
/* Check if path does not end with /, as then we cut off the file part */
- if(lstArg[strlen(lstArg) - 1] != '/') {
+ if(lstArg[strlen(lstArg) - 1] != '/') {
/* chop off the file part if format is dir/dir/file */
slashPos = strrchr(lstArg, '/');
if(slashPos)
- *(slashPos+1) = '\0';
+ *(slashPos + 1) = '\0';
}
}
@@ -1671,7 +1622,7 @@ static CURLcode ftp_state_ul_setup(struct connectdata *conn,
}
if(seekerr != CURL_SEEKFUNC_OK) {
- curl_off_t passed=0;
+ curl_off_t passed = 0;
if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
failf(data, "Could not seek stream");
return CURLE_FTP_COULDNT_USE_REST;
@@ -1733,7 +1684,7 @@ static CURLcode ftp_state_quote(struct connectdata *conn,
struct Curl_easy *data = conn->data;
struct FTP *ftp = data->req.protop;
struct ftp_conn *ftpc = &conn->proto.ftpc;
- bool quote=FALSE;
+ bool quote = FALSE;
struct curl_slist *item;
switch(instate) {
@@ -1870,11 +1821,11 @@ static CURLcode ftp_state_pasv_resp(struct connectdata *conn,
{
struct ftp_conn *ftpc = &conn->proto.ftpc;
CURLcode result;
- struct Curl_easy *data=conn->data;
- struct Curl_dns_entry *addr=NULL;
+ struct Curl_easy *data = conn->data;
+ struct Curl_dns_entry *addr = NULL;
int rc;
unsigned short connectport; /* the local port connect() should use! */
- char *str=&data->state.buffer[4]; /* start on the first letter */
+ char *str = &data->state.buffer[4]; /* start on the first letter */
/* if we come here again, make sure the former name is cleared */
Curl_safefree(ftpc->newhost);
@@ -1898,9 +1849,9 @@ static CURLcode ftp_state_pasv_resp(struct connectdata *conn,
/* The four separators should be identical, or else this is an oddly
formatted reply and we bail out immediately. */
- for(i=1; i<4; i++) {
+ for(i = 1; i<4; i++) {
if(separator[i] != sep1) {
- ptr=NULL; /* set to NULL to signal error */
+ ptr = NULL; /* set to NULL to signal error */
break;
}
}
@@ -1916,7 +1867,7 @@ static CURLcode ftp_state_pasv_resp(struct connectdata *conn,
}
}
else
- ptr=NULL;
+ ptr = NULL;
}
if(!ptr) {
failf(data, "Weirdly formatted EPSV reply");
@@ -2090,7 +2041,7 @@ static CURLcode ftp_state_mdtm_resp(struct connectdata *conn,
int ftpcode)
{
CURLcode result = CURLE_OK;
- struct Curl_easy *data=conn->data;
+ struct Curl_easy *data = conn->data;
struct FTP *ftp = data->req.protop;
struct ftp_conn *ftpc = &conn->proto.ftpc;
@@ -2104,7 +2055,7 @@ static CURLcode ftp_state_mdtm_resp(struct connectdata *conn,
&year, &month, &day, &hour, &minute, &second)) {
/* we have a time, reformat it */
char timebuf[24];
- time_t secs=time(NULL);
+ time_t secs = time(NULL);
snprintf(timebuf, sizeof(timebuf),
"%04d%02d%02d %02d:%02d:%02d GMT",
@@ -2120,7 +2071,7 @@ static CURLcode ftp_state_mdtm_resp(struct connectdata *conn,
if(data->set.opt_no_body &&
ftpc->file &&
data->set.get_filetime &&
- (data->info.filetime>=0) ) {
+ (data->info.filetime >= 0) ) {
char headerbuf[128];
time_t filetime = (time_t)data->info.filetime;
struct tm buffer;
@@ -2196,7 +2147,7 @@ static CURLcode ftp_state_type_resp(struct connectdata *conn,
ftpstate instate)
{
CURLcode result = CURLE_OK;
- struct Curl_easy *data=conn->data;
+ struct Curl_easy *data = conn->data;
if(ftpcode/100 != 2) {
/* "sasserftpd" and "(u)r(x)bot ftpd" both responds with 226 after a
@@ -2225,7 +2176,7 @@ static CURLcode ftp_state_retr(struct connectdata *conn,
curl_off_t filesize)
{
CURLcode result = CURLE_OK;
- struct Curl_easy *data=conn->data;
+ struct Curl_easy *data = conn->data;
struct FTP *ftp = data->req.protop;
struct ftp_conn *ftpc = &conn->proto.ftpc;
@@ -2308,12 +2259,14 @@ static CURLcode ftp_state_size_resp(struct connectdata *conn,
ftpstate instate)
{
CURLcode result = CURLE_OK;
- struct Curl_easy *data=conn->data;
- curl_off_t filesize;
+ struct Curl_easy *data = conn->data;
+ curl_off_t filesize = -1;
char *buf = data->state.buffer;
/* get the size from the ascii string: */
- filesize = (ftpcode == 213)?curlx_strtoofft(buf+4, NULL, 0):-1;
+ if(ftpcode == 213)
+ /* ignores parsing errors, which will make the size remain unknown */
+ (void)curlx_strtoofft(buf + 4, NULL, 0, &filesize);
if(instate == FTP_SIZE) {
#ifdef CURL_FTP_HTTPSTYLE_HEAD
@@ -2383,7 +2336,7 @@ static CURLcode ftp_state_stor_resp(struct connectdata *conn,
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
- if(ftpcode>=400) {
+ if(ftpcode >= 400) {
failf(data, "Failed FTP upload: %0d", ftpcode);
state(conn, FTP_STOP);
/* oops, we never close the sockets! */
@@ -2441,7 +2394,7 @@ static CURLcode ftp_state_get_resp(struct connectdata *conn,
E:
125 Data connection already open; Transfer starting. */
- curl_off_t size=-1; /* default unknown size */
+ curl_off_t size = -1; /* default unknown size */
/*
@@ -2465,9 +2418,9 @@ static CURLcode ftp_state_get_resp(struct connectdata *conn,
* Example D above makes this parsing a little tricky */
char *bytes;
char *buf = data->state.buffer;
- bytes=strstr(buf, " bytes");
+ bytes = strstr(buf, " bytes");
if(bytes--) {
- long in=(long)(bytes-buf);
+ long in = (long)(bytes-buf);
/* this is a hint there is size information in there! ;-) */
while(--in) {
/* scan for the left parenthesis and break there */
@@ -2475,7 +2428,7 @@ static CURLcode ftp_state_get_resp(struct connectdata *conn,
break;
/* skip only digits */
if(!ISDIGIT(*bytes)) {
- bytes=NULL;
+ bytes = NULL;
break;
}
/* one more estep backwards */
@@ -2484,7 +2437,7 @@ static CURLcode ftp_state_get_resp(struct connectdata *conn,
/* if we have nothing but digits: */
if(bytes++) {
/* get the number! */
- size = curlx_strtoofft(bytes, NULL, 0);
+ (void)curlx_strtoofft(bytes, NULL, 0, &size);
}
}
}
@@ -2647,7 +2600,7 @@ static CURLcode ftp_statemach_act(struct connectdata *conn)
{
CURLcode result;
curl_socket_t sock = conn->sock[FIRSTSOCKET];
- struct Curl_easy *data=conn->data;
+ struct Curl_easy *data = conn->data;
int ftpcode;
struct ftp_conn *ftpc = &conn->proto.ftpc;
struct pingpong *pp = &ftpc->pp;
@@ -2699,7 +2652,7 @@ static CURLcode ftp_statemach_act(struct connectdata *conn)
/* We don't have a SSL/TLS connection yet, but FTPS is
requested. Try a FTPS connection now */
- ftpc->count3=0;
+ ftpc->count3 = 0;
switch(data->set.ftpsslauth) {
case CURLFTPAUTH_DEFAULT:
case CURLFTPAUTH_SSL:
@@ -2822,10 +2775,11 @@ static CURLcode ftp_statemach_act(struct connectdata *conn)
case FTP_PWD:
if(ftpcode == 257) {
- char *ptr=&data->state.buffer[4]; /* start on the first letter */
+ char *ptr = &data->state.buffer[4]; /* start on the first letter */
const size_t buf_size = data->set.buffer_size;
char *dir;
char *store;
+ bool entry_extracted = FALSE;
dir = malloc(nread + 1);
if(!dir)
@@ -2857,7 +2811,7 @@ static CURLcode ftp_statemach_act(struct connectdata *conn)
}
else {
/* end of path */
- *store = '\0'; /* zero terminate */
+ entry_extracted = TRUE;
break; /* get out of this loop */
}
}
@@ -2866,7 +2820,9 @@ static CURLcode ftp_statemach_act(struct connectdata *conn)
store++;
ptr++;
}
-
+ *store = '\0'; /* zero terminate */
+ }
+ if(entry_extracted) {
/* If the path name does not look like an absolute path (i.e.: it
does not start with a '/'), we probably need some server-dependent
adjustments. For example, this is the case when connecting to
@@ -2913,7 +2869,7 @@ static CURLcode ftp_statemach_act(struct connectdata *conn)
case FTP_SYST:
if(ftpcode == 215) {
- char *ptr=&data->state.buffer[4]; /* start on the first letter */
+ char *ptr = &data->state.buffer[4]; /* start on the first letter */
char *os;
char *store;
@@ -2988,10 +2944,10 @@ static CURLcode ftp_statemach_act(struct connectdata *conn)
if(ftpcode/100 != 2) {
/* failure to CWD there */
if(conn->data->set.ftp_create_missing_dirs &&
- ftpc->count1 && !ftpc->count2) {
+ ftpc->cwdcount && !ftpc->count2) {
/* try making it */
ftpc->count2++; /* counter to prevent CWD-MKD loops */
- PPSENDF(&ftpc->pp, "MKD %s", ftpc->dirs[ftpc->count1 - 1]);
+ PPSENDF(&ftpc->pp, "MKD %s", ftpc->dirs[ftpc->cwdcount - 1]);
state(conn, FTP_MKD);
}
else {
@@ -3004,10 +2960,10 @@ static CURLcode ftp_statemach_act(struct connectdata *conn)
}
else {
/* success */
- ftpc->count2=0;
- if(++ftpc->count1 <= ftpc->dirdepth) {
+ ftpc->count2 = 0;
+ if(++ftpc->cwdcount <= ftpc->dirdepth) {
/* send next CWD */
- PPSENDF(&ftpc->pp, "CWD %s", ftpc->dirs[ftpc->count1 - 1]);
+ PPSENDF(&ftpc->pp, "CWD %s", ftpc->dirs[ftpc->cwdcount - 1]);
}
else {
result = ftp_state_mdtm(conn);
@@ -3025,7 +2981,7 @@ static CURLcode ftp_statemach_act(struct connectdata *conn)
}
state(conn, FTP_CWD);
/* send CWD */
- PPSENDF(&ftpc->pp, "CWD %s", ftpc->dirs[ftpc->count1 - 1]);
+ PPSENDF(&ftpc->pp, "CWD %s", ftpc->dirs[ftpc->cwdcount - 1]);
break;
case FTP_MDTM:
@@ -3244,15 +3200,16 @@ static CURLcode ftp_done(struct connectdata *conn, CURLcode status,
size_t flen = ftpc->file?strlen(ftpc->file):0; /* file is "raw" already */
size_t dlen = strlen(path)-flen;
if(!ftpc->cwdfail) {
+ ftpc->prevmethod = data->set.ftp_filemethod;
if(dlen && (data->set.ftp_filemethod != FTPFILE_NOCWD)) {
ftpc->prevpath = path;
if(flen)
/* if 'path' is not the whole string */
- ftpc->prevpath[dlen]=0; /* terminate */
+ ftpc->prevpath[dlen] = 0; /* terminate */
}
else {
/* we never changed dir */
- ftpc->prevpath=strdup("");
+ ftpc->prevpath = strdup("");
free(path);
}
if(ftpc->prevpath)
@@ -3515,35 +3472,36 @@ static CURLcode ftp_range(struct connectdata *conn)
{
curl_off_t from, to;
char *ptr;
- char *ptr2;
struct Curl_easy *data = conn->data;
struct ftp_conn *ftpc = &conn->proto.ftpc;
if(data->state.use_range && data->state.range) {
- from=curlx_strtoofft(data->state.range, &ptr, 0);
- while(*ptr && (ISSPACE(*ptr) || (*ptr=='-')))
+ CURLofft from_t;
+ CURLofft to_t;
+ from_t = curlx_strtoofft(data->state.range, &ptr, 0, &from);
+ if(from_t == CURL_OFFT_FLOW)
+ return CURLE_RANGE_ERROR;
+ while(*ptr && (ISSPACE(*ptr) || (*ptr == '-')))
ptr++;
- to=curlx_strtoofft(ptr, &ptr2, 0);
- if(ptr == ptr2) {
- /* we didn't get any digit */
- to=-1;
- }
- if((-1 == to) && (from>=0)) {
+ to_t = curlx_strtoofft(ptr, NULL, 0, &to);
+ if(to_t == CURL_OFFT_FLOW)
+ return CURLE_RANGE_ERROR;
+ if((to_t == CURL_OFFT_INVAL) && !from_t) {
/* X - */
data->state.resume_from = from;
DEBUGF(infof(conn->data, "FTP RANGE %" CURL_FORMAT_CURL_OFF_T
" to end of file\n", from));
}
- else if(from < 0) {
+ else if(!to_t && (from_t == CURL_OFFT_INVAL)) {
/* -Y */
- data->req.maxdownload = -from;
- data->state.resume_from = from;
+ data->req.maxdownload = to;
+ data->state.resume_from = -to;
DEBUGF(infof(conn->data, "FTP RANGE the last %" CURL_FORMAT_CURL_OFF_T
- " bytes\n", -from));
+ " bytes\n", to));
}
else {
/* X-Y */
- data->req.maxdownload = (to-from)+1; /* include last byte */
+ data->req.maxdownload = (to - from) + 1; /* include last byte */
data->state.resume_from = from;
DEBUGF(infof(conn->data, "FTP RANGE from %" CURL_FORMAT_CURL_OFF_T
" getting %" CURL_FORMAT_CURL_OFF_T " bytes\n",
@@ -3574,7 +3532,7 @@ static CURLcode ftp_range(struct connectdata *conn)
static CURLcode ftp_do_more(struct connectdata *conn, int *completep)
{
- struct Curl_easy *data=conn->data;
+ struct Curl_easy *data = conn->data;
struct ftp_conn *ftpc = &conn->proto.ftpc;
CURLcode result = CURLE_OK;
bool connected = FALSE;
@@ -3585,7 +3543,7 @@ static CURLcode ftp_do_more(struct connectdata *conn, int *completep)
/* if the second connection isn't done yet, wait for it */
if(!conn->bits.tcpconnect[SECONDARYSOCKET]) {
- if(conn->tunnel_state[SECONDARYSOCKET] == TUNNEL_CONNECT) {
+ if(Curl_connect_ongoing(conn)) {
/* As we're in TUNNEL_CONNECT state now, we know the proxy name and port
aren't used so we blank their arguments. TODO: make this nicer */
result = Curl_proxyCONNECT(conn, SECONDARYSOCKET, NULL, 0);
@@ -3617,7 +3575,7 @@ static CURLcode ftp_do_more(struct connectdata *conn, int *completep)
return result;
if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
- conn->tunnel_state[SECONDARYSOCKET] != TUNNEL_COMPLETE)
+ Curl_connect_ongoing(conn))
return result;
@@ -3741,7 +3699,7 @@ CURLcode ftp_perform(struct connectdata *conn,
bool *dophase_done)
{
/* this is FTP and no proxy */
- CURLcode result=CURLE_OK;
+ CURLcode result = CURLE_OK;
DEBUGF(infof(conn->data, "DO phase starts\n"));
@@ -4035,7 +3993,7 @@ CURLcode Curl_ftpsend(struct connectdata *conn, const char *cmd)
#define SBUF_SIZE 1024
char s[SBUF_SIZE];
size_t write_len;
- char *sptr=s;
+ char *sptr = s;
CURLcode result = CURLE_OK;
#ifdef HAVE_GSSAPI
enum protection_level data_sec = conn->data_prot;
@@ -4046,9 +4004,8 @@ CURLcode Curl_ftpsend(struct connectdata *conn, const char *cmd)
return CURLE_BAD_FUNCTION_ARGUMENT;
strcpy(&s[write_len], "\r\n"); /* append a trailing CRLF */
- write_len +=2;
-
- bytes_written=0;
+ write_len += 2;
+ bytes_written = 0;
result = Curl_convert_to_network(conn->data, s, write_len);
/* Curl_convert_to_network calls failf if unsuccessful */
@@ -4126,7 +4083,7 @@ static CURLcode ftp_quit(struct connectdata *conn)
*/
static CURLcode ftp_disconnect(struct connectdata *conn, bool dead_connection)
{
- struct ftp_conn *ftpc= &conn->proto.ftpc;
+ struct ftp_conn *ftpc = &conn->proto.ftpc;
struct pingpong *pp = &ftpc->pp;
/* We cannot send quit unconditionally. If this connection is stale or
@@ -4222,7 +4179,7 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
ftpc->dirdepth = 0;
break;
}
- slash_pos=strrchr(cur_pos, '/');
+ slash_pos = strrchr(cur_pos, '/');
if(slash_pos || !*cur_pos) {
size_t dirlen = slash_pos-cur_pos;
CURLcode result;
@@ -4243,7 +4200,7 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
return result;
}
ftpc->dirdepth = 1; /* we consider it to be a single dir */
- filename = slash_pos ? slash_pos+1 : cur_pos; /* rest is file name */
+ filename = slash_pos ? slash_pos + 1 : cur_pos; /* rest is file name */
}
else
filename = cur_pos; /* this is a file name only */
@@ -4327,8 +4284,8 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
}
}
else
- ftpc->file=NULL; /* instead of point to a zero byte, we make it a NULL
- pointer */
+ ftpc->file = NULL; /* instead of point to a zero byte, we make it a NULL
+ pointer */
if(data->set.upload && !ftpc->file && (ftp->transfer == FTPTRANSFER_BODY)) {
/* We need a file name when uploading. Return error! */
@@ -4352,7 +4309,8 @@ CURLcode ftp_parse_url_path(struct connectdata *conn)
dlen -= ftpc->file?strlen(ftpc->file):0;
if((dlen == strlen(ftpc->prevpath)) &&
- !strncmp(path, ftpc->prevpath, dlen)) {
+ !strncmp(path, ftpc->prevpath, dlen) &&
+ (ftpc->prevmethod == data->set.ftp_filemethod)) {
infof(data, "Request has same path as previous transfer\n");
ftpc->cwddone = TRUE;
}
@@ -4423,8 +4381,8 @@ static
CURLcode ftp_regular_transfer(struct connectdata *conn,
bool *dophase_done)
{
- CURLcode result=CURLE_OK;
- bool connected=FALSE;
+ CURLcode result = CURLE_OK;
+ bool connected = FALSE;
struct Curl_easy *data = conn->data;
struct ftp_conn *ftpc = &conn->proto.ftpc;
data->req.size = -1; /* make sure this is unknown at this point */
@@ -4464,28 +4422,6 @@ static CURLcode ftp_setup_connection(struct connectdata *conn)
char command;
struct FTP *ftp;
- if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
- /* Unless we have asked to tunnel ftp operations through the proxy, we
- switch and use HTTP operations only */
-#ifndef CURL_DISABLE_HTTP
- if(conn->handler == &Curl_handler_ftp)
- conn->handler = &Curl_handler_ftp_proxy;
- else {
-#ifdef USE_SSL
- conn->handler = &Curl_handler_ftps_proxy;
-#else
- failf(data, "FTPS not supported!");
- return CURLE_UNSUPPORTED_PROTOCOL;
-#endif
- }
- /* set it up as a HTTP connection instead */
- return conn->handler->setup_connection(conn);
-#else
- failf(data, "FTP over http proxy requires HTTP support built-in!");
- return CURLE_UNSUPPORTED_PROTOCOL;
-#endif
- }
-
conn->data->req.protop = ftp = malloc(sizeof(struct FTP));
if(NULL == ftp)
return CURLE_OUT_OF_MEMORY;
diff --git a/Utilities/cmcurl/lib/ftp.h b/Utilities/cmcurl/lib/ftp.h
index 3bbf26206..e4aa63f17 100644
--- a/Utilities/cmcurl/lib/ftp.h
+++ b/Utilities/cmcurl/lib/ftp.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -130,10 +130,12 @@ struct ftp_conn {
should be FALSE when it gets to Curl_ftp_quit() */
bool cwddone; /* if it has been determined that the proper CWD combo
already has been done */
+ int cwdcount; /* number of CWD commands issued */
bool cwdfail; /* set TRUE if a CWD command fails, as then we must prevent
caching the current directory */
bool wait_data_conn; /* this is set TRUE if data connection is waited */
char *prevpath; /* conn->path from the previous transfer */
+ curl_ftpfile prevmethod; /* ftp method in previous transfer */
char transfertype; /* set by ftp_transfertype for use by Curl_client_write()a
and others (A/I or zero) */
int count1; /* general purpose counter for the state machine */
diff --git a/Utilities/cmcurl/lib/ftplistparser.c b/Utilities/cmcurl/lib/ftplistparser.c
index 2acce31d8..b2a8c0fdb 100644
--- a/Utilities/cmcurl/lib/ftplistparser.c
+++ b/Utilities/cmcurl/lib/ftplistparser.c
@@ -421,7 +421,7 @@ size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb,
else if(c == '\n') {
finfo->b_data[parser->item_length - 1] = 0;
if(strncmp("total ", finfo->b_data, 6) == 0) {
- char *endptr = finfo->b_data+6;
+ char *endptr = finfo->b_data + 6;
/* here we can deal with directory size, pass the leading white
spaces and then the digits */
while(ISSPACE(*endptr))
@@ -609,16 +609,18 @@ size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb,
char *p;
curl_off_t fsize;
finfo->b_data[parser->item_offset + parser->item_length - 1] = 0;
- fsize = curlx_strtoofft(finfo->b_data+parser->item_offset, &p, 10);
- if(p[0] == '\0' && fsize != CURL_OFF_T_MAX &&
- fsize != CURL_OFF_T_MIN) {
- parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_SIZE;
- parser->file_data->info.size = fsize;
+ if(!curlx_strtoofft(finfo->b_data + parser->item_offset,
+ &p, 10, &fsize)) {
+ if(p[0] == '\0' && fsize != CURL_OFF_T_MAX &&
+ fsize != CURL_OFF_T_MIN) {
+ parser->file_data->info.flags |= CURLFINFOFLAG_KNOWN_SIZE;
+ parser->file_data->info.size = fsize;
+ }
+ parser->item_length = 0;
+ parser->item_offset = 0;
+ parser->state.UNIX.main = PL_UNIX_TIME;
+ parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART1;
}
- parser->item_length = 0;
- parser->item_offset = 0;
- parser->state.UNIX.main = PL_UNIX_TIME;
- parser->state.UNIX.sub.time = PL_UNIX_TIME_PREPART1;
}
else if(!ISDIGIT(c)) {
PL_ERROR(conn, CURLE_FTP_BAD_FILE_LIST);
@@ -935,19 +937,9 @@ size_t Curl_ftp_parselist(char *buffer, size_t size, size_t nmemb,
}
else {
char *endptr;
- finfo->size = curlx_strtoofft(finfo->b_data +
- parser->item_offset,
- &endptr, 10);
- if(!*endptr) {
- if(finfo->size == CURL_OFF_T_MAX ||
- finfo->size == CURL_OFF_T_MIN) {
- if(errno == ERANGE) {
- PL_ERROR(conn, CURLE_FTP_BAD_FILE_LIST);
- return bufflen;
- }
- }
- }
- else {
+ if(curlx_strtoofft(finfo->b_data +
+ parser->item_offset,
+ &endptr, 10, &finfo->size)) {
PL_ERROR(conn, CURLE_FTP_BAD_FILE_LIST);
return bufflen;
}
diff --git a/Utilities/cmcurl/lib/getinfo.c b/Utilities/cmcurl/lib/getinfo.c
index a1ce5058e..862ced019 100644
--- a/Utilities/cmcurl/lib/getinfo.c
+++ b/Utilities/cmcurl/lib/getinfo.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -54,6 +54,7 @@ CURLcode Curl_initinfo(struct Curl_easy *data)
pro->t_starttransfer = 0;
pro->timespent = 0;
pro->t_redirect = 0;
+ pro->is_t_startransfer_set = false;
info->httpcode = 0;
info->httpproxycode = 0;
@@ -246,27 +247,60 @@ static CURLcode getinfo_long(struct Curl_easy *data, CURLINFO info,
return CURLE_OK;
}
+#define DOUBLE_SECS(x) (double)(x)/1000000
+
+static CURLcode getinfo_offt(struct Curl_easy *data, CURLINFO info,
+ curl_off_t *param_offt)
+{
+ switch(info) {
+ case CURLINFO_SIZE_UPLOAD_T:
+ *param_offt = data->progress.uploaded;
+ break;
+ case CURLINFO_SIZE_DOWNLOAD_T:
+ *param_offt = data->progress.downloaded;
+ break;
+ case CURLINFO_SPEED_DOWNLOAD_T:
+ *param_offt = data->progress.dlspeed;
+ break;
+ case CURLINFO_SPEED_UPLOAD_T:
+ *param_offt = data->progress.ulspeed;
+ break;
+ case CURLINFO_CONTENT_LENGTH_DOWNLOAD_T:
+ *param_offt = (data->progress.flags & PGRS_DL_SIZE_KNOWN)?
+ data->progress.size_dl:-1;
+ break;
+ case CURLINFO_CONTENT_LENGTH_UPLOAD_T:
+ *param_offt = (data->progress.flags & PGRS_UL_SIZE_KNOWN)?
+ data->progress.size_ul:-1;
+ break;
+ default:
+ return CURLE_UNKNOWN_OPTION;
+ }
+
+ return CURLE_OK;
+}
+
static CURLcode getinfo_double(struct Curl_easy *data, CURLINFO info,
double *param_doublep)
{
switch(info) {
case CURLINFO_TOTAL_TIME:
- *param_doublep = data->progress.timespent;
+ *param_doublep = DOUBLE_SECS(data->progress.timespent);
break;
case CURLINFO_NAMELOOKUP_TIME:
- *param_doublep = data->progress.t_nslookup;
+ *param_doublep = DOUBLE_SECS(data->progress.t_nslookup);
break;
case CURLINFO_CONNECT_TIME:
- *param_doublep = data->progress.t_connect;
+ *param_doublep = DOUBLE_SECS(data->progress.t_connect);
break;
case CURLINFO_APPCONNECT_TIME:
- *param_doublep = data->progress.t_appconnect;
+ *param_doublep = DOUBLE_SECS(data->progress.t_appconnect);
break;
case CURLINFO_PRETRANSFER_TIME:
- *param_doublep = data->progress.t_pretransfer;
+ *param_doublep = DOUBLE_SECS(data->progress.t_pretransfer);
break;
case CURLINFO_STARTTRANSFER_TIME:
- *param_doublep = data->progress.t_starttransfer;
+ *param_doublep = DOUBLE_SECS(data->progress.t_starttransfer);
break;
case CURLINFO_SIZE_UPLOAD:
*param_doublep = (double)data->progress.uploaded;
@@ -289,7 +323,7 @@ static CURLcode getinfo_double(struct Curl_easy *data, CURLINFO info,
(double)data->progress.size_ul:-1;
break;
case CURLINFO_REDIRECT_TIME:
- *param_doublep = data->progress.t_redirect;
+ *param_doublep = DOUBLE_SECS(data->progress.t_redirect);
break;
default:
@@ -326,46 +360,25 @@ static CURLcode getinfo_slist(struct Curl_easy *data, CURLINFO info,
struct curl_tlssessioninfo **tsip = (struct curl_tlssessioninfo **)
param_slistp;
struct curl_tlssessioninfo *tsi = &data->tsi;
+#ifdef USE_SSL
struct connectdata *conn = data->easy_conn;
+#endif
*tsip = tsi;
tsi->backend = Curl_ssl_backend();
tsi->internals = NULL;
+#ifdef USE_SSL
if(conn && tsi->backend != CURLSSLBACKEND_NONE) {
unsigned int i;
for(i = 0; i < (sizeof(conn->ssl) / sizeof(conn->ssl[0])); ++i) {
if(conn->ssl[i].use) {
-#if defined(USE_AXTLS)
- tsi->internals = (void *)conn->ssl[i].ssl;
-#elif defined(USE_CYASSL)
- tsi->internals = (void *)conn->ssl[i].handle;
-#elif defined(USE_DARWINSSL)
- tsi->internals = (void *)conn->ssl[i].ssl_ctx;
-#elif defined(USE_GNUTLS)
- tsi->internals = (void *)conn->ssl[i].session;
-#elif defined(USE_GSKIT)
- tsi->internals = (void *)conn->ssl[i].handle;
-#elif defined(USE_MBEDTLS)
- tsi->internals = (void *)&conn->ssl[i].ssl;
-#elif defined(USE_NSS)
- tsi->internals = (void *)conn->ssl[i].handle;
-#elif defined(USE_OPENSSL)
- /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */
- tsi->internals = ((info == CURLINFO_TLS_SESSION) ?
- (void *)conn->ssl[i].ctx :
- (void *)conn->ssl[i].handle);
-#elif defined(USE_POLARSSL)
- tsi->internals = (void *)&conn->ssl[i].ssl;
-#elif defined(USE_SCHANNEL)
- tsi->internals = (void *)&conn->ssl[i].ctxt->ctxt_handle;
-#elif defined(USE_SSL)
-#error "SSL backend specific information missing for CURLINFO_TLS_SSL_PTR"
-#endif
+ tsi->internals = Curl_ssl->get_internals(&conn->ssl[i], info);
break;
}
}
}
+#endif
}
break;
default:
@@ -394,6 +407,7 @@ CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...)
va_list arg;
long *param_longp = NULL;
double *param_doublep = NULL;
+ curl_off_t *param_offt = NULL;
const char **param_charp = NULL;
struct curl_slist **param_slistp = NULL;
curl_socket_t *param_socketp = NULL;
@@ -422,6 +436,11 @@ CURLcode Curl_getinfo(struct Curl_easy *data, CURLINFO info, ...)
if(param_doublep)
result = getinfo_double(data, info, param_doublep);
break;
+ case CURLINFO_OFF_T:
+ param_offt = va_arg(arg, curl_off_t *);
+ if(param_offt)
+ result = getinfo_offt(data, info, param_offt);
+ break;
case CURLINFO_SLIST:
param_slistp = va_arg(arg, struct curl_slist **);
if(param_slistp)
diff --git a/Utilities/cmcurl/lib/gopher.c b/Utilities/cmcurl/lib/gopher.c
index e6d274648..b7c31b695 100644
--- a/Utilities/cmcurl/lib/gopher.c
+++ b/Utilities/cmcurl/lib/gopher.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -65,6 +65,7 @@ const struct Curl_handler Curl_handler_gopher = {
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_GOPHER, /* defport */
CURLPROTO_GOPHER, /* protocol */
PROTOPT_NONE /* flags */
@@ -72,8 +73,8 @@ const struct Curl_handler Curl_handler_gopher = {
static CURLcode gopher_do(struct connectdata *conn, bool *done)
{
- CURLcode result=CURLE_OK;
- struct Curl_easy *data=conn->data;
+ CURLcode result = CURLE_OK;
+ struct Curl_easy *data = conn->data;
curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
curl_off_t *bytecount = &data->req.bytecount;
@@ -96,11 +97,11 @@ static CURLcode gopher_do(struct connectdata *conn, bool *done)
/* Otherwise, drop / and the first character (i.e., item type) ... */
newp = path;
- newp+=2;
+ newp += 2;
/* ... then turn ? into TAB for search servers, Veronica, etc. ... */
j = strlen(newp);
- for(i=0; i<j; i++)
+ for(i = 0; i<j; i++)
if(newp[i] == '?')
newp[i] = '\x09';
diff --git a/Utilities/cmcurl/lib/hash.c b/Utilities/cmcurl/lib/hash.c
index 6afeaa12c..c99b1b699 100644
--- a/Utilities/cmcurl/lib/hash.c
+++ b/Utilities/cmcurl/lib/hash.c
@@ -300,10 +300,10 @@ Curl_hash_next_element(struct curl_hash_iterator *iter)
/* If we have reached the end of the list, find the next one */
if(!iter->current_element) {
- for(i = iter->slot_index;i < h->slots;i++) {
+ for(i = iter->slot_index; i < h->slots; i++) {
if(h->table[i].head) {
iter->current_element = h->table[i].head;
- iter->slot_index = i+1;
+ iter->slot_index = i + 1;
break;
}
}
diff --git a/Utilities/cmcurl/lib/hostcheck.c b/Utilities/cmcurl/lib/hostcheck.c
index 156091ca8..23dc3d2a7 100644
--- a/Utilities/cmcurl/lib/hostcheck.c
+++ b/Utilities/cmcurl/lib/hostcheck.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -73,10 +73,10 @@ static int hostmatch(char *hostname, char *pattern)
/* normalize pattern and hostname by stripping off trailing dots */
size_t len = strlen(hostname);
if(hostname[len-1]=='.')
- hostname[len-1]=0;
+ hostname[len-1] = 0;
len = strlen(pattern);
if(pattern[len-1]=='.')
- pattern[len-1]=0;
+ pattern[len-1] = 0;
pattern_wildcard = strchr(pattern, '*');
if(pattern_wildcard == NULL)
@@ -95,7 +95,7 @@ static int hostmatch(char *hostname, char *pattern)
match. */
wildcard_enabled = 1;
pattern_label_end = strchr(pattern, '.');
- if(pattern_label_end == NULL || strchr(pattern_label_end+1, '.') == NULL ||
+ if(pattern_label_end == NULL || strchr(pattern_label_end + 1, '.') == NULL ||
pattern_wildcard > pattern_label_end ||
strncasecompare(pattern, "xn--", 4)) {
wildcard_enabled = 0;
@@ -116,9 +116,9 @@ static int hostmatch(char *hostname, char *pattern)
return CURL_HOST_NOMATCH;
prefixlen = pattern_wildcard - pattern;
- suffixlen = pattern_label_end - (pattern_wildcard+1);
+ suffixlen = pattern_label_end - (pattern_wildcard + 1);
return strncasecompare(pattern, hostname, prefixlen) &&
- strncasecompare(pattern_wildcard+1, hostname_label_end - suffixlen,
+ strncasecompare(pattern_wildcard + 1, hostname_label_end - suffixlen,
suffixlen) ?
CURL_HOST_MATCH : CURL_HOST_NOMATCH;
}
@@ -137,7 +137,7 @@ int Curl_cert_hostcheck(const char *match_pattern, const char *hostname)
hostp = strdup(hostname);
if(hostp) {
if(hostmatch(hostp, matchp) == CURL_HOST_MATCH)
- res= 1;
+ res = 1;
free(hostp);
}
free(matchp);
diff --git a/Utilities/cmcurl/lib/hostip.c b/Utilities/cmcurl/lib/hostip.c
index 619ec84b5..1a18a3ed7 100644
--- a/Utilities/cmcurl/lib/hostip.c
+++ b/Utilities/cmcurl/lib/hostip.c
@@ -304,9 +304,9 @@ fetch_addr(struct connectdata *conn,
entry_len = strlen(entry_id);
/* See if its already in our dns cache */
- dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len+1);
+ dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
- if(dns && (data->set.dns_cache_timeout != -1)) {
+ if(dns && (data->set.dns_cache_timeout != -1)) {
/* See whether the returned entry is stale. Done before we release lock */
struct hostcache_prune_data user;
@@ -316,7 +316,7 @@ fetch_addr(struct connectdata *conn,
if(hostcache_timestamp_remove(&user, dns)) {
infof(data, "Hostname in DNS cache was stale, zapped\n");
dns = NULL; /* the memory deallocation is being handled by the hash */
- Curl_hash_delete(data->dns.hostcache, entry_id, entry_len+1);
+ Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
}
}
@@ -403,7 +403,7 @@ Curl_cache_addr(struct Curl_easy *data,
dns->timestamp = 1; /* zero indicates CURLOPT_RESOLVE entry */
/* Store the resolved data in our DNS cache. */
- dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len+1,
+ dns2 = Curl_hash_add(data->dns.hostcache, entry_id, entry_len + 1,
(void *)dns);
if(!dns2) {
free(dns);
@@ -807,7 +807,7 @@ CURLcode Curl_loadhostpairs(struct Curl_easy *data)
Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
/* delete entry, ignore if it didn't exist */
- Curl_hash_delete(data->dns.hostcache, entry_id, entry_len+1);
+ Curl_hash_delete(data->dns.hostcache, entry_id, entry_len + 1);
if(data->share)
Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
@@ -848,7 +848,7 @@ CURLcode Curl_loadhostpairs(struct Curl_easy *data)
Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
/* See if its already in our dns cache */
- dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len+1);
+ dns = Curl_hash_pick(data->dns.hostcache, entry_id, entry_len + 1);
/* free the allocated entry_id again */
free(entry_id);
diff --git a/Utilities/cmcurl/lib/hostip4.c b/Utilities/cmcurl/lib/hostip4.c
index e459328ac..6a7c6e576 100644
--- a/Utilities/cmcurl/lib/hostip4.c
+++ b/Utilities/cmcurl/lib/hostip4.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -249,7 +249,7 @@ Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname,
*/
if(CURL_HOSTENT_SIZE >=
- (sizeof(struct hostent)+sizeof(struct hostent_data))) {
+ (sizeof(struct hostent) + sizeof(struct hostent_data))) {
/* August 22nd, 2000: Albert Chin-A-Young brought an updated version
* that should work! September 20: Richard Prescott worked on the buffer
diff --git a/Utilities/cmcurl/lib/hostip6.c b/Utilities/cmcurl/lib/hostip6.c
index 4ebfc2dcf..edeebec9e 100644
--- a/Utilities/cmcurl/lib/hostip6.c
+++ b/Utilities/cmcurl/lib/hostip6.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -212,7 +212,7 @@ Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn,
if(port) {
snprintf(sbuf, sizeof(sbuf), "%d", port);
- sbufptr=sbuf;
+ sbufptr = sbuf;
}
error = Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &res);
diff --git a/Utilities/cmcurl/lib/http.c b/Utilities/cmcurl/lib/http.c
index 21574e21d..38227eb6c 100644
--- a/Utilities/cmcurl/lib/http.c
+++ b/Utilities/cmcurl/lib/http.c
@@ -50,6 +50,7 @@
#include "transfer.h"
#include "sendf.h"
#include "formdata.h"
+#include "mime.h"
#include "progress.h"
#include "curl_base64.h"
#include "cookie.h"
@@ -119,6 +120,7 @@ const struct Curl_handler Curl_handler_http = {
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_HTTP, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_CREDSPERREQUEST /* flags */
@@ -143,6 +145,7 @@ const struct Curl_handler Curl_handler_https = {
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_HTTPS, /* defport */
CURLPROTO_HTTPS, /* protocol */
PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | PROTOPT_ALPN_NPN /* flags */
@@ -160,6 +163,7 @@ CURLcode Curl_http_setup_conn(struct connectdata *conn)
if(!http)
return CURLE_OUT_OF_MEMORY;
+ Curl_mime_initpart(&http->form, conn->data);
conn->data->req.protop = http;
Curl_http2_setup_conn(conn);
@@ -168,26 +172,6 @@ CURLcode Curl_http_setup_conn(struct connectdata *conn)
return CURLE_OK;
}
-/*
- * checkheaders() checks the linked list of custom HTTP headers for a
- * particular header (prefix).
- *
- * Returns a pointer to the first matching header or NULL if none matched.
- */
-char *Curl_checkheaders(const struct connectdata *conn,
- const char *thisheader)
-{
- struct curl_slist *head;
- size_t thislen = strlen(thisheader);
- struct Curl_easy *data = conn->data;
-
- for(head = data->set.headers;head; head=head->next) {
- if(strncasecompare(head->data, thisheader, thislen))
- return head->data;
- }
-
- return NULL;
-}
/*
* checkProxyHeaders() checks the linked list of custom proxy headers
@@ -207,7 +191,7 @@ char *Curl_checkProxyheaders(const struct connectdata *conn,
for(head = (conn->bits.proxy && data->set.sep_headers) ?
data->set.proxyheaders : data->set.headers;
- head; head=head->next) {
+ head; head = head->next) {
if(strncasecompare(head->data, thisheader, thislen))
return head->data;
}
@@ -425,6 +409,7 @@ static CURLcode http_perhapsrewind(struct connectdata *conn)
expectsend = data->state.infilesize;
break;
case HTTPREQ_POST_FORM:
+ case HTTPREQ_POST_MIME:
expectsend = http->postsize;
break;
default:
@@ -608,7 +593,7 @@ output_auth_headers(struct connectdata *conn,
#endif
#if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
if(authstatus->picked == CURLAUTH_NTLM_WB) {
- auth="NTLM_WB";
+ auth = "NTLM_WB";
result = Curl_output_ntlm_wb(conn, proxy);
if(result)
return result;
@@ -1020,7 +1005,7 @@ static size_t readmoredata(char *buffer,
http->sending++; /* move one step up */
- http->backup.postsize=0;
+ http->backup.postsize = 0;
}
else
http->postsize = 0;
@@ -1148,7 +1133,7 @@ CURLcode Curl_add_buffer_send(Curl_send_buffer *in,
/* there was body data sent beyond the initial header part, pass that
on to the debug callback too */
Curl_debug(conn->data, CURLINFO_DATA_OUT,
- ptr+headlen, bodylen, conn);
+ ptr + headlen, bodylen, conn);
}
}
@@ -1260,7 +1245,7 @@ CURLcode Curl_add_buffer(Curl_send_buffer *in, const void *inptr, size_t size)
(~(size * 2) < (in->size_used * 2)))
new_size = (size_t)-1;
else
- new_size = (in->size_used+size) * 2;
+ new_size = (in->size_used + size) * 2;
if(in->buffer)
/* we have a buffer, enlarge the existing one */
@@ -1337,7 +1322,7 @@ Curl_compareheader(const char *headerline, /* line to check */
clen = strlen(content); /* length of the word to find */
/* find the content string in the rest of the line */
- for(;len>=clen;len--, start++) {
+ for(; len >= clen; len--, start++) {
if(strncasecompare(start, content, clen))
return TRUE; /* match! */
}
@@ -1369,7 +1354,7 @@ CURLcode Curl_http_connect(struct connectdata *conn, bool *done)
if(CONNECT_FIRSTSOCKET_PROXY_SSL())
return CURLE_OK; /* wait for HTTPS proxy SSL initialization to complete */
- if(conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
+ if(Curl_connect_ongoing(conn))
/* nothing else to do except wait right now - we're not done here. */
return CURLE_OK;
@@ -1468,18 +1453,17 @@ CURLcode Curl_http_done(struct connectdata *conn,
Curl_http2_done(conn, premature);
- if(HTTPREQ_POST_FORM == data->set.httpreq) {
- data->req.bytecount = http->readbytecount + http->writebytecount;
+ Curl_mime_cleanpart(&http->form);
- Curl_formclean(&http->sendit); /* Now free that whole lot */
- if(http->form.fp) {
- /* a file being uploaded was left opened, close it! */
- fclose(http->form.fp);
- http->form.fp = NULL;
- }
- }
- else if(HTTPREQ_PUT == data->set.httpreq)
+ switch(data->set.httpreq) {
+ case HTTPREQ_PUT:
+ case HTTPREQ_POST_FORM:
+ case HTTPREQ_POST_MIME:
data->req.bytecount = http->readbytecount + http->writebytecount;
+ break;
+ default:
+ break;
+ }
if(status)
return status;
@@ -1579,7 +1563,7 @@ CURLcode Curl_add_custom_headers(struct connectdata *conn,
char *ptr;
struct curl_slist *h[2];
struct curl_slist *headers;
- int numlists=1; /* by default */
+ int numlists = 1; /* by default */
struct Curl_easy *data = conn->data;
int i;
@@ -1611,7 +1595,7 @@ CURLcode Curl_add_custom_headers(struct connectdata *conn,
}
/* loop through one or two lists */
- for(i=0; i < numlists; i++) {
+ for(i = 0; i < numlists; i++) {
headers = h[i];
while(headers) {
@@ -1635,15 +1619,19 @@ CURLcode Curl_add_custom_headers(struct connectdata *conn,
/* this header (extended by formdata.c) is sent later */
checkprefix("Content-Type:", headers->data))
;
+ else if(data->set.httpreq == HTTPREQ_POST_MIME &&
+ /* this header is sent later */
+ checkprefix("Content-Type:", headers->data))
+ ;
else if(conn->bits.authneg &&
/* while doing auth neg, don't allow the custom length since
we will force length zero then */
- checkprefix("Content-Length", headers->data))
+ checkprefix("Content-Length:", headers->data))
;
else if(conn->allocptr.te &&
/* when asking for Transfer-Encoding, don't pass on a custom
Connection: */
- checkprefix("Connection", headers->data))
+ checkprefix("Connection:", headers->data))
;
else if((conn->httpversion == 20) &&
checkprefix("Transfer-Encoding:", headers->data))
@@ -1676,6 +1664,10 @@ CURLcode Curl_add_custom_headers(struct connectdata *conn,
*ptr = ':';
result = Curl_add_bufferf(req_buffer, "%s\r\n",
headers->data);
+
+ /* restore the previous value */
+ *ptr = ';';
+
if(result)
return result;
}
@@ -1773,7 +1765,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
const char *httpstring;
Curl_send_buffer *req_buffer;
curl_off_t postsize = 0; /* curl_off_t to handle large file sizes */
- int seekerr = CURL_SEEKFUNC_OK;
+ int seekerr = CURL_SEEKFUNC_CANTSEEK;
/* Always consider the DO phase done after this function call, even if there
may be parts of the request that is not yet sent, since we can deal with
@@ -1846,11 +1838,15 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
switch(httpreq) {
case HTTPREQ_POST:
case HTTPREQ_POST_FORM:
+ case HTTPREQ_POST_MIME:
request = "POST";
break;
case HTTPREQ_PUT:
request = "PUT";
break;
+ case HTTPREQ_OPTIONS:
+ request = "OPTIONS";
+ break;
default: /* this should never happen */
case HTTPREQ_GET:
request = "GET";
@@ -1868,7 +1864,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
here. */
if(Curl_checkheaders(conn, "User-Agent:")) {
free(conn->allocptr.uagent);
- conn->allocptr.uagent=NULL;
+ conn->allocptr.uagent = NULL;
}
/* setup the authentication headers */
@@ -1937,6 +1933,48 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
}
#endif
+ switch(httpreq) {
+ case HTTPREQ_POST_MIME:
+ http->sendit = &data->set.mimepost;
+ break;
+ case HTTPREQ_POST_FORM:
+ /* Convert the form structure into a mime structure. */
+ Curl_mime_cleanpart(&http->form);
+ result = Curl_getformdata(data, &http->form, data->set.httppost,
+ data->state.fread_func);
+ if(result)
+ return result;
+ http->sendit = &http->form;
+ break;
+ default:
+ http->sendit = NULL;
+ }
+
+ if(http->sendit) {
+ const char *cthdr = Curl_checkheaders(conn, "Content-Type:");
+
+ /* Read and seek body only. */
+ http->sendit->flags |= MIME_BODY_ONLY;
+
+ /* Prepare the mime structure headers & set content type. */
+
+ if(cthdr)
+ for(cthdr += 13; *cthdr == ' '; cthdr++)
+ ;
+ else if(http->sendit->kind == MIMEKIND_MULTIPART)
+ cthdr = "multipart/form-data";
+
+ curl_mime_headers(http->sendit, data->set.headers, 0);
+ result = Curl_mime_prepare_headers(http->sendit, cthdr,
+ NULL, MIMESTRATEGY_FORM);
+ curl_mime_headers(http->sendit, NULL, 0);
+ if(!result)
+ result = Curl_mime_rewind(http->sendit);
+ if(result)
+ return result;
+ http->postsize = Curl_mime_size(http->sendit);
+ }
+
ptr = Curl_checkheaders(conn, "Transfer-Encoding:");
if(ptr) {
/* Some kind of TE is requested, check if 'chunked' is chosen */
@@ -1944,9 +1982,10 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
Curl_compareheader(ptr, "Transfer-Encoding:", "chunked");
}
else {
- if((conn->handler->protocol&PROTO_FAMILY_HTTP) &&
- data->set.upload &&
- (data->state.infilesize == -1)) {
+ if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
+ (((httpreq == HTTPREQ_POST_MIME || httpreq == HTTPREQ_POST_FORM) &&
+ http->postsize < 0) ||
+ (data->set.upload && data->state.infilesize == -1))) {
if(conn->bits.authneg)
/* don't enable chunked during auth neg */
;
@@ -2044,7 +2083,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
}
#ifndef CURL_DISABLE_PROXY
- if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) {
+ if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) {
/* Using a proxy but does not tunnel through it */
/* The path sent to the proxy is in fact the entire URL. But if the remote
@@ -2118,21 +2157,9 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
}
#endif /* CURL_DISABLE_PROXY */
- if(HTTPREQ_POST_FORM == httpreq) {
- /* we must build the whole post sequence first, so that we have a size of
- the whole transfer before we start to send it */
- result = Curl_getformdata(data, &http->sendit, data->set.httppost,
- Curl_checkheaders(conn, "Content-Type:"),
- &http->postsize);
- if(result)
- return result;
- }
-
http->p_accept = Curl_checkheaders(conn, "Accept:")?NULL:"Accept: */*\r\n";
- if(( (HTTPREQ_POST == httpreq) ||
- (HTTPREQ_POST_FORM == httpreq) ||
- (HTTPREQ_PUT == httpreq) ) &&
+ if((HTTPREQ_POST == httpreq || HTTPREQ_PUT == httpreq) &&
data->state.resume_from) {
/**********************************************************************
* Resuming upload in HTTP means that we PUT or POST and that we have
@@ -2140,6 +2167,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
* a Range: header that will be passed along. We need to "fast forward"
* the file the given number of bytes and decrease the assume upload
* file size before we continue this venture in the dark lands of HTTP.
+ * Resuming mime/form posting at an offset > 0 has no sense and is ignored.
*********************************************************************/
if(data->state.resume_from < 0) {
@@ -2161,7 +2189,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
}
if(seekerr != CURL_SEEKFUNC_OK) {
- curl_off_t passed=0;
+ curl_off_t passed = 0;
if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
failf(data, "Could not seek stream");
@@ -2214,7 +2242,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
conn->allocptr.rangeline = aprintf("Range: bytes=%s\r\n",
data->state.range);
}
- else if((httpreq != HTTPREQ_GET) &&
+ else if((httpreq == HTTPREQ_POST || httpreq == HTTPREQ_PUT) &&
!Curl_checkheaders(conn, "Content-Range:")) {
/* if a line like this was already allocated, free the previous one */
@@ -2232,7 +2260,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
}
else if(data->state.resume_from) {
/* This is because "resume" was selected */
- curl_off_t total_expected_size=
+ curl_off_t total_expected_size =
data->state.resume_from + data->state.infilesize;
conn->allocptr.rangeline =
aprintf("Content-Range: bytes %s%" CURL_FORMAT_CURL_OFF_T
@@ -2266,6 +2294,9 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
if(result)
return result;
+ if(data->set.str[STRING_TARGET])
+ ppath = data->set.str[STRING_TARGET];
+
/* url */
if(paste_ftp_userpwd)
result = Curl_add_bufferf(req_buffer, "ftp://%s:%s@%s",
@@ -2339,8 +2370,8 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
#if !defined(CURL_DISABLE_COOKIES)
if(data->cookies || addcookies) {
- struct Cookie *co=NULL; /* no cookies from start */
- int count=0;
+ struct Cookie *co = NULL; /* no cookies from start */
+ int count = 0;
if(data->cookies) {
Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
@@ -2353,7 +2384,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
}
if(co) {
- struct Cookie *store=co;
+ struct Cookie *store = co;
/* now loop through all cookies that matched */
while(co) {
if(co->value) {
@@ -2407,117 +2438,79 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
switch(httpreq) {
- case HTTPREQ_POST_FORM:
- if(!http->sendit || conn->bits.authneg) {
- /* nothing to post! */
- result = Curl_add_bufferf(req_buffer, "Content-Length: 0\r\n\r\n");
- if(result)
- return result;
-
- result = Curl_add_buffer_send(req_buffer, conn,
- &data->info.request_size, 0, FIRSTSOCKET);
- if(result)
- failf(data, "Failed sending POST request");
- else
- /* setup variables for the upcoming transfer */
- Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
- -1, NULL);
- break;
- }
-
- if(Curl_FormInit(&http->form, http->sendit)) {
- failf(data, "Internal HTTP POST error!");
- return CURLE_HTTP_POST_ERROR;
- }
-
- /* Get the currently set callback function pointer and store that in the
- form struct since we might want the actual user-provided callback later
- on. The data->set.fread_func pointer itself will be changed for the
- multipart case to the function that returns a multipart formatted
- stream. */
- http->form.fread_func = data->state.fread_func;
-
- /* Set the read function to read from the generated form data */
- data->state.fread_func = (curl_read_callback)Curl_FormReader;
- data->state.in = &http->form;
+ case HTTPREQ_PUT: /* Let's PUT the data to the server! */
- http->sending = HTTPSEND_BODY;
+ if(conn->bits.authneg)
+ postsize = 0;
+ else
+ postsize = data->state.infilesize;
- if(!data->req.upload_chunky &&
- !Curl_checkheaders(conn, "Content-Length:")) {
+ if((postsize != -1) && !data->req.upload_chunky &&
+ (conn->bits.authneg || !Curl_checkheaders(conn, "Content-Length:"))) {
/* only add Content-Length if not uploading chunked */
result = Curl_add_bufferf(req_buffer,
"Content-Length: %" CURL_FORMAT_CURL_OFF_T
- "\r\n", http->postsize);
+ "\r\n", postsize);
if(result)
return result;
}
- result = expect100(data, conn, req_buffer);
- if(result)
- return result;
-
- {
-
- /* Get Content-Type: line from Curl_formpostheader.
- */
- char *contentType;
- size_t linelength=0;
- contentType = Curl_formpostheader((void *)&http->form,
- &linelength);
- if(!contentType) {
- failf(data, "Could not get Content-Type header line!");
- return CURLE_HTTP_POST_ERROR;
- }
-
- result = Curl_add_buffer(req_buffer, contentType, linelength);
+ if(postsize != 0) {
+ result = expect100(data, conn, req_buffer);
if(result)
return result;
}
- /* make the request end in a true CRLF */
- result = Curl_add_buffer(req_buffer, "\r\n", 2);
+ result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers */
if(result)
return result;
- /* set upload size to the progress meter */
- Curl_pgrsSetUploadSize(data, http->postsize);
+ /* set the upload size to the progress meter */
+ Curl_pgrsSetUploadSize(data, postsize);
- /* fire away the whole request to the server */
+ /* this sends the buffer and frees all the buffer resources */
result = Curl_add_buffer_send(req_buffer, conn,
&data->info.request_size, 0, FIRSTSOCKET);
if(result)
- failf(data, "Failed sending POST request");
+ failf(data, "Failed sending PUT request");
else
- /* setup variables for the upcoming transfer */
+ /* prepare for transfer */
Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
- &http->readbytecount, FIRSTSOCKET,
- &http->writebytecount);
-
- if(result) {
- Curl_formclean(&http->sendit); /* free that whole lot */
- return result;
- }
-
- /* convert the form data */
- result = Curl_convert_form(data, http->sendit);
- if(result) {
- Curl_formclean(&http->sendit); /* free that whole lot */
+ &http->readbytecount, postsize?FIRSTSOCKET:-1,
+ postsize?&http->writebytecount:NULL);
+ if(result)
return result;
- }
-
break;
- case HTTPREQ_PUT: /* Let's PUT the data to the server! */
+ case HTTPREQ_POST_FORM:
+ case HTTPREQ_POST_MIME:
+ /* This is form posting using mime data. */
+ if(conn->bits.authneg) {
+ /* nothing to post! */
+ result = Curl_add_bufferf(req_buffer, "Content-Length: 0\r\n\r\n");
+ if(result)
+ return result;
- if(conn->bits.authneg)
- postsize = 0;
- else
- postsize = data->state.infilesize;
+ result = Curl_add_buffer_send(req_buffer, conn,
+ &data->info.request_size, 0, FIRSTSOCKET);
+ if(result)
+ failf(data, "Failed sending POST request");
+ else
+ /* setup variables for the upcoming transfer */
+ Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
+ -1, NULL);
+ break;
+ }
- if((postsize != -1) && !data->req.upload_chunky &&
+ postsize = http->postsize;
+
+ /* We only set Content-Length and allow a custom Content-Length if
+ we don't upload data chunked, as RFC2616 forbids us to set both
+ kinds of headers (Transfer-Encoding: chunked and Content-Length) */
+ if(postsize != -1 && !data->req.upload_chunky &&
(conn->bits.authneg || !Curl_checkheaders(conn, "Content-Length:"))) {
- /* only add Content-Length if not uploading chunked */
+ /* we allow replacing this header if not during auth negotiation,
+ although it isn't very wise to actually set your own */
result = Curl_add_bufferf(req_buffer,
"Content-Length: %" CURL_FORMAT_CURL_OFF_T
"\r\n", postsize);
@@ -2525,24 +2518,52 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
return result;
}
- if(postsize != 0) {
+ /* Output mime-generated headers. */
+ {
+ struct curl_slist *hdr;
+
+ for(hdr = http->sendit->curlheaders; hdr; hdr = hdr->next) {
+ result = Curl_add_bufferf(req_buffer, "%s\r\n", hdr->data);
+ if(result)
+ return result;
+ }
+ }
+
+ /* For really small posts we don't use Expect: headers at all, and for
+ the somewhat bigger ones we allow the app to disable it. Just make
+ sure that the expect100header is always set to the preferred value
+ here. */
+ ptr = Curl_checkheaders(conn, "Expect:");
+ if(ptr) {
+ data->state.expect100header =
+ Curl_compareheader(ptr, "Expect:", "100-continue");
+ }
+ else if(postsize > EXPECT_100_THRESHOLD || postsize < 0) {
result = expect100(data, conn, req_buffer);
if(result)
return result;
}
+ else
+ data->state.expect100header = FALSE;
- result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers */
+ /* make the request end in a true CRLF */
+ result = Curl_add_buffer(req_buffer, "\r\n", 2);
if(result)
return result;
/* set the upload size to the progress meter */
Curl_pgrsSetUploadSize(data, postsize);
+ /* Read from mime structure. */
+ data->state.fread_func = (curl_read_callback) Curl_mime_read;
+ data->state.in = (void *) http->sendit;
+ http->sending = HTTPSEND_BODY;
+
/* this sends the buffer and frees all the buffer resources */
result = Curl_add_buffer_send(req_buffer, conn,
&data->info.request_size, 0, FIRSTSOCKET);
if(result)
- failf(data, "Failed sending PUT request");
+ failf(data, "Failed sending POST request");
else
/* prepare for transfer */
Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
@@ -2550,6 +2571,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
postsize?&http->writebytecount:NULL);
if(result)
return result;
+
break;
case HTTPREQ_POST:
@@ -2592,7 +2614,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
data->state.expect100header =
Curl_compareheader(ptr, "Expect:", "100-continue");
}
- else if(postsize > TINY_INITIAL_POST_SIZE || postsize < 0) {
+ else if(postsize > EXPECT_100_THRESHOLD || postsize < 0) {
result = expect100(data, conn, req_buffer);
if(result)
return result;
@@ -2606,7 +2628,7 @@ CURLcode Curl_http(struct connectdata *conn, bool *done)
its size. */
if(conn->httpversion != 20 &&
!data->state.expect100header &&
- (postsize < MAX_INITIAL_POST_SIZE)) {
+ (postsize < MAX_INITIAL_POST_SIZE)) {
/* if we don't use expect: 100 AND
postsize is less than MAX_INITIAL_POST_SIZE
@@ -2771,7 +2793,7 @@ checkhttpprefix(struct Curl_easy *data,
failf(data, "Failed to allocate memory for conversion!");
return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
}
- if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s)+1)) {
+ if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s) + 1)) {
/* Curl_convert_from_network calls failf if unsuccessful */
free(scratch);
return FALSE; /* can't return CURLE_foobar so return FALSE */
@@ -2801,6 +2823,7 @@ static bool
checkrtspprefix(struct Curl_easy *data,
const char *s)
{
+ bool result = FALSE;
#ifdef CURL_DOES_CONVERSIONS
/* convert from the network encoding using a scratch area */
@@ -2809,18 +2832,19 @@ checkrtspprefix(struct Curl_easy *data,
failf(data, "Failed to allocate memory for conversion!");
return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
}
- if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s)+1)) {
+ if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s) + 1)) {
/* Curl_convert_from_network calls failf if unsuccessful */
- free(scratch);
- return FALSE; /* can't return CURLE_foobar so return FALSE */
+ result = FALSE; /* can't return CURLE_foobar so return FALSE */
}
- s = scratch;
+ else
+ result = checkprefix("RTSP/", scratch)? TRUE: FALSE;
+ free(scratch);
#else
(void)data; /* unused */
+ result = checkprefix("RTSP/", s)? TRUE: FALSE;
#endif /* CURL_DOES_CONVERSIONS */
- if(checkprefix("RTSP/", s))
- return TRUE;
- return FALSE;
+
+ return result;
}
#endif /* CURL_DISABLE_RTSP */
@@ -2862,14 +2886,14 @@ static CURLcode header_append(struct Curl_easy *data,
return CURLE_OUT_OF_MEMORY;
}
- newsize=CURLMAX((k->hbuflen+ length)*3/2, data->state.headersize*2);
+ newsize = CURLMAX((k->hbuflen + length) * 3 / 2, data->state.headersize*2);
hbufp_index = k->hbufp - data->state.headerbuff;
newbuff = realloc(data->state.headerbuff, newsize);
if(!newbuff) {
failf(data, "Failed to alloc memory for big header!");
return CURLE_OUT_OF_MEMORY;
}
- data->state.headersize=newsize;
+ data->state.headersize = newsize;
data->state.headerbuff = newbuff;
k->hbufp = data->state.headerbuff + hbufp_index;
}
@@ -2962,7 +2986,7 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
}
/* decrease the size of the remaining (supposed) header line */
- rest_length = (k->end_ptr - k->str)+1;
+ rest_length = (k->end_ptr - k->str) + 1;
*nread -= (ssize_t)rest_length;
k->str = k->end_ptr + 1; /* move past new line */
@@ -3161,6 +3185,7 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
case HTTPREQ_PUT:
case HTTPREQ_POST:
case HTTPREQ_POST_FORM:
+ case HTTPREQ_POST_MIME:
/* We got an error response. If this happened before the whole
* request body has been sent we stop sending and mark the
* connection for closure after we've read the entire response.
@@ -3288,7 +3313,7 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
#define HEADER1 scratch
#define SCRATCHSIZE 21
CURLcode res;
- char scratch[SCRATCHSIZE+1]; /* "HTTP/major.minor 123" */
+ char scratch[SCRATCHSIZE + 1]; /* "HTTP/major.minor 123" */
/* We can't really convert this yet because we
don't know if it's the 1st header line or the body.
So we do a partial conversion into a scratch area,
@@ -3314,19 +3339,22 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
* says. We try to allow any number here, but we cannot make
* guarantees on future behaviors since it isn't within the protocol.
*/
+ char separator;
nc = sscanf(HEADER1,
- " HTTP/%d.%d %d",
+ " HTTP/%1d.%1d%c%3d",
&httpversion_major,
&conn->httpversion,
+ &separator,
&k->httpcode);
if(nc == 1 && httpversion_major == 2 &&
1 == sscanf(HEADER1, " HTTP/2 %d", &k->httpcode)) {
conn->httpversion = 0;
- nc = 3;
+ nc = 4;
+ separator = ' ';
}
- if(nc==3) {
+ if((nc == 4) && (' ' == separator)) {
conn->httpversion += 10 * httpversion_major;
if(k->upgr101 == UPGR101_RECEIVED) {
@@ -3335,11 +3363,11 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
infof(data, "Lying server, not serving HTTP/2\n");
}
}
- else {
+ else if(!nc) {
/* this is the real world, not a Nirvana
NCSA 1.5.x returns this crap when asked for HTTP/1.1
*/
- nc=sscanf(HEADER1, " HTTP %3d", &k->httpcode);
+ nc = sscanf(HEADER1, " HTTP %3d", &k->httpcode);
conn->httpversion = 10;
/* If user has set option HTTP200ALIASES,
@@ -3353,6 +3381,10 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
}
}
}
+ else {
+ failf(data, "Unsupported HTTP version in response\n");
+ return CURLE_UNSUPPORTED_PROTOCOL;
+ }
}
else if(conn->handler->protocol & CURLPROTO_RTSP) {
nc = sscanf(HEADER1,
@@ -3360,7 +3392,7 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
&rtspversion_major,
&conn->rtspversion,
&k->httpcode);
- if(nc==3) {
+ if(nc == 3) {
conn->rtspversion += 10 * rtspversion_major;
conn->httpversion = 11; /* For us, RTSP acts like HTTP 1.1 */
}
@@ -3392,7 +3424,7 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
((k->httpcode != 407) || !conn->bits.proxy_user_passwd) ) {
if(data->state.resume_from &&
- (data->set.httpreq==HTTPREQ_GET) &&
+ (data->set.httpreq == HTTPREQ_GET) &&
(k->httpcode == 416)) {
/* "Requested Range Not Satisfiable", just proceed and
pretend this is no error */
@@ -3448,8 +3480,8 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
* fields. */
if(data->set.timecondition)
data->info.timecond = TRUE;
- k->size=0;
- k->maxdownload=0;
+ k->size = 0;
+ k->maxdownload = 0;
k->ignorecl = TRUE; /* ignore Content-Length headers */
break;
default:
@@ -3471,28 +3503,32 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
/* Check for Content-Length: header lines to get size */
if(!k->ignorecl && !data->set.ignorecl &&
checkprefix("Content-Length:", k->p)) {
- curl_off_t contentlength = curlx_strtoofft(k->p+15, NULL, 10);
- if(data->set.max_filesize &&
- contentlength > data->set.max_filesize) {
- failf(data, "Maximum file size exceeded");
- return CURLE_FILESIZE_EXCEEDED;
- }
- if(contentlength >= 0) {
- k->size = contentlength;
- k->maxdownload = k->size;
- /* we set the progress download size already at this point
- just to make it easier for apps/callbacks to extract this
- info as soon as possible */
- Curl_pgrsSetDownloadSize(data, k->size);
- }
- else {
- /* Negative Content-Length is really odd, and we know it
- happens for example when older Apache servers send large
- files */
- streamclose(conn, "negative content-length");
- infof(data, "Negative content-length: %" CURL_FORMAT_CURL_OFF_T
- ", closing after transfer\n", contentlength);
+ curl_off_t contentlength;
+ if(!curlx_strtoofft(k->p + 15, NULL, 10, &contentlength)) {
+ if(data->set.max_filesize &&
+ contentlength > data->set.max_filesize) {
+ failf(data, "Maximum file size exceeded");
+ return CURLE_FILESIZE_EXCEEDED;
+ }
+ if(contentlength >= 0) {
+ k->size = contentlength;
+ k->maxdownload = k->size;
+ /* we set the progress download size already at this point
+ just to make it easier for apps/callbacks to extract this
+ info as soon as possible */
+ Curl_pgrsSetDownloadSize(data, k->size);
+ }
+ else {
+ /* Negative Content-Length is really odd, and we know it
+ happens for example when older Apache servers send large
+ files */
+ streamclose(conn, "negative content-length");
+ infof(data, "Negative content-length: %" CURL_FORMAT_CURL_OFF_T
+ ", closing after transfer\n", contentlength);
+ }
}
+ else
+ infof(data, "Illegal Content-Length: header\n");
}
/* check for Content-Type: header lines to get the MIME-type */
else if(checkprefix("Content-Type:", k->p)) {
@@ -3667,11 +3703,11 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
/* if it truly stopped on a digit */
if(ISDIGIT(*ptr)) {
- k->offset = curlx_strtoofft(ptr, NULL, 10);
-
- if(data->state.resume_from == k->offset)
- /* we asked for a resume and we got it */
- k->content_range = TRUE;
+ if(!curlx_strtoofft(ptr, NULL, 10, &k->offset)) {
+ if(data->state.resume_from == k->offset)
+ /* we asked for a resume and we got it */
+ k->content_range = TRUE;
+ }
}
else
data->state.resume_from = 0; /* get everything */
@@ -3682,7 +3718,7 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
CURL_LOCK_ACCESS_SINGLE);
Curl_cookie_add(data,
- data->cookies, TRUE, k->p+11,
+ data->cookies, TRUE, k->p + 11,
/* If there is a custom-set Host: name, use it
here, or else use real peer host name. */
conn->allocptr.cookiehost?
@@ -3693,8 +3729,8 @@ CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
#endif
else if(checkprefix("Last-Modified:", k->p) &&
(data->set.timecondition || data->set.get_filetime) ) {
- time_t secs=time(NULL);
- k->timeofdoc = curl_getdate(k->p+strlen("Last-Modified:"),
+ time_t secs = time(NULL);
+ k->timeofdoc = curl_getdate(k->p + strlen("Last-Modified:"),
&secs);
if(data->set.get_filetime)
data->info.filetime = (long)k->timeofdoc;
diff --git a/Utilities/cmcurl/lib/http.h b/Utilities/cmcurl/lib/http.h
index 7ce4bd9a0..d2781bc0f 100644
--- a/Utilities/cmcurl/lib/http.h
+++ b/Utilities/cmcurl/lib/http.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -40,8 +40,6 @@ bool Curl_compareheader(const char *headerline, /* line to check */
const char *header, /* header keyword _with_ colon */
const char *content); /* content string to find */
-char *Curl_checkheaders(const struct connectdata *conn,
- const char *thisheader);
char *Curl_copy_header_value(const char *header);
char *Curl_checkProxyheaders(const struct connectdata *conn,
@@ -115,8 +113,13 @@ CURLcode Curl_http_perhapsrewind(struct connectdata *conn);
#define MAX_INITIAL_POST_SIZE (64*1024)
#endif
-#ifndef TINY_INITIAL_POST_SIZE
-#define TINY_INITIAL_POST_SIZE 1024
+/* EXPECT_100_THRESHOLD is the request body size limit for when libcurl will
+ * automatically add an "Expect: 100-continue" header in HTTP requests. When
+ * the size is unknown, it will always add it.
+ *
+ */
+#ifndef EXPECT_100_THRESHOLD
+#define EXPECT_100_THRESHOLD 1024
#endif
#endif /* CURL_DISABLE_HTTP */
@@ -125,7 +128,7 @@ CURLcode Curl_http_perhapsrewind(struct connectdata *conn);
* HTTP unique setup
***************************************************************************/
struct HTTP {
- struct FormData *sendit;
+ curl_mimepart *sendit;
curl_off_t postsize; /* off_t to handle large file sizes */
const char *postdata;
@@ -135,7 +138,7 @@ struct HTTP {
curl_off_t writebytecount;
/* For FORM posting */
- struct Form form;
+ curl_mimepart form;
struct back {
curl_read_callback fread_func; /* backup storage for fread pointer */
diff --git a/Utilities/cmcurl/lib/http2.c b/Utilities/cmcurl/lib/http2.c
index f8e23c517..9a2a1dd55 100644
--- a/Utilities/cmcurl/lib/http2.c
+++ b/Utilities/cmcurl/lib/http2.c
@@ -28,6 +28,7 @@
#include "http2.h"
#include "http.h"
#include "sendf.h"
+#include "select.h"
#include "curl_base64.h"
#include "strcase.h"
#include "multiif.h"
@@ -151,6 +152,49 @@ static CURLcode http2_disconnect(struct connectdata *conn,
return CURLE_OK;
}
+/*
+ * The server may send us data at any point (e.g. PING frames). Therefore,
+ * we cannot assume that an HTTP/2 socket is dead just because it is readable.
+ *
+ * Instead, if it is readable, run Curl_connalive() to peek at the socket
+ * and distinguish between closed and data.
+ */
+static bool http2_connisdead(struct connectdata *check)
+{
+ int sval;
+ bool ret_val = TRUE;
+
+ sval = SOCKET_READABLE(check->sock[FIRSTSOCKET], 0);
+ if(sval == 0) {
+ /* timeout */
+ ret_val = FALSE;
+ }
+ else if(sval & CURL_CSELECT_ERR) {
+ /* socket is in an error state */
+ ret_val = TRUE;
+ }
+ else if(sval & CURL_CSELECT_IN) {
+ /* readable with no error. could still be closed */
+ ret_val = !Curl_connalive(check);
+ }
+
+ return ret_val;
+}
+
+
+static unsigned int http2_conncheck(struct connectdata *check,
+ unsigned int checks_to_perform)
+{
+ unsigned int ret_val = CONNRESULT_NONE;
+
+ if(checks_to_perform & CONNCHECK_ISDEAD) {
+ if(http2_connisdead(check))
+ ret_val |= CONNRESULT_DEAD;
+ }
+
+ return ret_val;
+}
+
/* called from Curl_http_setup_conn */
void Curl_http2_setup_req(struct Curl_easy *data)
{
@@ -196,6 +240,7 @@ static const struct Curl_handler Curl_handler_http2 = {
http2_perform_getsock, /* perform_getsock */
http2_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ http2_conncheck, /* connection_check */
PORT_HTTP, /* defport */
CURLPROTO_HTTP, /* protocol */
PROTOPT_STREAM /* flags */
@@ -216,6 +261,7 @@ static const struct Curl_handler Curl_handler_http2_ssl = {
http2_perform_getsock, /* perform_getsock */
http2_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ http2_conncheck, /* connection_check */
PORT_HTTP, /* defport */
CURLPROTO_HTTPS, /* protocol */
PROTOPT_SSL | PROTOPT_STREAM /* flags */
@@ -338,12 +384,12 @@ char *curl_pushheader_byname(struct curl_pushheaders *h, const char *header)
struct HTTP *stream = h->data->req.protop;
size_t len = strlen(header);
size_t i;
- for(i=0; i<stream->push_headers_used; i++) {
+ for(i = 0; i<stream->push_headers_used; i++) {
if(!strncmp(header, stream->push_headers[i], len)) {
/* sub-match, make sure that it is followed by a colon */
if(stream->push_headers[i][len] != ':')
continue;
- return &stream->push_headers[i][len+1];
+ return &stream->push_headers[i][len + 1];
}
}
}
@@ -418,7 +464,7 @@ static int push_promise(struct Curl_easy *data,
data->multi->push_userp);
/* free the headers again */
- for(i=0; i<stream->push_headers_used; i++)
+ for(i = 0; i<stream->push_headers_used; i++)
free(stream->push_headers[i]);
free(stream->push_headers);
stream->push_headers = NULL;
@@ -1536,7 +1582,7 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex,
failf(data, "nghttp2_session_mem_recv() returned %d:%s\n",
rv, nghttp2_strerror((int)rv));
*err = CURLE_RECV_ERROR;
- return 0;
+ return -1;
}
DEBUGF(infof(data, "nghttp2_session_mem_recv() returns %zd\n", rv));
if(nread == rv) {
@@ -1554,7 +1600,7 @@ static ssize_t http2_recv(struct connectdata *conn, int sockindex,
rv = h2_session_send(data, httpc->h2);
if(rv != 0) {
*err = CURLE_SEND_ERROR;
- return 0;
+ return -1;
}
if(should_close_session(httpc)) {
@@ -1909,6 +1955,7 @@ static ssize_t http2_send(struct connectdata *conn, int sockindex,
switch(conn->data->set.httpreq) {
case HTTPREQ_POST:
case HTTPREQ_POST_FORM:
+ case HTTPREQ_POST_MIME:
case HTTPREQ_PUT:
if(conn->data->state.infilesize != -1)
stream->upload_left = conn->data->state.infilesize;
@@ -2134,12 +2181,15 @@ CURLcode Curl_http2_switched(struct connectdata *conn,
return CURLE_OK;
}
-void Curl_http2_add_child(struct Curl_easy *parent, struct Curl_easy *child,
- bool exclusive)
+CURLcode Curl_http2_add_child(struct Curl_easy *parent,
+ struct Curl_easy *child,
+ bool exclusive)
{
if(parent) {
struct Curl_http2_dep **tail;
struct Curl_http2_dep *dep = calloc(1, sizeof(struct Curl_http2_dep));
+ if(!dep)
+ return CURLE_OUT_OF_MEMORY;
dep->data = child;
if(parent->set.stream_dependents && exclusive) {
@@ -2170,6 +2220,7 @@ void Curl_http2_add_child(struct Curl_easy *parent, struct Curl_easy *child,
child->set.stream_depends_on = parent;
child->set.stream_depends_e = exclusive;
+ return CURLE_OK;
}
void Curl_http2_remove_child(struct Curl_easy *parent, struct Curl_easy *child)
diff --git a/Utilities/cmcurl/lib/http2.h b/Utilities/cmcurl/lib/http2.h
index f405b3aeb..f597c805e 100644
--- a/Utilities/cmcurl/lib/http2.h
+++ b/Utilities/cmcurl/lib/http2.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -53,8 +53,9 @@ void Curl_http2_setup_conn(struct connectdata *conn);
void Curl_http2_setup_req(struct Curl_easy *data);
void Curl_http2_done(struct connectdata *conn, bool premature);
CURLcode Curl_http2_done_sending(struct connectdata *conn);
-void Curl_http2_add_child(struct Curl_easy *parent, struct Curl_easy *child,
- bool exclusive);
+CURLcode Curl_http2_add_child(struct Curl_easy *parent,
+ struct Curl_easy *child,
+ bool exclusive);
void Curl_http2_remove_child(struct Curl_easy *parent,
struct Curl_easy *child);
void Curl_http2_cleanup_dependencies(struct Curl_easy *data);
diff --git a/Utilities/cmcurl/lib/http_chunks.c b/Utilities/cmcurl/lib/http_chunks.c
index 1bdf6974c..92d773112 100644
--- a/Utilities/cmcurl/lib/http_chunks.c
+++ b/Utilities/cmcurl/lib/http_chunks.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -86,8 +86,8 @@ static bool Curl_isxdigit(char digit)
void Curl_httpchunk_init(struct connectdata *conn)
{
struct Curl_chunker *chunk = &conn->chunk;
- chunk->hexindex=0; /* start at 0 */
- chunk->dataleft=0; /* no data left yet! */
+ chunk->hexindex = 0; /* start at 0 */
+ chunk->dataleft = 0; /* no data left yet! */
chunk->state = CHUNK_HEX; /* we get hex first! */
}
@@ -107,7 +107,7 @@ CHUNKcode Curl_httpchunk_read(struct connectdata *conn,
ssize_t datalen,
ssize_t *wrotep)
{
- CURLcode result=CURLE_OK;
+ CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
struct Curl_chunker *ch = &conn->chunk;
struct SingleRequest *k = &data->req;
@@ -147,7 +147,7 @@ CHUNKcode Curl_httpchunk_read(struct connectdata *conn,
return CHUNKE_ILLEGAL_HEX;
/* length and datap are unmodified */
- ch->hexbuffer[ch->hexindex]=0;
+ ch->hexbuffer[ch->hexindex] = 0;
/* convert to host encoding before calling strtoul */
result = Curl_convert_from_network(conn->data, ch->hexbuffer,
@@ -158,9 +158,7 @@ CHUNKcode Curl_httpchunk_read(struct connectdata *conn,
return CHUNKE_ILLEGAL_HEX;
}
- ch->datasize=curlx_strtoofft(ch->hexbuffer, &endptr, 16);
- if((ch->datasize == CURL_OFF_T_MAX) && (errno == ERANGE))
- /* overflow is an error */
+ if(curlx_strtoofft(ch->hexbuffer, &endptr, 16, &ch->datasize))
return CHUNKE_ILLEGAL_HEX;
ch->state = CHUNK_LF; /* now wait for the CRLF */
}
@@ -172,7 +170,7 @@ CHUNKcode Curl_httpchunk_read(struct connectdata *conn,
/* we're now expecting data to come, unless size was zero! */
if(0 == ch->datasize) {
ch->state = CHUNK_TRAILER; /* now check for trailers */
- conn->trlPos=0;
+ conn->trlPos = 0;
}
else
ch->state = CHUNK_DATA;
@@ -259,9 +257,9 @@ CHUNKcode Curl_httpchunk_read(struct connectdata *conn,
if(conn->trlPos) {
/* we allocate trailer with 3 bytes extra room to fit this */
- conn->trailer[conn->trlPos++]=0x0d;
- conn->trailer[conn->trlPos++]=0x0a;
- conn->trailer[conn->trlPos]=0;
+ conn->trailer[conn->trlPos++] = 0x0d;
+ conn->trailer[conn->trlPos++] = 0x0a;
+ conn->trailer[conn->trlPos] = 0;
/* Convert to host encoding before calling Curl_client_write */
result = Curl_convert_from_network(conn->data, conn->trailer,
@@ -277,7 +275,7 @@ CHUNKcode Curl_httpchunk_read(struct connectdata *conn,
if(result)
return CHUNKE_WRITE_ERROR;
}
- conn->trlPos=0;
+ conn->trlPos = 0;
ch->state = CHUNK_TRAILER_CR;
if(*datap == 0x0a)
/* already on the LF */
@@ -301,7 +299,7 @@ CHUNKcode Curl_httpchunk_read(struct connectdata *conn,
ptr = realloc(conn->trailer, conn->trlMax + 3);
}
else {
- conn->trlMax=128;
+ conn->trlMax = 128;
ptr = malloc(conn->trlMax + 3);
}
if(!ptr)
diff --git a/Utilities/cmcurl/lib/http_ntlm.c b/Utilities/cmcurl/lib/http_ntlm.c
index 8a78bd293..0f1edcf65 100644
--- a/Utilities/cmcurl/lib/http_ntlm.c
+++ b/Utilities/cmcurl/lib/http_ntlm.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -37,11 +37,14 @@
#include "sendf.h"
#include "strcase.h"
#include "http_ntlm.h"
+#include "curl_ntlm_core.h"
#include "curl_ntlm_wb.h"
#include "vauth/vauth.h"
#include "url.h"
-#if defined(USE_NSS)
+/* SSL backend-specific #if branches in this file must be kept in the order
+ documented in curl_ntlm_core. */
+#if defined(NTLM_NEEDS_NSS_INIT)
#include "vtls/nssg.h"
#elif defined(USE_WINDOWS_SSPI)
#include "curl_sspi.h"
@@ -129,7 +132,7 @@ CURLcode Curl_output_ntlm(struct connectdata *conn, bool proxy)
DEBUGASSERT(conn);
DEBUGASSERT(conn->data);
-#ifdef USE_NSS
+#if defined(NTLM_NEEDS_NSS_INIT)
if(CURLE_OK != Curl_nss_force_init(conn->data))
return CURLE_OUT_OF_MEMORY;
#endif
@@ -170,8 +173,8 @@ CURLcode Curl_output_ntlm(struct connectdata *conn, bool proxy)
case NTLMSTATE_TYPE1:
default: /* for the weird cases we (re)start here */
/* Create a type-1 message */
- result = Curl_auth_create_ntlm_type1_message(userp, passwdp, ntlm, &base64,
- &len);
+ result = Curl_auth_create_ntlm_type1_message(conn->data, userp, passwdp,
+ ntlm, &base64, &len);
if(result)
return result;
diff --git a/Utilities/cmcurl/lib/http_proxy.c b/Utilities/cmcurl/lib/http_proxy.c
index 9894e2e5f..dff9d230a 100644
--- a/Utilities/cmcurl/lib/http_proxy.c
+++ b/Utilities/cmcurl/lib/http_proxy.c
@@ -22,11 +22,11 @@
#include "curl_setup.h"
+#include "http_proxy.h"
+
#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
-#include "urldata.h"
#include <curl/curl.h>
-#include "http_proxy.h"
#include "sendf.h"
#include "http.h"
#include "url.h"
@@ -135,35 +135,73 @@ CURLcode Curl_proxy_connect(struct connectdata *conn, int sockindex)
return CURLE_OK;
}
-#define CONNECT_BUFFER_SIZE 16384
+bool Curl_connect_complete(struct connectdata *conn)
+{
+ return !conn->connect_state ||
+ (conn->connect_state->tunnel_state == TUNNEL_COMPLETE);
+}
+
+bool Curl_connect_ongoing(struct connectdata *conn)
+{
+ return conn->connect_state &&
+ (conn->connect_state->tunnel_state != TUNNEL_COMPLETE);
+}
+
+static CURLcode connect_init(struct connectdata *conn, bool reinit)
+{
+ struct http_connect_state *s;
+ if(!reinit) {
+ DEBUGASSERT(!conn->connect_state);
+ s = calloc(1, sizeof(struct http_connect_state));
+ if(!s)
+ return CURLE_OUT_OF_MEMORY;
+ infof(conn->data, "allocate connect buffer!\n");
+ conn->connect_state = s;
+ }
+ else {
+ DEBUGASSERT(conn->connect_state);
+ s = conn->connect_state;
+ }
+ s->tunnel_state = TUNNEL_INIT;
+ s->keepon = TRUE;
+ s->line_start = s->connect_buffer;
+ s->ptr = s->line_start;
+ s->cl = 0;
+ return CURLE_OK;
+}
+
+static void connect_done(struct connectdata *conn)
+{
+ struct http_connect_state *s = conn->connect_state;
+ s->tunnel_state = TUNNEL_COMPLETE;
+ infof(conn->data, "CONNECT phase completed!\n");
+}
static CURLcode CONNECT(struct connectdata *conn,
int sockindex,
const char *hostname,
int remote_port)
{
- int subversion=0;
- struct Curl_easy *data=conn->data;
+ int subversion = 0;
+ struct Curl_easy *data = conn->data;
struct SingleRequest *k = &data->req;
CURLcode result;
curl_socket_t tunnelsocket = conn->sock[sockindex];
- curl_off_t cl=0;
bool closeConnection = FALSE;
- bool chunked_encoding = FALSE;
time_t check;
+ struct http_connect_state *s = conn->connect_state;
#define SELECT_OK 0
#define SELECT_ERROR 1
#define SELECT_TIMEOUT 2
- int error = SELECT_OK;
- if(conn->tunnel_state[sockindex] == TUNNEL_COMPLETE)
+ if(Curl_connect_complete(conn))
return CURLE_OK; /* CONNECT is already completed */
conn->bits.proxy_connect_closed = FALSE;
do {
- if(TUNNEL_INIT == conn->tunnel_state[sockindex]) {
+ if(TUNNEL_INIT == s->tunnel_state) {
/* BEGIN CONNECT PHASE */
char *host_port;
Curl_send_buffer *req_buffer;
@@ -196,8 +234,8 @@ static CURLcode CONNECT(struct connectdata *conn,
if(!result) {
char *host = NULL;
- const char *proxyconn="";
- const char *useragent="";
+ const char *proxyconn = "";
+ const char *useragent = "";
const char *http = (conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0) ?
"1.0" : "1.1";
bool ipv6_ip = conn->bits.ipv6_ip;
@@ -206,7 +244,7 @@ static CURLcode CONNECT(struct connectdata *conn,
/* the hostname may be different */
if(hostname != conn->host.name)
ipv6_ip = (strchr(hostname, ':') != NULL);
- hostheader= /* host:port with IPv6 support */
+ hostheader = /* host:port with IPv6 support */
aprintf("%s%s%s:%hu", ipv6_ip?"[":"", hostname, ipv6_ip?"]":"",
remote_port);
if(!hostheader) {
@@ -271,65 +309,46 @@ static CURLcode CONNECT(struct connectdata *conn,
if(result)
return result;
- conn->tunnel_state[sockindex] = TUNNEL_CONNECT;
+ s->tunnel_state = TUNNEL_CONNECT;
+ s->perline = 0;
} /* END CONNECT PHASE */
check = Curl_timeleft(data, NULL, TRUE);
if(check <= 0) {
failf(data, "Proxy CONNECT aborted due to timeout");
- return CURLE_RECV_ERROR;
+ return CURLE_OPERATION_TIMEDOUT;
}
if(!Curl_conn_data_pending(conn, sockindex))
/* return so we'll be called again polling-style */
return CURLE_OK;
- DEBUGF(infof(data, "Read response immediately from proxy CONNECT\n"));
/* at this point, the tunnel_connecting phase is over. */
{ /* READING RESPONSE PHASE */
- size_t nread; /* total size read */
- int perline; /* count bytes per line */
- int keepon=TRUE;
- ssize_t gotbytes;
- char *ptr;
- char *line_start;
+ int error = SELECT_OK;
- ptr = conn->connect_buffer;
- line_start = ptr;
+ while(s->keepon && !error) {
+ ssize_t gotbytes;
- nread = 0;
- perline = 0;
-
- while(nread < (size_t)CONNECT_BUFFER_SIZE && keepon && !error) {
- if(Curl_pgrsUpdate(conn))
- return CURLE_ABORTED_BY_CALLBACK;
-
- if(ptr >= &conn->connect_buffer[CONNECT_BUFFER_SIZE]) {
+ /* make sure we have space to read more data */
+ if(s->ptr >= &s->connect_buffer[CONNECT_BUFFER_SIZE]) {
failf(data, "CONNECT response too large!");
return CURLE_RECV_ERROR;
}
- check = Curl_timeleft(data, NULL, TRUE);
- if(check <= 0) {
- failf(data, "Proxy CONNECT aborted due to timeout");
- error = SELECT_TIMEOUT; /* already too little time */
- break;
- }
-
/* Read one byte at a time to avoid a race condition. Wait at most one
second before looping to ensure continuous pgrsUpdates. */
- result = Curl_read(conn, tunnelsocket, ptr, 1, &gotbytes);
- if(result == CURLE_AGAIN) {
- if(SOCKET_READABLE(tunnelsocket, check<1000L?check:1000) == -1) {
- error = SELECT_ERROR;
- failf(data, "Proxy CONNECT aborted due to select/poll error");
- break;
- }
- continue;
- }
+ result = Curl_read(conn, tunnelsocket, s->ptr, 1, &gotbytes);
+ if(result == CURLE_AGAIN)
+ /* socket buffer drained, return */
+ return CURLE_OK;
+
+ if(Curl_pgrsUpdate(conn))
+ return CURLE_ABORTED_BY_CALLBACK;
+
if(result) {
- keepon = FALSE;
+ s->keepon = FALSE;
break;
}
else if(gotbytes <= 0) {
@@ -343,24 +362,22 @@ static CURLcode CONNECT(struct connectdata *conn,
error = SELECT_ERROR;
failf(data, "Proxy CONNECT aborted");
}
- keepon = FALSE;
+ s->keepon = FALSE;
break;
}
- /* We got a byte of data */
- nread++;
- if(keepon > TRUE) {
+ if(s->keepon > TRUE) {
/* This means we are currently ignoring a response-body */
- nread = 0; /* make next read start over in the read buffer */
- ptr = conn->connect_buffer;
- if(cl) {
+ s->ptr = s->connect_buffer;
+ if(s->cl) {
/* A Content-Length based body: simply count down the counter
and make sure to break out of the loop when we're done! */
- cl--;
- if(cl <= 0) {
- keepon = FALSE;
+ s->cl--;
+ if(s->cl <= 0) {
+ s->keepon = FALSE;
+ s->tunnel_state = TUNNEL_COMPLETE;
break;
}
}
@@ -372,28 +389,29 @@ static CURLcode CONNECT(struct connectdata *conn,
/* now parse the chunked piece of data so that we can
properly tell when the stream ends */
- r = Curl_httpchunk_read(conn, ptr, 1, &tookcareof);
+ r = Curl_httpchunk_read(conn, s->ptr, 1, &tookcareof);
if(r == CHUNKE_STOP) {
/* we're done reading chunks! */
infof(data, "chunk reading DONE\n");
- keepon = FALSE;
+ s->keepon = FALSE;
/* we did the full CONNECT treatment, go COMPLETE */
- conn->tunnel_state[sockindex] = TUNNEL_COMPLETE;
+ s->tunnel_state = TUNNEL_COMPLETE;
}
}
continue;
}
- perline++; /* amount of bytes in this line so far */
+ s->perline++; /* amount of bytes in this line so far */
/* if this is not the end of a header line then continue */
- if(*ptr != 0x0a) {
- ptr++;
+ if(*s->ptr != 0x0a) {
+ s->ptr++;
continue;
}
/* convert from the network encoding */
- result = Curl_convert_from_network(data, line_start, perline);
+ result = Curl_convert_from_network(data, s->line_start,
+ (size_t)s->perline);
/* Curl_convert_from_network calls failf if unsuccessful */
if(result)
return result;
@@ -401,7 +419,7 @@ static CURLcode CONNECT(struct connectdata *conn,
/* output debug if that is requested */
if(data->set.verbose)
Curl_debug(data, CURLINFO_HEADER_IN,
- line_start, (size_t)perline, conn);
+ s->line_start, (size_t)s->perline, conn);
if(!data->set.suppress_connect_headers) {
/* send the header to the callback */
@@ -409,35 +427,34 @@ static CURLcode CONNECT(struct connectdata *conn,
if(data->set.include_header)
writetype |= CLIENTWRITE_BODY;
- result = Curl_client_write(conn, writetype, line_start, perline);
+ result = Curl_client_write(conn, writetype,
+ s->line_start, s->perline);
if(result)
return result;
}
- data->info.header_size += (long)perline;
- data->req.headerbytecount += (long)perline;
+ data->info.header_size += (long)s->perline;
+ data->req.headerbytecount += (long)s->perline;
/* Newlines are CRLF, so the CR is ignored as the line isn't
really terminated until the LF comes. Treat a following CR
as end-of-headers as well.*/
- if(('\r' == line_start[0]) ||
- ('\n' == line_start[0])) {
+ if(('\r' == s->line_start[0]) ||
+ ('\n' == s->line_start[0])) {
/* end of response-headers from the proxy */
- nread = 0; /* make next read start over in the read
- buffer */
- ptr = conn->connect_buffer;
+ s->ptr = s->connect_buffer;
if((407 == k->httpcode) && !data->state.authproblem) {
/* If we get a 407 response code with content length
when we have no auth problem, we must ignore the
whole response-body */
- keepon = 2;
+ s->keepon = 2;
- if(cl) {
+ if(s->cl) {
infof(data, "Ignore %" CURL_FORMAT_CURL_OFF_T
- " bytes of response-body\n", cl);
+ " bytes of response-body\n", s->cl);
}
- else if(chunked_encoding) {
+ else if(s->chunked_encoding) {
CHUNKcode r;
infof(data, "Ignore chunked response-body\n");
@@ -448,46 +465,46 @@ static CURLcode CONNECT(struct connectdata *conn,
function returns! */
k->ignorebody = TRUE;
- if(line_start[1] == '\n') {
+ if(s->line_start[1] == '\n') {
/* this can only be a LF if the letter at index 0
was a CR */
- line_start++;
+ s->line_start++;
}
/* now parse the chunked piece of data so that we can
properly tell when the stream ends */
- r = Curl_httpchunk_read(conn, line_start + 1, 1, &gotbytes);
+ r = Curl_httpchunk_read(conn, s->line_start + 1, 1, &gotbytes);
if(r == CHUNKE_STOP) {
/* we're done reading chunks! */
infof(data, "chunk reading DONE\n");
- keepon = FALSE;
- /* we did the full CONNECT treatment, go to
- COMPLETE */
- conn->tunnel_state[sockindex] = TUNNEL_COMPLETE;
+ s->keepon = FALSE;
+ /* we did the full CONNECT treatment, go to COMPLETE */
+ s->tunnel_state = TUNNEL_COMPLETE;
}
}
else {
/* without content-length or chunked encoding, we
can't keep the connection alive since the close is
the end signal so we bail out at once instead */
- keepon = FALSE;
+ s->keepon = FALSE;
}
}
else
- keepon = FALSE;
- /* we did the full CONNECT treatment, go to COMPLETE */
- conn->tunnel_state[sockindex] = TUNNEL_COMPLETE;
+ s->keepon = FALSE;
+ if(!s->cl)
+ /* we did the full CONNECT treatment, go to COMPLETE */
+ s->tunnel_state = TUNNEL_COMPLETE;
continue;
}
- line_start[perline] = 0; /* zero terminate the buffer */
- if((checkprefix("WWW-Authenticate:", line_start) &&
+ s->line_start[s->perline] = 0; /* zero terminate the buffer */
+ if((checkprefix("WWW-Authenticate:", s->line_start) &&
(401 == k->httpcode)) ||
- (checkprefix("Proxy-authenticate:", line_start) &&
+ (checkprefix("Proxy-authenticate:", s->line_start) &&
(407 == k->httpcode))) {
bool proxy = (k->httpcode == 407) ? TRUE : FALSE;
- char *auth = Curl_copy_header_value(line_start);
+ char *auth = Curl_copy_header_value(s->line_start);
if(!auth)
return CURLE_OUT_OF_MEMORY;
@@ -498,7 +515,7 @@ static CURLcode CONNECT(struct connectdata *conn,
if(result)
return result;
}
- else if(checkprefix("Content-Length:", line_start)) {
+ else if(checkprefix("Content-Length:", s->line_start)) {
if(k->httpcode/100 == 2) {
/* A client MUST ignore any Content-Length or Transfer-Encoding
header fields received in a successful response to CONNECT.
@@ -507,13 +524,13 @@ static CURLcode CONNECT(struct connectdata *conn,
k->httpcode);
}
else {
- cl = curlx_strtoofft(line_start +
- strlen("Content-Length:"), NULL, 10);
+ (void)curlx_strtoofft(s->line_start +
+ strlen("Content-Length:"), NULL, 10, &s->cl);
}
}
- else if(Curl_compareheader(line_start, "Connection:", "close"))
+ else if(Curl_compareheader(s->line_start, "Connection:", "close"))
closeConnection = TRUE;
- else if(checkprefix("Transfer-Encoding:", line_start)) {
+ else if(checkprefix("Transfer-Encoding:", s->line_start)) {
if(k->httpcode/100 == 2) {
/* A client MUST ignore any Content-Length or Transfer-Encoding
header fields received in a successful response to CONNECT.
@@ -521,26 +538,27 @@ static CURLcode CONNECT(struct connectdata *conn,
infof(data, "Ignoring Transfer-Encoding in "
"CONNECT %03d response\n", k->httpcode);
}
- else if(Curl_compareheader(line_start,
+ else if(Curl_compareheader(s->line_start,
"Transfer-Encoding:", "chunked")) {
infof(data, "CONNECT responded chunked\n");
- chunked_encoding = TRUE;
+ s->chunked_encoding = TRUE;
/* init our chunky engine */
Curl_httpchunk_init(conn);
}
}
- else if(Curl_compareheader(line_start, "Proxy-Connection:", "close"))
+ else if(Curl_compareheader(s->line_start,
+ "Proxy-Connection:", "close"))
closeConnection = TRUE;
- else if(2 == sscanf(line_start, "HTTP/1.%d %d",
+ else if(2 == sscanf(s->line_start, "HTTP/1.%d %d",
&subversion,
&k->httpcode)) {
/* store the HTTP code from the proxy */
data->info.httpproxycode = k->httpcode;
}
- perline = 0; /* line starts over here */
- ptr = conn->connect_buffer;
- line_start = ptr;
+ s->perline = 0; /* line starts over here */
+ s->ptr = s->connect_buffer;
+ s->line_start = s->ptr;
} /* while there's buffer left and loop is requested */
if(Curl_pgrsUpdate(conn))
@@ -549,7 +567,7 @@ static CURLcode CONNECT(struct connectdata *conn,
if(error)
return CURLE_RECV_ERROR;
- if(data->info.httpproxycode != 200) {
+ if(data->info.httpproxycode/100 != 2) {
/* Deal with the possibly already received authenticate
headers. 'newurl' is set to a new URL if we must loop. */
result = Curl_http_auth_act(conn);
@@ -574,19 +592,17 @@ static CURLcode CONNECT(struct connectdata *conn,
/* If we are supposed to continue and request a new URL, which basically
* means the HTTP authentication is still going on so if the tunnel
* is complete we start over in INIT state */
- if(data->req.newurl &&
- (TUNNEL_COMPLETE == conn->tunnel_state[sockindex])) {
- conn->tunnel_state[sockindex] = TUNNEL_INIT;
- infof(data, "TUNNEL_STATE switched to: %d\n",
- conn->tunnel_state[sockindex]);
+ if(data->req.newurl && (TUNNEL_COMPLETE == s->tunnel_state)) {
+ connect_init(conn, TRUE); /* reinit */
}
} while(data->req.newurl);
- if(200 != data->req.httpcode) {
+ if(data->info.httpproxycode/100 != 2) {
if(closeConnection && data->req.newurl) {
conn->bits.proxy_connect_closed = TRUE;
infof(data, "Connect me again please\n");
+ connect_done(conn);
}
else {
free(data->req.newurl);
@@ -598,7 +614,7 @@ static CURLcode CONNECT(struct connectdata *conn,
}
/* to back to init state */
- conn->tunnel_state[sockindex] = TUNNEL_INIT;
+ s->tunnel_state = TUNNEL_INIT;
if(conn->bits.proxy_connect_closed)
/* this is not an error, just part of the connection negotiation */
@@ -608,7 +624,7 @@ static CURLcode CONNECT(struct connectdata *conn,
return CURLE_RECV_ERROR;
}
- conn->tunnel_state[sockindex] = TUNNEL_COMPLETE;
+ s->tunnel_state = TUNNEL_COMPLETE;
/* If a proxy-authorization header was used for the proxy, then we should
make sure that it isn't accidentally used for the document request
@@ -618,13 +634,24 @@ static CURLcode CONNECT(struct connectdata *conn,
data->state.authproxy.done = TRUE;
- infof(data, "Proxy replied OK to CONNECT request\n");
+ infof(data, "Proxy replied %d to CONNECT request\n",
+ data->info.httpproxycode);
data->req.ignorebody = FALSE; /* put it (back) to non-ignore state */
conn->bits.rewindaftersend = FALSE; /* make sure this isn't set for the
document request */
return CURLE_OK;
}
+void Curl_connect_free(struct Curl_easy *data)
+{
+ struct connectdata *conn = data->easy_conn;
+ struct http_connect_state *s = conn->connect_state;
+ if(s) {
+ free(s);
+ conn->connect_state = NULL;
+ }
+}
+
/*
* Curl_proxyCONNECT() requires that we're connected to a HTTP proxy. This
* function will issue the necessary commands to get a seamless tunnel through
@@ -637,20 +664,23 @@ CURLcode Curl_proxyCONNECT(struct connectdata *conn,
int remote_port)
{
CURLcode result;
- if(TUNNEL_INIT == conn->tunnel_state[sockindex]) {
- if(!conn->connect_buffer) {
- conn->connect_buffer = malloc(CONNECT_BUFFER_SIZE);
- if(!conn->connect_buffer)
- return CURLE_OUT_OF_MEMORY;
- }
+ if(!conn->connect_state) {
+ result = connect_init(conn, FALSE);
+ if(result)
+ return result;
}
result = CONNECT(conn, sockindex, hostname, remote_port);
- if(result || (TUNNEL_COMPLETE == conn->tunnel_state[sockindex]))
- Curl_safefree(conn->connect_buffer);
+ if(result || Curl_connect_complete(conn))
+ connect_done(conn);
return result;
}
+#else
+void Curl_connect_free(struct Curl_easy *data)
+{
+ (void)data;
+}
#endif /* CURL_DISABLE_PROXY */
diff --git a/Utilities/cmcurl/lib/http_proxy.h b/Utilities/cmcurl/lib/http_proxy.h
index cbb1ab421..e19fa859a 100644
--- a/Utilities/cmcurl/lib/http_proxy.h
+++ b/Utilities/cmcurl/lib/http_proxy.h
@@ -22,6 +22,9 @@
*
***************************************************************************/
+#include "curl_setup.h"
+#include "urldata.h"
+
#if !defined(CURL_DISABLE_PROXY) && !defined(CURL_DISABLE_HTTP)
/* ftp can use this as well */
CURLcode Curl_proxyCONNECT(struct connectdata *conn,
@@ -33,9 +36,16 @@ CURLcode Curl_proxyCONNECT(struct connectdata *conn,
CURLcode Curl_proxy_connect(struct connectdata *conn, int sockindex);
+bool Curl_connect_complete(struct connectdata *conn);
+bool Curl_connect_ongoing(struct connectdata *conn);
+
#else
#define Curl_proxyCONNECT(x,y,z,w) CURLE_NOT_BUILT_IN
#define Curl_proxy_connect(x,y) CURLE_OK
+#define Curl_connect_complete(x) CURLE_OK
+#define Curl_connect_ongoing(x) FALSE
#endif
+void Curl_connect_free(struct Curl_easy *data);
+
#endif /* HEADER_CURL_HTTP_PROXY_H */
diff --git a/Utilities/cmcurl/lib/if2ip.c b/Utilities/cmcurl/lib/if2ip.c
index 4de81be60..ce38ea117 100644
--- a/Utilities/cmcurl/lib/if2ip.c
+++ b/Utilities/cmcurl/lib/if2ip.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -71,6 +71,8 @@ unsigned int Curl_ipv6_scope(const struct sockaddr *sa)
const unsigned char *b = sa6->sin6_addr.s6_addr;
unsigned short w = (unsigned short) ((b[0] << 8) | b[1]);
+ if((b[0] & 0xFE) == 0xFC) /* Handle ULAs */
+ return IPV6_SCOPE_UNIQUELOCAL;
switch(w & 0xFFC0) {
case 0xFE80:
return IPV6_SCOPE_LINKLOCAL;
@@ -101,7 +103,7 @@ bool Curl_if_is_interface_name(const char *interf)
struct ifaddrs *iface, *head;
if(getifaddrs(&head) >= 0) {
- for(iface=head; iface != NULL; iface=iface->ifa_next) {
+ for(iface = head; iface != NULL; iface = iface->ifa_next) {
if(strcasecompare(iface->ifa_name, interf)) {
result = TRUE;
break;
@@ -121,15 +123,15 @@ if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
#ifndef ENABLE_IPV6
(void) remote_scope;
-
-#ifndef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
- (void) remote_scope_id;
#endif
+#if !defined(HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID) || \
+ !defined(ENABLE_IPV6)
+ (void) remote_scope_id;
#endif
if(getifaddrs(&head) >= 0) {
- for(iface = head; iface != NULL; iface=iface->ifa_next) {
+ for(iface = head; iface != NULL; iface = iface->ifa_next) {
if(iface->ifa_addr != NULL) {
if(iface->ifa_addr->sa_family == af) {
if(strcasecompare(iface->ifa_name, interf)) {
@@ -228,7 +230,7 @@ if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope,
return IF2IP_NOT_FOUND;
memset(&req, 0, sizeof(req));
- memcpy(req.ifr_name, interf, len+1);
+ memcpy(req.ifr_name, interf, len + 1);
req.ifr_addr.sa_family = AF_INET;
if(ioctl(dummy, SIOCGIFADDR, &req) < 0) {
diff --git a/Utilities/cmcurl/lib/if2ip.h b/Utilities/cmcurl/lib/if2ip.h
index f3a7ff0b2..a90e66216 100644
--- a/Utilities/cmcurl/lib/if2ip.h
+++ b/Utilities/cmcurl/lib/if2ip.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -27,7 +27,8 @@
#define IPV6_SCOPE_GLOBAL 0 /* Global scope. */
#define IPV6_SCOPE_LINKLOCAL 1 /* Link-local scope. */
#define IPV6_SCOPE_SITELOCAL 2 /* Site-local scope (deprecated). */
-#define IPV6_SCOPE_NODELOCAL 3 /* Loopback. */
+#define IPV6_SCOPE_UNIQUELOCAL 3 /* Unique local */
+#define IPV6_SCOPE_NODELOCAL 4 /* Loopback. */
unsigned int Curl_ipv6_scope(const struct sockaddr *sa);
diff --git a/Utilities/cmcurl/lib/imap.c b/Utilities/cmcurl/lib/imap.c
index b528f77d9..954d18f37 100644
--- a/Utilities/cmcurl/lib/imap.c
+++ b/Utilities/cmcurl/lib/imap.c
@@ -68,6 +68,7 @@
#include "http.h" /* for HTTP proxy tunnel stuff */
#include "socks.h"
#include "imap.h"
+#include "mime.h"
#include "strtoofft.h"
#include "strcase.h"
#include "vtls/vtls.h"
@@ -128,6 +129,7 @@ const struct Curl_handler Curl_handler_imap = {
ZERO_NULL, /* perform_getsock */
imap_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_IMAP, /* defport */
CURLPROTO_IMAP, /* protocol */
PROTOPT_CLOSEACTION| /* flags */
@@ -154,69 +156,22 @@ const struct Curl_handler Curl_handler_imaps = {
ZERO_NULL, /* perform_getsock */
imap_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_IMAPS, /* defport */
CURLPROTO_IMAPS, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_SSL /* flags */
};
#endif
-#ifndef CURL_DISABLE_HTTP
-/*
- * HTTP-proxyed IMAP protocol handler.
- */
-
-static const struct Curl_handler Curl_handler_imap_proxy = {
- "IMAP", /* scheme */
- Curl_http_setup_conn, /* setup_connection */
- Curl_http, /* do_it */
- Curl_http_done, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
- PORT_IMAP, /* defport */
- CURLPROTO_HTTP, /* protocol */
- PROTOPT_NONE /* flags */
-};
-
-#ifdef USE_SSL
-/*
- * HTTP-proxyed IMAPS protocol handler.
- */
-
-static const struct Curl_handler Curl_handler_imaps_proxy = {
- "IMAPS", /* scheme */
- Curl_http_setup_conn, /* setup_connection */
- Curl_http, /* do_it */
- Curl_http_done, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
- PORT_IMAPS, /* defport */
- CURLPROTO_HTTP, /* protocol */
- PROTOPT_NONE /* flags */
-};
-#endif
-#endif
+#define IMAP_RESP_OK 1
+#define IMAP_RESP_NOT_OK 2
+#define IMAP_RESP_PREAUTH 3
/* SASL parameters for the imap protocol */
static const struct SASLproto saslimap = {
"imap", /* The service name */
'+', /* Code received when continuation is expected */
- 'O', /* Code to receive upon authentication success */
+ IMAP_RESP_OK, /* Code to receive upon authentication success */
0, /* Maximum initial response length (no max) */
imap_perform_authenticate, /* Send authentication command */
imap_continue_authenticate, /* Send authentication continuation */
@@ -299,15 +254,11 @@ static bool imap_endofresp(struct connectdata *conn, char *line, size_t len,
len -= id_len + 1;
if(len >= 2 && !memcmp(line, "OK", 2))
- *resp = 'O';
- else if(len >= 2 && !memcmp(line, "NO", 2))
- *resp = 'N';
- else if(len >= 3 && !memcmp(line, "BAD", 3))
- *resp = 'B';
- else {
- failf(conn->data, "Bad tagged response");
- *resp = -1;
- }
+ *resp = IMAP_RESP_OK;
+ else if(len >= 7 && !memcmp(line, "PREAUTH", 7))
+ *resp = IMAP_RESP_PREAUTH;
+ else
+ *resp = IMAP_RESP_NOT_OK;
return TRUE;
}
@@ -613,9 +564,10 @@ static CURLcode imap_perform_authentication(struct connectdata *conn)
struct imap_conn *imapc = &conn->proto.imapc;
saslprogress progress;
- /* Check we have enough data to authenticate with and end the
- connect phase if we don't */
- if(!Curl_sasl_can_authenticate(&imapc->sasl, conn)) {
+ /* Check if already authenticated OR if there is enough data to authenticate
+ with and end the connect phase if we don't */
+ if(imapc->preauth ||
+ !Curl_sasl_can_authenticate(&imapc->sasl, conn)) {
state(conn, IMAP_STOP);
return result;
}
@@ -757,18 +709,48 @@ static CURLcode imap_perform_fetch(struct connectdata *conn)
static CURLcode imap_perform_append(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
- struct IMAP *imap = conn->data->req.protop;
+ struct Curl_easy *data = conn->data;
+ struct IMAP *imap = data->req.protop;
char *mailbox;
/* Check we have a mailbox */
if(!imap->mailbox) {
- failf(conn->data, "Cannot APPEND without a mailbox.");
+ failf(data, "Cannot APPEND without a mailbox.");
return CURLE_URL_MALFORMAT;
}
+ /* Prepare the mime data if some. */
+ if(data->set.mimepost.kind != MIMEKIND_NONE) {
+ /* Use the whole structure as data. */
+ data->set.mimepost.flags &= ~MIME_BODY_ONLY;
+
+ /* Add external headers and mime version. */
+ curl_mime_headers(&data->set.mimepost, data->set.headers, 0);
+ result = Curl_mime_prepare_headers(&data->set.mimepost, NULL,
+ NULL, MIMESTRATEGY_MAIL);
+
+ if(!result)
+ if(!Curl_checkheaders(conn, "Mime-Version"))
+ result = Curl_mime_add_header(&data->set.mimepost.curlheaders,
+ "Mime-Version: 1.0");
+
+ /* Make sure we will read the entire mime structure. */
+ if(!result)
+ result = Curl_mime_rewind(&data->set.mimepost);
+
+ if(result)
+ return result;
+
+ data->state.infilesize = Curl_mime_size(&data->set.mimepost);
+
+ /* Read from mime structure. */
+ data->state.fread_func = (curl_read_callback) Curl_mime_read;
+ data->state.in = (void *) &data->set.mimepost;
+ }
+
/* Check we know the size of the upload */
- if(conn->data->state.infilesize < 0) {
- failf(conn->data, "Cannot APPEND with unknown input file size\n");
+ if(data->state.infilesize < 0) {
+ failf(data, "Cannot APPEND with unknown input file size\n");
return CURLE_UPLOAD_FAILED;
}
@@ -779,7 +761,7 @@ static CURLcode imap_perform_append(struct connectdata *conn)
/* Send the APPEND command */
result = imap_sendf(conn, "APPEND %s (\\Seen) {%" CURL_FORMAT_CURL_OFF_T "}",
- mailbox, conn->data->state.infilesize);
+ mailbox, data->state.infilesize);
free(mailbox);
@@ -839,19 +821,21 @@ static CURLcode imap_state_servergreet_resp(struct connectdata *conn,
int imapcode,
imapstate instate)
{
- CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
-
(void)instate; /* no use for this yet */
- if(imapcode != 'O') {
+ if(imapcode == IMAP_RESP_PREAUTH) {
+ /* PREAUTH */
+ struct imap_conn *imapc = &conn->proto.imapc;
+ imapc->preauth = TRUE;
+ infof(data, "PREAUTH connection, already authenticated!\n");
+ }
+ else if(imapcode != IMAP_RESP_OK) {
failf(data, "Got unexpected imap-server response");
- result = CURLE_WEIRD_SERVER_REPLY;
+ return CURLE_WEIRD_SERVER_REPLY;
}
- else
- result = imap_perform_capability(conn);
- return result;
+ return imap_perform_capability(conn);
}
/* For CAPABILITY responses */
@@ -918,7 +902,7 @@ static CURLcode imap_state_capability_resp(struct connectdata *conn,
line += wordlen;
}
}
- else if(imapcode == 'O') {
+ else if(imapcode == IMAP_RESP_OK) {
if(data->set.use_ssl && !conn->ssl[FIRSTSOCKET].use) {
/* We don't have a SSL/TLS connection yet, but SSL is requested */
if(imapc->tls_supported)
@@ -951,7 +935,7 @@ static CURLcode imap_state_starttls_resp(struct connectdata *conn,
(void)instate; /* no use for this yet */
- if(imapcode != 'O') {
+ if(imapcode != IMAP_RESP_OK) {
if(data->set.use_ssl != CURLUSESSL_TRY) {
failf(data, "STARTTLS denied");
result = CURLE_USE_SSL_FAILED;
@@ -1009,7 +993,7 @@ static CURLcode imap_state_login_resp(struct connectdata *conn,
(void)instate; /* no use for this yet */
- if(imapcode != 'O') {
+ if(imapcode != IMAP_RESP_OK) {
failf(data, "Access denied. %c", imapcode);
result = CURLE_LOGIN_DENIED;
}
@@ -1037,7 +1021,7 @@ static CURLcode imap_state_listsearch_resp(struct connectdata *conn,
result = Curl_client_write(conn, CLIENTWRITE_BODY, line, len + 1);
line[len] = '\0';
}
- else if(imapcode != 'O')
+ else if(imapcode != IMAP_RESP_OK)
result = CURLE_QUOTE_ERROR; /* TODO: Fix error code */
else
/* End of DO phase */
@@ -1066,7 +1050,7 @@ static CURLcode imap_state_select_resp(struct connectdata *conn, int imapcode,
imapc->mailbox_uidvalidity = strdup(tmp);
}
}
- else if(imapcode == 'O') {
+ else if(imapcode == IMAP_RESP_OK) {
/* Check if the UIDVALIDITY has been specified and matches */
if(imap->uidvalidity && imapc->mailbox_uidvalidity &&
strcmp(imap->uidvalidity, imapc->mailbox_uidvalidity)) {
@@ -1120,10 +1104,11 @@ static CURLcode imap_state_fetch_resp(struct connectdata *conn, int imapcode,
if(*ptr == '{') {
char *endptr;
- size = curlx_strtoofft(ptr + 1, &endptr, 10);
- if(endptr - ptr > 1 && endptr[0] == '}' &&
- endptr[1] == '\r' && endptr[2] == '\0')
- parsed = TRUE;
+ if(!curlx_strtoofft(ptr + 1, &endptr, 10, &size)) {
+ if(endptr - ptr > 1 && endptr[0] == '}' &&
+ endptr[1] == '\r' && endptr[2] == '\0')
+ parsed = TRUE;
+ }
}
if(parsed) {
@@ -1197,7 +1182,7 @@ static CURLcode imap_state_fetch_final_resp(struct connectdata *conn,
(void)instate; /* No use for this yet */
- if(imapcode != 'O')
+ if(imapcode != IMAP_RESP_OK)
result = CURLE_WEIRD_SERVER_REPLY;
else
/* End of DONE phase */
@@ -1241,7 +1226,7 @@ static CURLcode imap_state_append_final_resp(struct connectdata *conn,
(void)instate; /* No use for this yet */
- if(imapcode != 'O')
+ if(imapcode != IMAP_RESP_OK)
result = CURLE_UPLOAD_FAILED;
else
/* End of DONE phase */
@@ -1469,9 +1454,10 @@ static CURLcode imap_done(struct connectdata *conn, CURLcode status,
result = status; /* use the already set error code */
}
else if(!data->set.connect_only && !imap->custom &&
- (imap->uid || data->set.upload)) {
+ (imap->uid || data->set.upload ||
+ data->set.mimepost.kind != MIMEKIND_NONE)) {
/* Handle responses after FETCH or APPEND transfer has finished */
- if(!data->set.upload)
+ if(!data->set.upload && data->set.mimepost.kind == MIMEKIND_NONE)
state(conn, IMAP_FETCH_FINAL);
else {
/* End the APPEND command first by sending an empty line */
@@ -1541,7 +1527,7 @@ static CURLcode imap_perform(struct connectdata *conn, bool *connected,
selected = TRUE;
/* Start the first command in the DO phase */
- if(conn->data->set.upload)
+ if(conn->data->set.upload || data->set.mimepost.kind != MIMEKIND_NONE)
/* APPEND can be executed directly */
result = imap_perform_append(conn);
else if(imap->custom && (selected || !imap->mailbox))
@@ -1715,31 +1701,6 @@ static CURLcode imap_setup_connection(struct connectdata *conn)
/* Clear the TLS upgraded flag */
conn->tls_upgraded = FALSE;
-
- /* Set up the proxy if necessary */
- if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
- /* Unless we have asked to tunnel IMAP operations through the proxy, we
- switch and use HTTP operations only */
-#ifndef CURL_DISABLE_HTTP
- if(conn->handler == &Curl_handler_imap)
- conn->handler = &Curl_handler_imap_proxy;
- else {
-#ifdef USE_SSL
- conn->handler = &Curl_handler_imaps_proxy;
-#else
- failf(data, "IMAPS not supported!");
- return CURLE_UNSUPPORTED_PROTOCOL;
-#endif
- }
-
- /* set it up as an HTTP connection instead */
- return conn->handler->setup_connection(conn);
-#else
- failf(data, "IMAP over http proxy requires HTTP support built-in!");
- return CURLE_UNSUPPORTED_PROTOCOL;
-#endif
- }
-
data->state.path++; /* don't include the initial slash */
return CURLE_OK;
@@ -1836,7 +1797,7 @@ static char *imap_atom(const char *str, bool escape_only)
return strdup(str);
/* Calculate the new string length */
- newlen = strlen(str) + backsp_count + quote_count + (others_exists ? 2 : 0);
+ newlen = strlen(str) + backsp_count + quote_count + (escape_only ? 0 : 2);
/* Allocate the new string */
newstr = (char *) malloc((newlen + 1) * sizeof(char));
@@ -1845,7 +1806,7 @@ static char *imap_atom(const char *str, bool escape_only)
/* Surround the string in quotes if necessary */
p2 = newstr;
- if(others_exists) {
+ if(!escape_only) {
newstr[0] = '"';
newstr[newlen - 1] = '"';
p2++;
diff --git a/Utilities/cmcurl/lib/imap.h b/Utilities/cmcurl/lib/imap.h
index 5e0e228f5..9fc4ff5a3 100644
--- a/Utilities/cmcurl/lib/imap.h
+++ b/Utilities/cmcurl/lib/imap.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 2009 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 2009 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -71,6 +71,7 @@ struct imap_conn {
struct pingpong pp;
imapstate state; /* Always use imap.c:state() to change state! */
bool ssldone; /* Is connect() over SSL done? */
+ bool preauth; /* Is this connection PREAUTH? */
struct SASL sasl; /* SASL-related parameters */
unsigned int preftype; /* Preferred authentication type */
int cmdid; /* Last used command ID */
diff --git a/Utilities/cmcurl/lib/inet_ntop.c b/Utilities/cmcurl/lib/inet_ntop.c
index 9afbdbb32..fb91a505d 100644
--- a/Utilities/cmcurl/lib/inet_ntop.c
+++ b/Utilities/cmcurl/lib/inet_ntop.c
@@ -63,7 +63,7 @@ static char *inet_ntop4 (const unsigned char *src, char *dst, size_t size)
len = strlen(tmp);
if(len == 0 || len >= size) {
- SET_ERRNO(ENOSPC);
+ errno = ENOSPC;
return (NULL);
}
strcpy(dst, tmp);
@@ -141,8 +141,8 @@ static char *inet_ntop6 (const unsigned char *src, char *dst, size_t size)
*/
if(i == 6 && best.base == 0 &&
(best.len == 6 || (best.len == 5 && words[5] == 0xffff))) {
- if(!inet_ntop4(src+12, tp, sizeof(tmp) - (tp - tmp))) {
- SET_ERRNO(ENOSPC);
+ if(!inet_ntop4(src + 12, tp, sizeof(tmp) - (tp - tmp))) {
+ errno = ENOSPC;
return (NULL);
}
tp += strlen(tp);
@@ -160,7 +160,7 @@ static char *inet_ntop6 (const unsigned char *src, char *dst, size_t size)
/* Check for overflow, copy, and we're done.
*/
if((size_t)(tp - tmp) > size) {
- SET_ERRNO(ENOSPC);
+ errno = ENOSPC;
return (NULL);
}
strcpy(dst, tmp);
@@ -177,8 +177,8 @@ static char *inet_ntop6 (const unsigned char *src, char *dst, size_t size)
*
* On Windows we store the error in the thread errno, not
* in the winsock error code. This is to avoid losing the
- * actual last winsock error. So use macro ERRNO to fetch the
- * errno this function sets when returning NULL, not SOCKERRNO.
+ * actual last winsock error. So when this function returns
+ * NULL, check errno not SOCKERRNO.
*/
char *Curl_inet_ntop(int af, const void *src, char *buf, size_t size)
{
@@ -190,7 +190,7 @@ char *Curl_inet_ntop(int af, const void *src, char *buf, size_t size)
return inet_ntop6((const unsigned char *)src, buf, size);
#endif
default:
- SET_ERRNO(EAFNOSUPPORT);
+ errno = EAFNOSUPPORT;
return NULL;
}
}
diff --git a/Utilities/cmcurl/lib/inet_pton.c b/Utilities/cmcurl/lib/inet_pton.c
index 475f44abc..fef9610d1 100644
--- a/Utilities/cmcurl/lib/inet_pton.c
+++ b/Utilities/cmcurl/lib/inet_pton.c
@@ -57,8 +57,8 @@ static int inet_pton6(const char *src, unsigned char *dst);
* notice:
* On Windows we store the error in the thread errno, not
* in the winsock error code. This is to avoid losing the
- * actual last winsock error. So use macro ERRNO to fetch the
- * errno this function sets when returning (-1), not SOCKERRNO.
+ * actual last winsock error. So when this function returns
+ * -1, check errno not SOCKERRNO.
* author:
* Paul Vixie, 1996.
*/
@@ -73,7 +73,7 @@ Curl_inet_pton(int af, const char *src, void *dst)
return (inet_pton6(src, (unsigned char *)dst));
#endif
default:
- SET_ERRNO(EAFNOSUPPORT);
+ errno = EAFNOSUPPORT;
return (-1);
}
/* NOTREACHED */
diff --git a/Utilities/cmcurl/lib/inet_pton.h b/Utilities/cmcurl/lib/inet_pton.h
index 9188d9598..e216f4efa 100644
--- a/Utilities/cmcurl/lib/inet_pton.h
+++ b/Utilities/cmcurl/lib/inet_pton.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2005, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -29,6 +29,9 @@ int Curl_inet_pton(int, const char *, void *);
#ifdef HAVE_INET_PTON
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
+#elif defined(HAVE_WS2TCPIP_H)
+/* inet_pton() exists in Vista or later */
+#include <ws2tcpip.h>
#endif
#define Curl_inet_pton(x,y,z) inet_pton(x,y,z)
#endif
diff --git a/Utilities/cmcurl/lib/krb5.c b/Utilities/cmcurl/lib/krb5.c
index 69a35979a..af25e9204 100644
--- a/Utilities/cmcurl/lib/krb5.c
+++ b/Utilities/cmcurl/lib/krb5.c
@@ -1,6 +1,6 @@
/* GSSAPI/krb5 support for FTP - loosely based on old krb4.c
*
- * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan
+ * Copyright (c) 1995, 1996, 1997, 1998, 1999 Kungliga Tekniska Högskolan
* (Royal Institute of Technology, Stockholm, Sweden).
* Copyright (c) 2004 - 2016 Daniel Stenberg
* All rights reserved.
diff --git a/Utilities/cmcurl/lib/ldap.c b/Utilities/cmcurl/lib/ldap.c
index 79e84d94e..040641cf8 100644
--- a/Utilities/cmcurl/lib/ldap.c
+++ b/Utilities/cmcurl/lib/ldap.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -150,6 +150,7 @@ const struct Curl_handler Curl_handler_ldap = {
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_LDAP, /* defport */
CURLPROTO_LDAP, /* protocol */
PROTOPT_NONE /* flags */
@@ -175,6 +176,7 @@ const struct Curl_handler Curl_handler_ldaps = {
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_LDAPS, /* defport */
CURLPROTO_LDAPS, /* protocol */
PROTOPT_SSL /* flags */
@@ -233,7 +235,6 @@ static int ldap_win_bind(struct connectdata *conn, LDAP *server,
const char *user, const char *passwd)
{
int rc = LDAP_INVALID_CREDENTIALS;
- ULONG method = LDAP_AUTH_SIMPLE;
PTCHAR inuser = NULL;
PTCHAR inpass = NULL;
@@ -242,7 +243,7 @@ static int ldap_win_bind(struct connectdata *conn, LDAP *server,
inuser = Curl_convert_UTF8_to_tchar((char *) user);
inpass = Curl_convert_UTF8_to_tchar((char *) passwd);
- rc = ldap_bind_s(server, inuser, inpass, method);
+ rc = ldap_simple_bind_s(server, inuser, inpass);
Curl_unicodefree(inuser);
Curl_unicodefree(inpass);
@@ -266,7 +267,7 @@ static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
LDAPMessage *ldapmsg = NULL;
LDAPMessage *entryIterator;
int num = 0;
- struct Curl_easy *data=conn->data;
+ struct Curl_easy *data = conn->data;
int ldap_proto = LDAP_VERSION3;
int ldap_ssl = 0;
char *val_b64 = NULL;
diff --git a/Utilities/cmcurl/lib/memdebug.c b/Utilities/cmcurl/lib/memdebug.c
index 2b8808ab0..0eb249ce9 100644
--- a/Utilities/cmcurl/lib/memdebug.c
+++ b/Utilities/cmcurl/lib/memdebug.c
@@ -115,7 +115,8 @@ void curl_memdebug(const char *logname)
logfile = stderr;
#ifdef MEMDEBUG_LOG_SYNC
/* Flush the log file after every line so the log isn't lost in a crash */
- setbuf(logfile, (char *)NULL);
+ if(logfile)
+ setbuf(logfile, (char *)NULL);
#endif
}
}
@@ -146,7 +147,7 @@ static bool countcheck(const char *func, int line, const char *source)
source, line, func);
fflush(logfile); /* because it might crash now */
}
- SET_ERRNO(ENOMEM);
+ errno = ENOMEM;
return TRUE; /* RETURN ERROR! */
}
else
@@ -169,7 +170,7 @@ void *curl_domalloc(size_t wantedsize, int line, const char *source)
return NULL;
/* alloc at least 64 bytes */
- size = sizeof(struct memdebug)+wantedsize;
+ size = sizeof(struct memdebug) + wantedsize;
mem = (Curl_cmalloc)(size);
if(mem) {
@@ -224,9 +225,9 @@ char *curl_dostrdup(const char *str, int line, const char *source)
if(countcheck("strdup", line, source))
return NULL;
- len=strlen(str)+1;
+ len = strlen(str) + 1;
- mem=curl_domalloc(len, 0, NULL); /* NULL prevents logging */
+ mem = curl_domalloc(len, 0, NULL); /* NULL prevents logging */
if(mem)
memcpy(mem, str, len);
@@ -268,9 +269,9 @@ wchar_t *curl_dowcsdup(const wchar_t *str, int line, const char *source)
void *curl_dorealloc(void *ptr, size_t wantedsize,
int line, const char *source)
{
- struct memdebug *mem=NULL;
+ struct memdebug *mem = NULL;
- size_t size = sizeof(struct memdebug)+wantedsize;
+ size_t size = sizeof(struct memdebug) + wantedsize;
DEBUGASSERT(wantedsize != 0);
@@ -406,7 +407,7 @@ void curl_mark_sclose(curl_socket_t sockfd, int line, const char *source)
/* this is our own defined way to close sockets on *ALL* platforms */
int curl_sclose(curl_socket_t sockfd, int line, const char *source)
{
- int res=sclose(sockfd);
+ int res = sclose(sockfd);
curl_mark_sclose(sockfd, line, source);
return res;
}
@@ -414,7 +415,7 @@ int curl_sclose(curl_socket_t sockfd, int line, const char *source)
FILE *curl_fopen(const char *file, const char *mode,
int line, const char *source)
{
- FILE *res=fopen(file, mode);
+ FILE *res = fopen(file, mode);
if(source)
curl_memlog("FILE %s:%d fopen(\"%s\",\"%s\") = %p\n",
@@ -427,7 +428,7 @@ FILE *curl_fopen(const char *file, const char *mode,
FILE *curl_fdopen(int filedes, const char *mode,
int line, const char *source)
{
- FILE *res=fdopen(filedes, mode);
+ FILE *res = fdopen(filedes, mode);
if(source)
curl_memlog("FILE %s:%d fdopen(\"%d\",\"%s\") = %p\n",
@@ -443,7 +444,7 @@ int curl_fclose(FILE *file, int line, const char *source)
DEBUGASSERT(file != NULL);
- res=fclose(file);
+ res = fclose(file);
if(source)
curl_memlog("FILE %s:%d fclose(%p)\n",
diff --git a/Utilities/cmcurl/lib/mime.c b/Utilities/cmcurl/lib/mime.c
new file mode 100644
index 000000000..496f5e6fb
--- /dev/null
+++ b/Utilities/cmcurl/lib/mime.c
@@ -0,0 +1,1860 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl_setup.h"
+
+#include <curl/curl.h>
+
+#include "mime.h"
+#include "non-ascii.h"
+
+#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \
+ !defined(CURL_DISABLE_IMAP)
+
+#if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME)
+#include <libgen.h>
+#endif
+
+#include "rand.h"
+#include "slist.h"
+#include "strcase.h"
+/* The last 3 #include files should be in this order */
+#include "curl_printf.h"
+#include "curl_memory.h"
+#include "memdebug.h"
+
+#ifdef WIN32
+# ifndef R_OK
+# define R_OK 4
+# endif
+#endif
+
+
+#define FILE_CONTENTTYPE_DEFAULT "application/octet-stream"
+#define MULTIPART_CONTENTTYPE_DEFAULT "multipart/mixed"
+#define DISPOSITION_DEFAULT "attachment"
+
+#define READ_ERROR ((size_t) -1)
+
+/* Encoders. */
+static size_t encoder_nop_read(char *buffer, size_t size, bool ateof,
+ curl_mimepart *part);
+static curl_off_t encoder_nop_size(curl_mimepart *part);
+static size_t encoder_7bit_read(char *buffer, size_t size, bool ateof,
+ curl_mimepart *part);
+static size_t encoder_base64_read(char *buffer, size_t size, bool ateof,
+ curl_mimepart *part);
+static curl_off_t encoder_base64_size(curl_mimepart *part);
+static size_t encoder_qp_read(char *buffer, size_t size, bool ateof,
+ curl_mimepart *part);
+static curl_off_t encoder_qp_size(curl_mimepart *part);
+
+static const mime_encoder encoders[] = {
+ {"binary", encoder_nop_read, encoder_nop_size},
+ {"8bit", encoder_nop_read, encoder_nop_size},
+ {"7bit", encoder_7bit_read, encoder_nop_size},
+ {"base64", encoder_base64_read, encoder_base64_size},
+ {"quoted-printable", encoder_qp_read, encoder_qp_size},
+ {ZERO_NULL, ZERO_NULL, ZERO_NULL}
+};
+
+/* Base64 encoding table */
+static const char base64[] =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+/* Quoted-printable character class table.
+ *
+ * We cannot rely on ctype functions since quoted-printable input data
+ * is assumed to be ascii-compatible, even on non-ascii platforms. */
+#define QP_OK 1 /* Can be represented by itself. */
+#define QP_SP 2 /* Space or tab. */
+#define QP_CR 3 /* Carriage return. */
+#define QP_LF 4 /* Line-feed. */
+static const unsigned char qp_class[] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 07 */
+ 0, QP_SP, QP_LF, 0, 0, QP_CR, 0, 0, /* 08 - 0F */
+ 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 17 */
+ 0, 0, 0, 0, 0, 0, 0, 0, /* 18 - 1F */
+ QP_SP, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 20 - 27 */
+ QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 28 - 2F */
+ QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 30 - 37 */
+ QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, 0 , QP_OK, QP_OK, /* 38 - 3F */
+ QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 40 - 47 */
+ QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 48 - 4F */
+ QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 50 - 57 */
+ QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 58 - 5F */
+ QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 60 - 67 */
+ QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 68 - 6F */
+ QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, /* 70 - 77 */
+ QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, QP_OK, 0, /* 78 - 7F */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0 - FF */
+};
+
+
+/* Binary --> hexadecimal ASCII table. */
+static const char aschex[] =
+ "\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x41\x42\x43\x44\x45\x46";
+
+
+
+#ifndef __VMS
+#define filesize(name, stat_data) (stat_data.st_size)
+#define fopen_read fopen
+
+#else
+
+#include <fabdef.h>
+/*
+ * get_vms_file_size does what it takes to get the real size of the file
+ *
+ * For fixed files, find out the size of the EOF block and adjust.
+ *
+ * For all others, have to read the entire file in, discarding the contents.
+ * Most posted text files will be small, and binary files like zlib archives
+ * and CD/DVD images should be either a STREAM_LF format or a fixed format.
+ *
+ */
+curl_off_t VmsRealFileSize(const char *name,
+ const struct_stat *stat_buf)
+{
+ char buffer[8192];
+ curl_off_t count;
+ int ret_stat;
+ FILE * file;
+
+ file = fopen(name, FOPEN_READTEXT); /* VMS */
+ if(file == NULL)
+ return 0;
+
+ count = 0;
+ ret_stat = 1;
+ while(ret_stat > 0) {
+ ret_stat = fread(buffer, 1, sizeof(buffer), file);
+ if(ret_stat != 0)
+ count += ret_stat;
+ }
+ fclose(file);
+
+ return count;
+}
+
+/*
+ *
+ * VmsSpecialSize checks to see if the stat st_size can be trusted and
+ * if not to call a routine to get the correct size.
+ *
+ */
+static curl_off_t VmsSpecialSize(const char *name,
+ const struct_stat *stat_buf)
+{
+ switch(stat_buf->st_fab_rfm) {
+ case FAB$C_VAR:
+ case FAB$C_VFC:
+ return VmsRealFileSize(name, stat_buf);
+ break;
+ default:
+ return stat_buf->st_size;
+ }
+}
+
+#define filesize(name, stat_data) VmsSpecialSize(name, &stat_data)
+
+/*
+ * vmsfopenread
+ *
+ * For upload to work as expected on VMS, different optional
+ * parameters must be added to the fopen command based on
+ * record format of the file.
+ *
+ */
+static FILE * vmsfopenread(const char *file, const char *mode)
+{
+ struct_stat statbuf;
+ int result;
+
+ result = stat(file, &statbuf);
+
+ switch(statbuf.st_fab_rfm) {
+ case FAB$C_VAR:
+ case FAB$C_VFC:
+ case FAB$C_STMCR:
+ return fopen(file, FOPEN_READTEXT); /* VMS */
+ break;
+ default:
+ return fopen(file, FOPEN_READTEXT, "rfm=stmlf", "ctx=stm");
+ }
+}
+
+#define fopen_read vmsfopenread
+#endif
+
+
+#ifndef HAVE_BASENAME
+/*
+ (Quote from The Open Group Base Specifications Issue 6 IEEE Std 1003.1, 2004
+ Edition)
+
+ The basename() function shall take the pathname pointed to by path and
+ return a pointer to the final component of the pathname, deleting any
+ trailing '/' characters.
+
+ If the string pointed to by path consists entirely of the '/' character,
+ basename() shall return a pointer to the string "/". If the string pointed
+ to by path is exactly "//", it is implementation-defined whether '/' or "//"
+ is returned.
+
+ If path is a null pointer or points to an empty string, basename() shall
+ return a pointer to the string ".".
+
+ The basename() function may modify the string pointed to by path, and may
+ return a pointer to static storage that may then be overwritten by a
+ subsequent call to basename().
+
+ The basename() function need not be reentrant. A function that is not
+ required to be reentrant is not required to be thread-safe.
+
+*/
+static char *Curl_basename(char *path)
+{
+ /* Ignore all the details above for now and make a quick and simple
+ implementaion here */
+ char *s1;
+ char *s2;
+
+ s1 = strrchr(path, '/');
+ s2 = strrchr(path, '\\');
+
+ if(s1 && s2) {
+ path = (s1 > s2? s1 : s2) + 1;
+ }
+ else if(s1)
+ path = s1 + 1;
+ else if(s2)
+ path = s2 + 1;
+
+ return path;
+}
+
+#define basename(x) Curl_basename((x))
+#endif
+
+
+/* Set readback state. */
+static void mimesetstate(mime_state *state, enum mimestate tok, void *ptr)
+{
+ state->state = tok;
+ state->ptr = ptr;
+ state->offset = 0;
+}
+
+
+/* Escape header string into allocated memory. */
+static char *escape_string(const char *src)
+{
+ size_t bytecount = 0;
+ size_t i;
+ char *dst;
+
+ for(i = 0; src[i]; i++)
+ if(src[i] == '"' || src[i] == '\\')
+ bytecount++;
+
+ bytecount += i;
+ dst = malloc(bytecount + 1);
+ if(!dst)
+ return NULL;
+
+ for(i = 0; *src; src++) {
+ if(*src == '"' || *src == '\\')
+ dst[i++] = '\\';
+ dst[i++] = *src;
+ }
+
+ dst[i] = '\0';
+ return dst;
+}
+
+/* Check if header matches. */
+static char *match_header(struct curl_slist *hdr, const char *lbl, size_t len)
+{
+ char *value = NULL;
+
+ if(strncasecompare(hdr->data, lbl, len) && hdr->data[len] == ':')
+ for(value = hdr->data + len + 1; *value == ' '; value++)
+ ;
+ return value;
+}
+
+/* Get a header from an slist. */
+static char *search_header(struct curl_slist *hdrlist, const char *hdr)
+{
+ size_t len = strlen(hdr);
+ char *value = NULL;
+
+ for(; !value && hdrlist; hdrlist = hdrlist->next)
+ value = match_header(hdrlist, hdr, len);
+
+ return value;
+}
+
+static char *strippath(const char *fullfile)
+{
+ char *filename;
+ char *base;
+ filename = strdup(fullfile); /* duplicate since basename() may ruin the
+ buffer it works on */
+ if(!filename)
+ return NULL;
+ base = strdup(basename(filename));
+
+ free(filename); /* free temporary buffer */
+
+ return base; /* returns an allocated string or NULL ! */
+}
+
+/* Initialize data encoder state. */
+static void cleanup_encoder_state(mime_encoder_state *p)
+{
+ p->pos = 0;
+ p->bufbeg = 0;
+ p->bufend = 0;
+}
+
+
+/* Dummy encoder. This is used for 8bit and binary content encodings. */
+static size_t encoder_nop_read(char *buffer, size_t size, bool ateof,
+ curl_mimepart *part)
+{
+ mime_encoder_state *st = &part->encstate;
+ size_t insize = st->bufend - st->bufbeg;
+
+ (void) ateof;
+
+ if(size > insize)
+ size = insize;
+ if(size)
+ memcpy(buffer, st->buf, size);
+ st->bufbeg += size;
+ return size;
+}
+
+static curl_off_t encoder_nop_size(curl_mimepart *part)
+{
+ return part->datasize;
+}
+
+
+/* 7bit encoder: the encoder is just a data validity check. */
+static size_t encoder_7bit_read(char *buffer, size_t size, bool ateof,
+ curl_mimepart *part)
+{
+ mime_encoder_state *st = &part->encstate;
+ size_t cursize = st->bufend - st->bufbeg;
+
+ (void) ateof;
+
+ if(size > cursize)
+ size = cursize;
+
+ for(cursize = 0; cursize < size; cursize++) {
+ *buffer = st->buf[st->bufbeg];
+ if(*buffer++ & 0x80)
+ return cursize? cursize: READ_ERROR;
+ st->bufbeg++;
+ }
+
+ return cursize;
+}
+
+
+/* Base64 content encoder. */
+static size_t encoder_base64_read(char *buffer, size_t size, bool ateof,
+ curl_mimepart *part)
+{
+ mime_encoder_state *st = &part->encstate;
+ size_t cursize = 0;
+ int i;
+ char *ptr = buffer;
+
+ while(st->bufbeg < st->bufend) {
+ /* Line full ? */
+ if(st->pos >= MAX_ENCODED_LINE_LENGTH - 4) {
+ /* Yes, we need 2 characters for CRLF. */
+ if(size < 2)
+ break;
+ *ptr++ = '\r';
+ *ptr++ = '\n';
+ st->pos = 0;
+ cursize += 2;
+ size -= 2;
+ }
+
+ /* Be sure there is enough space and input data for a base64 group. */
+ if(size < 4 || st->bufend - st->bufbeg < 3)
+ break;
+
+ /* Encode three bytes a four characters. */
+ i = st->buf[st->bufbeg++] & 0xFF;
+ i = (i << 8) | (st->buf[st->bufbeg++] & 0xFF);
+ i = (i << 8) | (st->buf[st->bufbeg++] & 0xFF);
+ *ptr++ = base64[(i >> 18) & 0x3F];
+ *ptr++ = base64[(i >> 12) & 0x3F];
+ *ptr++ = base64[(i >> 6) & 0x3F];
+ *ptr++ = base64[i & 0x3F];
+ cursize += 4;
+ st->pos += 4;
+ size -= 4;
+ }
+
+ /* If at eof, we have to flush the buffered data. */
+ if(ateof && size >= 4) {
+ /* Buffered data size can only be 0, 1 or 2. */
+ ptr[2] = ptr[3] = '=';
+ i = 0;
+ switch(st->bufend - st->bufbeg) {
+ case 2:
+ i = (st->buf[st->bufbeg + 1] & 0xFF) << 8;
+ /* FALLTHROUGH */
+ case 1:
+ i |= (st->buf[st->bufbeg] & 0xFF) << 16;
+ ptr[0] = base64[(i >> 18) & 0x3F];
+ ptr[1] = base64[(i >> 12) & 0x3F];
+ if(++st->bufbeg != st->bufend) {
+ ptr[2] = base64[(i >> 6) & 0x3F];
+ st->bufbeg++;
+ }
+ cursize += 4;
+ st->pos += 4;
+ break;
+ }
+ }
+
+#ifdef CURL_DOES_CONVERSIONS
+ /* This is now textual data, Convert character codes. */
+ if(part->easy && cursize) {
+ CURLcode result = Curl_convert_to_network(part->easy, buffer, cursize);
+ if(result)
+ return READ_ERROR;
+ }
+#endif
+
+ return cursize;
+}
+
+static curl_off_t encoder_base64_size(curl_mimepart *part)
+{
+ curl_off_t size = part->datasize;
+
+ if(size <= 0)
+ return size; /* Unknown size or no data. */
+
+ /* Compute base64 character count. */
+ size = 4 * (1 + (size - 1) / 3);
+
+ /* Effective character count must include CRLFs. */
+ return size + 2 * ((size - 1) / MAX_ENCODED_LINE_LENGTH);
+}
+
+
+/* Quoted-printable lookahead.
+ *
+ * Check if a CRLF or end of data is in input buffer at current position + n.
+ * Return -1 if more data needed, 1 if CRLF or end of data, else 0.
+ */
+static int qp_lookahead_eol(mime_encoder_state *st, int ateof, size_t n)
+{
+ n += st->bufbeg;
+ if(n >= st->bufend && ateof)
+ return 1;
+ if(n + 2 > st->bufend)
+ return ateof? 0: -1;
+ if(qp_class[st->buf[n] & 0xFF] == QP_CR &&
+ qp_class[st->buf[n + 1] & 0xFF] == QP_LF)
+ return 1;
+ return 0;
+}
+
+/* Quoted-printable encoder. */
+static size_t encoder_qp_read(char *buffer, size_t size, bool ateof,
+ curl_mimepart *part)
+{
+ mime_encoder_state *st = &part->encstate;
+ char *ptr = buffer;
+ size_t cursize = 0;
+ int i;
+ size_t len;
+ size_t consumed;
+ int softlinebreak;
+ char buf[4];
+
+ /* On all platforms, input is supposed to be ASCII compatible: for this
+ reason, we use hexadecimal ASCII codes in this function rather than
+ character constants that can be interpreted as non-ascii on some
+ platforms. Preserve ASCII encoding on output too. */
+ while(st->bufbeg < st->bufend) {
+ len = 1;
+ consumed = 1;
+ i = st->buf[st->bufbeg];
+ buf[0] = (char) i;
+ buf[1] = aschex[(i >> 4) & 0xF];
+ buf[2] = aschex[i & 0xF];
+
+ switch(qp_class[st->buf[st->bufbeg] & 0xFF]) {
+ case QP_OK: /* Not a special character. */
+ break;
+ case QP_SP: /* Space or tab. */
+ /* Spacing must be escaped if followed by CRLF. */
+ switch(qp_lookahead_eol(st, ateof, 1)) {
+ case -1: /* More input data needed. */
+ return cursize;
+ case 0: /* No encoding needed. */
+ break;
+ default: /* CRLF after space or tab. */
+ buf[0] = '\x3D'; /* '=' */
+ len = 3;
+ break;
+ }
+ break;
+ case QP_CR: /* Carriage return. */
+ /* If followed by a line-feed, output the CRLF pair.
+ Else escape it. */
+ switch(qp_lookahead_eol(st, ateof, 0)) {
+ case -1: /* Need more data. */
+ return cursize;
+ case 1: /* CRLF found. */
+ buf[len++] = '\x0A'; /* Append '\n'. */
+ consumed = 2;
+ break;
+ default: /* Not followed by LF: escape. */
+ buf[0] = '\x3D'; /* '=' */
+ len = 3;
+ break;
+ }
+ break;
+ default: /* Character must be escaped. */
+ buf[0] = '\x3D'; /* '=' */
+ len = 3;
+ break;
+ }
+
+ /* Be sure the encoded character fits within maximum line length. */
+ if(buf[len - 1] != '\x0A') { /* '\n' */
+ softlinebreak = st->pos + len > MAX_ENCODED_LINE_LENGTH;
+ if(!softlinebreak && st->pos + len == MAX_ENCODED_LINE_LENGTH) {
+ /* We may use the current line only if end of data or followed by
+ a CRLF. */
+ switch(qp_lookahead_eol(st, ateof, consumed)) {
+ case -1: /* Need more data. */
+ return cursize;
+ break;
+ case 0: /* Not followed by a CRLF. */
+ softlinebreak = 1;
+ break;
+ }
+ }
+ if(softlinebreak) {
+ strcpy(buf, "\x3D\x0D\x0A"); /* "=\r\n" */
+ len = 3;
+ consumed = 0;
+ }
+ }
+
+ /* If the output buffer would overflow, do not store. */
+ if(len > size)
+ break;
+
+ /* Append to output buffer. */
+ memcpy(ptr, buf, len);
+ cursize += len;
+ ptr += len;
+ size -= len;
+ st->pos += len;
+ if(buf[len - 1] == '\x0A') /* '\n' */
+ st->pos = 0;
+ st->bufbeg += consumed;
+ }
+
+ return cursize;
+}
+
+static curl_off_t encoder_qp_size(curl_mimepart *part)
+{
+ /* Determining the size can only be done by reading the data: unless the
+ data size is 0, we return it as unknown (-1). */
+ return part->datasize? -1: 0;
+}
+
+
+/* In-memory data callbacks. */
+/* Argument is a pointer to the mime part. */
+static size_t mime_mem_read(char *buffer, size_t size, size_t nitems,
+ void *instream)
+{
+ curl_mimepart *part = (curl_mimepart *) instream;
+ size_t sz = (size_t) part->datasize - part->state.offset;
+
+ (void) size; /* Always 1.*/
+
+ if(sz > nitems)
+ sz = nitems;
+
+ if(sz)
+ memcpy(buffer, (char *) part->data, sz);
+
+ part->state.offset += sz;
+ return sz;
+}
+
+static int mime_mem_seek(void *instream, curl_off_t offset, int whence)
+{
+ curl_mimepart *part = (curl_mimepart *) instream;
+
+ switch(whence) {
+ case SEEK_CUR:
+ offset += part->state.offset;
+ break;
+ case SEEK_END:
+ offset += part->datasize;
+ break;
+ }
+
+ if(offset < 0 || offset > part->datasize)
+ return CURL_SEEKFUNC_FAIL;
+
+ part->state.offset = (size_t) offset;
+ return CURL_SEEKFUNC_OK;
+}
+
+static void mime_mem_free(void *ptr)
+{
+ Curl_safefree(((curl_mimepart *) ptr)->data);
+}
+
+
+/* Named file callbacks. */
+/* Argument is a pointer to the mime part. */
+static int mime_open_file(curl_mimepart * part)
+{
+ /* Open a MIMEKIND_FILE part. */
+
+ if(part->fp)
+ return 0;
+ part->fp = fopen_read(part->data, "rb");
+ return part->fp? 0: -1;
+}
+
+static size_t mime_file_read(char *buffer, size_t size, size_t nitems,
+ void *instream)
+{
+ curl_mimepart *part = (curl_mimepart *) instream;
+
+ if(mime_open_file(part))
+ return READ_ERROR;
+
+ return fread(buffer, size, nitems, part->fp);
+}
+
+static int mime_file_seek(void *instream, curl_off_t offset, int whence)
+{
+ curl_mimepart *part = (curl_mimepart *) instream;
+
+ if(whence == SEEK_SET && !offset && !part->fp)
+ return CURL_SEEKFUNC_OK; /* Not open: implicitly already at BOF. */
+
+ if(mime_open_file(part))
+ return CURL_SEEKFUNC_FAIL;
+
+ return fseek(part->fp, (long) offset, whence)?
+ CURL_SEEKFUNC_CANTSEEK: CURL_SEEKFUNC_OK;
+}
+
+static void mime_file_free(void *ptr)
+{
+ curl_mimepart *part = (curl_mimepart *) ptr;
+
+ if(part->fp) {
+ fclose(part->fp);
+ part->fp = NULL;
+ }
+ Curl_safefree(part->data);
+ part->data = NULL;
+}
+
+
+/* Subparts callbacks. */
+/* Argument is a pointer to the mime structure. */
+
+/* Readback a byte string segment. */
+static size_t readback_bytes(mime_state *state,
+ char *buffer, size_t bufsize,
+ const char *bytes, size_t numbytes,
+ const char *trail)
+{
+ size_t sz;
+
+ sz = numbytes - state->offset;
+
+ if(numbytes > state->offset) {
+ sz = numbytes - state->offset;
+ bytes += state->offset;
+ }
+ else {
+ size_t tsz = strlen(trail);
+
+ sz = state->offset - numbytes;
+ if(sz >= tsz)
+ return 0;
+ bytes = trail + sz;
+ sz = tsz - sz;
+ }
+
+ if(sz > bufsize)
+ sz = bufsize;
+
+ memcpy(buffer, bytes, sz);
+ state->offset += sz;
+ return sz;
+}
+
+/* Read a non-encoded part content. */
+static size_t read_part_content(curl_mimepart *part,
+ char *buffer, size_t bufsize)
+{
+ size_t sz = 0;
+
+ if(part->readfunc)
+ sz = part->readfunc(buffer, 1, bufsize, part->arg);
+ return sz;
+}
+
+/* Read and encode part content. */
+static size_t read_encoded_part_content(curl_mimepart *part,
+ char *buffer, size_t bufsize)
+{
+ mime_encoder_state *st = &part->encstate;
+ size_t cursize = 0;
+ size_t sz;
+ bool ateof = FALSE;
+
+ while(bufsize) {
+ if(st->bufbeg < st->bufend || ateof) {
+ /* Encode buffered data. */
+ sz = part->encoder->encodefunc(buffer, bufsize, ateof, part);
+ switch(sz) {
+ case 0:
+ if(ateof)
+ return cursize;
+ break;
+ case CURL_READFUNC_ABORT:
+ case CURL_READFUNC_PAUSE:
+ case READ_ERROR:
+ return cursize? cursize: sz;
+ default:
+ cursize += sz;
+ buffer += sz;
+ bufsize -= sz;
+ continue;
+ }
+ }
+
+ /* We need more data in input buffer. */
+ if(st->bufbeg) {
+ size_t len = st->bufend - st->bufbeg;
+
+ if(len)
+ memmove(st->buf, st->buf + st->bufbeg, len);
+ st->bufbeg = 0;
+ st->bufend = len;
+ }
+ if(st->bufend >= sizeof st->buf)
+ return cursize? cursize: READ_ERROR; /* Buffer full. */
+ sz = read_part_content(part, st->buf + st->bufend,
+ sizeof st->buf - st->bufend);
+ switch(sz) {
+ case 0:
+ ateof = TRUE;
+ break;
+ case CURL_READFUNC_ABORT:
+ case CURL_READFUNC_PAUSE:
+ case READ_ERROR:
+ return cursize? cursize: sz;
+ default:
+ st->bufend += sz;
+ break;
+ }
+ }
+
+ return cursize;
+}
+
+/* Readback a mime part. */
+static size_t readback_part(curl_mimepart *part,
+ char *buffer, size_t bufsize)
+{
+ size_t cursize = 0;
+ size_t sz;
+ struct curl_slist *hdr;
+#ifdef CURL_DOES_CONVERSIONS
+ char *convbuf = buffer;
+#endif
+
+ /* Readback from part. */
+
+ while(bufsize) {
+ sz = 0;
+ hdr = (struct curl_slist *) part->state.ptr;
+ switch(part->state.state) {
+ case MIMESTATE_BEGIN:
+ mimesetstate(&part->state, part->flags & MIME_BODY_ONLY? MIMESTATE_BODY:
+ MIMESTATE_CURLHEADERS, part->curlheaders);
+ break;
+ case MIMESTATE_USERHEADERS:
+ if(!hdr) {
+ mimesetstate(&part->state, MIMESTATE_EOH, NULL);
+ break;
+ }
+ if(match_header(hdr, "Content-Type", 12)) {
+ mimesetstate(&part->state, MIMESTATE_USERHEADERS, hdr->next);
+ break;
+ }
+ /* FALLTHROUGH */
+ case MIMESTATE_CURLHEADERS:
+ if(!hdr)
+ mimesetstate(&part->state, MIMESTATE_USERHEADERS, part->userheaders);
+ else {
+ sz = readback_bytes(&part->state, buffer, bufsize,
+ hdr->data, strlen(hdr->data), "\r\n");
+ if(!sz)
+ mimesetstate(&part->state, part->state.state, hdr->next);
+ }
+ break;
+ case MIMESTATE_EOH:
+ sz = readback_bytes(&part->state, buffer, bufsize, "\r\n", 2, "");
+ if(!sz)
+ mimesetstate(&part->state, MIMESTATE_BODY, NULL);
+ break;
+ case MIMESTATE_BODY:
+#ifdef CURL_DOES_CONVERSIONS
+ if(part->easy && convbuf < buffer) {
+ CURLcode result = Curl_convert_to_network(part->easy, convbuf,
+ buffer - convbuf);
+ if(result)
+ return READ_ERROR;
+ convbuf = buffer;
+ }
+#endif
+ cleanup_encoder_state(&part->encstate);
+ mimesetstate(&part->state, MIMESTATE_CONTENT, NULL);
+ break;
+ case MIMESTATE_CONTENT:
+ if(part->encoder)
+ sz = read_encoded_part_content(part, buffer, bufsize);
+ else
+ sz = read_part_content(part, buffer, bufsize);
+ switch(sz) {
+ case 0:
+ mimesetstate(&part->state, MIMESTATE_END, NULL);
+ /* Try sparing open file descriptors. */
+ if(part->kind == MIMEKIND_FILE && part->fp) {
+ fclose(part->fp);
+ part->fp = NULL;
+ }
+ /* FALLTHROUGH */
+ case CURL_READFUNC_ABORT:
+ case CURL_READFUNC_PAUSE:
+ case READ_ERROR:
+ return cursize? cursize: sz;
+ }
+ break;
+ case MIMESTATE_END:
+ return cursize;
+ default:
+ break; /* Other values not in part state. */
+ }
+
+ /* Bump buffer and counters according to read size. */
+ cursize += sz;
+ buffer += sz;
+ bufsize -= sz;
+ }
+
+#ifdef CURL_DOES_CONVERSIONS
+ if(part->easy && convbuf < buffer &&
+ part->state.state < MIMESTATE_BODY) {
+ CURLcode result = Curl_convert_to_network(part->easy, convbuf,
+ buffer - convbuf);
+ if(result)
+ return READ_ERROR;
+ }
+#endif
+
+ return cursize;
+}
+
+/* Readback from mime. */
+static size_t mime_subparts_read(char *buffer, size_t size, size_t nitems,
+ void *instream)
+{
+ curl_mime *mime = (curl_mime *) instream;
+ size_t cursize = 0;
+ size_t sz;
+ curl_mimepart *part;
+#ifdef CURL_DOES_CONVERSIONS
+ char *convbuf = buffer;
+#endif
+
+ (void) size; /* Always 1. */
+
+ while(nitems) {
+ sz = 0;
+ part = mime->state.ptr;
+ switch(mime->state.state) {
+ case MIMESTATE_BEGIN:
+ case MIMESTATE_BODY:
+#ifdef CURL_DOES_CONVERSIONS
+ convbuf = buffer;
+#endif
+ mimesetstate(&mime->state, MIMESTATE_BOUNDARY1, mime->firstpart);
+ /* The first boundary always follows the header termination empty line,
+ so is always preceded by a CRLK. We can then spare 2 characters
+ by skipping the leading CRLF in boundary. */
+ mime->state.offset += 2;
+ break;
+ case MIMESTATE_BOUNDARY1:
+ sz = readback_bytes(&mime->state, buffer, nitems, "\r\n--", 4, "");
+ if(!sz)
+ mimesetstate(&mime->state, MIMESTATE_BOUNDARY2, part);
+ break;
+ case MIMESTATE_BOUNDARY2:
+ sz = readback_bytes(&mime->state, buffer, nitems, mime->boundary,
+ strlen(mime->boundary), part? "\r\n": "--\r\n");
+ if(!sz) {
+#ifdef CURL_DOES_CONVERSIONS
+ if(mime->easy && convbuf < buffer) {
+ CURLcode result = Curl_convert_to_network(mime->easy, convbuf,
+ buffer - convbuf);
+ if(result)
+ return READ_ERROR;
+ convbuf = buffer;
+ }
+#endif
+ mimesetstate(&mime->state, MIMESTATE_CONTENT, part);
+ }
+ break;
+ case MIMESTATE_CONTENT:
+ if(!part) {
+ mimesetstate(&mime->state, MIMESTATE_END, NULL);
+ break;
+ }
+ sz = readback_part(part, buffer, nitems);
+ switch(sz) {
+ case CURL_READFUNC_ABORT:
+ case CURL_READFUNC_PAUSE:
+ case READ_ERROR:
+ return cursize? cursize: sz;
+ case 0:
+#ifdef CURL_DOES_CONVERSIONS
+ convbuf = buffer;
+#endif
+ mimesetstate(&mime->state, MIMESTATE_BOUNDARY1, part->nextpart);
+ break;
+ }
+ break;
+ case MIMESTATE_END:
+ return cursize;
+ default:
+ break; /* other values not used in mime state. */
+ }
+
+ /* Bump buffer and counters according to read size. */
+ cursize += sz;
+ buffer += sz;
+ nitems -= sz;
+ }
+
+#ifdef CURL_DOES_CONVERSIONS
+ if(mime->easy && convbuf < buffer &&
+ mime->state.state <= MIMESTATE_CONTENT) {
+ CURLcode result = Curl_convert_to_network(mime->easy, convbuf,
+ buffer - convbuf);
+ if(result)
+ return READ_ERROR;
+ }
+#endif
+
+ return cursize;
+}
+
+static int mime_part_rewind(curl_mimepart *part)
+{
+ int res = CURL_SEEKFUNC_OK;
+ enum mimestate targetstate = MIMESTATE_BEGIN;
+
+ if(part->flags & MIME_BODY_ONLY)
+ targetstate = MIMESTATE_BODY;
+ cleanup_encoder_state(&part->encstate);
+ if(part->state.state > targetstate) {
+ res = CURL_SEEKFUNC_CANTSEEK;
+ if(part->seekfunc) {
+ res = part->seekfunc(part->arg, (curl_off_t) 0, SEEK_SET);
+ switch(res) {
+ case CURL_SEEKFUNC_OK:
+ case CURL_SEEKFUNC_FAIL:
+ case CURL_SEEKFUNC_CANTSEEK:
+ break;
+ case -1: /* For fseek() error. */
+ res = CURL_SEEKFUNC_CANTSEEK;
+ break;
+ default:
+ res = CURL_SEEKFUNC_FAIL;
+ break;
+ }
+ }
+ }
+
+ if(res == CURL_SEEKFUNC_OK)
+ mimesetstate(&part->state, targetstate, NULL);
+
+ return res;
+}
+
+static int mime_subparts_seek(void *instream, curl_off_t offset, int whence)
+{
+ curl_mime *mime = (curl_mime *) instream;
+ curl_mimepart *part;
+ int result = CURL_SEEKFUNC_OK;
+ int res;
+
+ if(whence != SEEK_SET || offset)
+ return CURL_SEEKFUNC_CANTSEEK; /* Only support full rewind. */
+
+ if(mime->state.state == MIMESTATE_BEGIN)
+ return CURL_SEEKFUNC_OK; /* Already rewound. */
+
+ for(part = mime->firstpart; part; part = part->nextpart) {
+ res = mime_part_rewind(part);
+ if(res != CURL_SEEKFUNC_OK)
+ result = res;
+ }
+
+ if(result == CURL_SEEKFUNC_OK)
+ mimesetstate(&mime->state, MIMESTATE_BEGIN, NULL);
+
+ return result;
+}
+
+static void mime_subparts_free(void *ptr)
+{
+ curl_mime *mime = (curl_mime *) ptr;
+ curl_mime_free(mime);
+}
+
+
+/* Release part content. */
+static void cleanup_part_content(curl_mimepart *part)
+{
+ if(part->freefunc)
+ part->freefunc(part->arg);
+
+ part->readfunc = NULL;
+ part->seekfunc = NULL;
+ part->freefunc = NULL;
+ part->arg = (void *) part; /* Defaults to part itself. */
+ part->data = NULL;
+ part->fp = NULL;
+ part->datasize = (curl_off_t) 0; /* No size yet. */
+ part->encoder = NULL;
+ cleanup_encoder_state(&part->encstate);
+ part->kind = MIMEKIND_NONE;
+}
+
+void Curl_mime_cleanpart(curl_mimepart *part)
+{
+ cleanup_part_content(part);
+ curl_slist_free_all(part->curlheaders);
+ if(part->flags & MIME_USERHEADERS_OWNER)
+ curl_slist_free_all(part->userheaders);
+ Curl_safefree(part->mimetype);
+ Curl_safefree(part->name);
+ Curl_safefree(part->filename);
+ Curl_mime_initpart(part, part->easy);
+}
+
+/* Recursively delete a mime handle and its parts. */
+void curl_mime_free(curl_mime *mime)
+{
+ curl_mimepart *part;
+
+ if(mime) {
+ while(mime->firstpart) {
+ part = mime->firstpart;
+ mime->firstpart = part->nextpart;
+ Curl_mime_cleanpart(part);
+ free(part);
+ }
+
+ free(mime->boundary);
+ free(mime);
+ }
+}
+
+/*
+ * Mime build functions.
+ */
+
+/* Create a mime handle. */
+curl_mime *curl_mime_init(struct Curl_easy *easy)
+{
+ curl_mime *mime;
+
+ mime = (curl_mime *) malloc(sizeof *mime);
+
+ if(mime) {
+ mime->easy = easy;
+ mime->parent = NULL;
+ mime->firstpart = NULL;
+ mime->lastpart = NULL;
+
+ /* Get a part boundary. */
+ mime->boundary = malloc(24 + MIME_RAND_BOUNDARY_CHARS + 1);
+ if(!mime->boundary) {
+ free(mime);
+ return NULL;
+ }
+
+ memset(mime->boundary, '-', 24);
+ Curl_rand_hex(easy, (unsigned char *) mime->boundary + 24,
+ MIME_RAND_BOUNDARY_CHARS + 1);
+ mimesetstate(&mime->state, MIMESTATE_BEGIN, NULL);
+ }
+
+ return mime;
+}
+
+/* Initialize a mime part. */
+void Curl_mime_initpart(curl_mimepart *part, struct Curl_easy *easy)
+{
+ memset((char *) part, 0, sizeof *part);
+ part->easy = easy;
+ mimesetstate(&part->state, MIMESTATE_BEGIN, NULL);
+}
+
+/* Create a mime part and append it to a mime handle's part list. */
+curl_mimepart *curl_mime_addpart(curl_mime *mime)
+{
+ curl_mimepart *part;
+
+ if(!mime)
+ return NULL;
+
+ part = (curl_mimepart *) malloc(sizeof *part);
+
+ if(part) {
+ Curl_mime_initpart(part, mime->easy);
+ part->parent = mime;
+
+ if(mime->lastpart)
+ mime->lastpart->nextpart = part;
+ else
+ mime->firstpart = part;
+
+ mime->lastpart = part;
+ }
+
+ return part;
+}
+
+/* Set mime part name. */
+CURLcode curl_mime_name(curl_mimepart *part, const char *name)
+{
+ if(!part)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ Curl_safefree(part->name);
+ part->name = NULL;
+
+ if(name) {
+ part->name = strdup(name);
+ if(!part->name)
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ return CURLE_OK;
+}
+
+/* Set mime part remote file name. */
+CURLcode curl_mime_filename(curl_mimepart *part, const char *filename)
+{
+ if(!part)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ Curl_safefree(part->filename);
+ part->filename = NULL;
+
+ if(filename) {
+ part->filename = strdup(filename);
+ if(!part->filename)
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ return CURLE_OK;
+}
+
+/* Set mime part content from memory data. */
+CURLcode curl_mime_data(curl_mimepart *part,
+ const char *data, size_t datasize)
+{
+ if(!part)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ cleanup_part_content(part);
+
+ if(data) {
+ if(datasize == CURL_ZERO_TERMINATED)
+ datasize = strlen(data);
+
+ part->data = malloc(datasize + 1);
+ if(!part->data)
+ return CURLE_OUT_OF_MEMORY;
+
+ part->datasize = datasize;
+
+ if(datasize)
+ memcpy(part->data, data, datasize);
+ part->data[datasize] = '\0'; /* Set a nul terminator as sentinel. */
+
+ part->readfunc = mime_mem_read;
+ part->seekfunc = mime_mem_seek;
+ part->freefunc = mime_mem_free;
+ part->kind = MIMEKIND_DATA;
+ }
+
+ return CURLE_OK;
+}
+
+/* Set mime part content from named local file. */
+CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename)
+{
+ CURLcode result = CURLE_OK;
+ char *base;
+
+ if(!part)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ cleanup_part_content(part);
+
+ if(filename) {
+ struct_stat sbuf;
+
+ if(stat(filename, &sbuf) || access(filename, R_OK))
+ result = CURLE_READ_ERROR;
+
+ part->data = strdup(filename);
+ if(!part->data)
+ result = CURLE_OUT_OF_MEMORY;
+
+ part->datasize = -1;
+ if(!result && S_ISREG(sbuf.st_mode)) {
+ part->datasize = filesize(filename, sbuf);
+ part->seekfunc = mime_file_seek;
+ }
+
+ part->readfunc = mime_file_read;
+ part->freefunc = mime_file_free;
+ part->kind = MIMEKIND_FILE;
+
+ /* As a side effect, set the filename to the current file's base name.
+ It is possible to withdraw this by explicitly calling
+ curl_mime_filename() with a NULL filename argument after the current
+ call. */
+ base = strippath(filename);
+ if(!base)
+ result = CURLE_OUT_OF_MEMORY;
+ else {
+ CURLcode res = curl_mime_filename(part, base);
+
+ if(res)
+ result = res;
+ free(base);
+ }
+ }
+ return result;
+}
+
+/* Set mime part type. */
+CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype)
+{
+ if(!part)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ Curl_safefree(part->mimetype);
+ part->mimetype = NULL;
+
+ if(mimetype) {
+ part->mimetype = strdup(mimetype);
+ if(!part->mimetype)
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ return CURLE_OK;
+}
+
+/* Set mime data transfer encoder. */
+CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding)
+{
+ CURLcode result = CURLE_BAD_FUNCTION_ARGUMENT;
+ const mime_encoder *mep;
+
+ if(!part)
+ return result;
+
+ part->encoder = NULL;
+
+ if(!encoding)
+ return CURLE_OK; /* Removing current encoder. */
+
+ for(mep = encoders; mep->name; mep++)
+ if(strcasecompare(encoding, mep->name)) {
+ part->encoder = mep;
+ result = CURLE_OK;
+ }
+
+ return result;
+}
+
+/* Set mime part headers. */
+CURLcode curl_mime_headers(curl_mimepart *part,
+ struct curl_slist *headers, int take_ownership)
+{
+ if(!part)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ if(part->flags & MIME_USERHEADERS_OWNER) {
+ curl_slist_free_all(part->userheaders);
+ part->flags &= ~MIME_USERHEADERS_OWNER;
+ }
+ part->userheaders = headers;
+ if(headers && take_ownership)
+ part->flags |= MIME_USERHEADERS_OWNER;
+ return CURLE_OK;
+}
+
+/* Set mime part content from callback. */
+CURLcode curl_mime_data_cb(curl_mimepart *part, curl_off_t datasize,
+ curl_read_callback readfunc,
+ curl_seek_callback seekfunc,
+ curl_free_callback freefunc, void *arg)
+{
+ if(!part)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ cleanup_part_content(part);
+
+ if(readfunc) {
+ part->readfunc = readfunc;
+ part->seekfunc = seekfunc;
+ part->freefunc = freefunc;
+ part->arg = arg;
+ part->datasize = datasize;
+ part->kind = MIMEKIND_CALLBACK;
+ }
+
+ return CURLE_OK;
+}
+
+/* Set mime part content from subparts. */
+CURLcode curl_mime_subparts(curl_mimepart *part,
+ curl_mime *subparts)
+{
+ if(!part)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ /* Accept setting twice the same subparts. */
+ if(part->kind == MIMEKIND_MULTIPART && part->arg == subparts)
+ return CURLE_OK;
+
+ cleanup_part_content(part);
+
+ if(subparts) {
+ /* Must belong to the same data handle. */
+ if(part->easy && subparts->easy && part->easy != subparts->easy)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ /* Should not have been attached already. */
+ if(subparts->parent)
+ return CURLE_BAD_FUNCTION_ARGUMENT;
+
+ subparts->parent = part;
+ part->readfunc = mime_subparts_read;
+ part->seekfunc = mime_subparts_seek;
+ part->freefunc = mime_subparts_free;
+ part->arg = subparts;
+ part->datasize = -1;
+ part->kind = MIMEKIND_MULTIPART;
+ }
+
+ return CURLE_OK;
+}
+
+
+/* Readback from top mime. */
+/* Argument is the dummy top part. */
+size_t Curl_mime_read(char *buffer, size_t size, size_t nitems, void *instream)
+{
+ curl_mimepart *part = (curl_mimepart *) instream;
+
+ (void) size; /* Always 1. */
+ return readback_part(part, buffer, nitems);
+}
+
+/* Rewind mime stream. */
+CURLcode Curl_mime_rewind(curl_mimepart *part)
+{
+ return mime_part_rewind(part) == CURL_SEEKFUNC_OK?
+ CURLE_OK: CURLE_SEND_FAIL_REWIND;
+}
+
+/* Compute header list size. */
+static size_t slist_size(struct curl_slist *s,
+ size_t overhead, const char *skip)
+{
+ size_t size = 0;
+ size_t skiplen = skip? strlen(skip): 0;
+
+ for(; s; s = s->next)
+ if(!skip || !match_header(s, skip, skiplen))
+ size += strlen(s->data) + overhead;
+ return size;
+}
+
+/* Get/compute multipart size. */
+static curl_off_t multipart_size(curl_mime *mime)
+{
+ curl_off_t size;
+ curl_off_t sz;
+ size_t boundarysize;
+ curl_mimepart *part;
+
+ if(!mime)
+ return 0; /* Not present -> empty. */
+
+ boundarysize = 4 + strlen(mime->boundary) + 2;
+ size = boundarysize; /* Final boundary - CRLF after headers. */
+
+ for(part = mime->firstpart; part; part = part->nextpart) {
+ sz = Curl_mime_size(part);
+
+ if(sz < 0)
+ size = sz;
+
+ if(size >= 0)
+ size += boundarysize + sz;
+ }
+
+ return size;
+}
+
+/* Get/compute mime size. */
+curl_off_t Curl_mime_size(curl_mimepart *part)
+{
+ curl_off_t size;
+
+ if(part->datasize < 0 && part->kind == MIMEKIND_MULTIPART)
+ part->datasize = multipart_size(part->arg);
+
+ size = part->datasize;
+
+ if(part->encoder)
+ size = part->encoder->sizefunc(part);
+
+ if(size >= 0 && !(part->flags & MIME_BODY_ONLY)) {
+ /* Compute total part size. */
+ size += slist_size(part->curlheaders, 2, NULL);
+ size += slist_size(part->userheaders, 2, "Content-Type");
+ size += 2; /* CRLF after headers. */
+ }
+ return size;
+}
+
+/* Add a header. */
+/* VARARGS2 */
+CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...)
+{
+ struct curl_slist *hdr = NULL;
+ char *s = NULL;
+ va_list ap;
+
+ va_start(ap, fmt);
+ s = curl_mvaprintf(fmt, ap);
+ va_end(ap);
+
+ if(s) {
+ hdr = Curl_slist_append_nodup(*slp, s);
+ if(hdr)
+ *slp = hdr;
+ else
+ free(s);
+ }
+
+ return hdr? CURLE_OK: CURLE_OUT_OF_MEMORY;
+}
+
+/* Add a content type header. */
+static CURLcode add_content_type(struct curl_slist **slp,
+ const char *type, const char *boundary)
+{
+ return Curl_mime_add_header(slp, "Content-Type: %s%s%s", type,
+ boundary? "; boundary=": "",
+ boundary? boundary: "");
+}
+
+
+static const char *ContentTypeForFilename(const char *filename)
+{
+ unsigned int i;
+
+ /*
+ * If no content type was specified, we scan through a few well-known
+ * extensions and pick the first we match!
+ */
+ struct ContentType {
+ const char *extension;
+ const char *type;
+ };
+ static const struct ContentType ctts[] = {
+ {".gif", "image/gif"},
+ {".jpg", "image/jpeg"},
+ {".jpeg", "image/jpeg"},
+ {".png", "image/png"},
+ {".svg", "image/svg+xml"},
+ {".txt", "text/plain"},
+ {".htm", "text/html"},
+ {".html", "text/html"},
+ {".pdf", "application/pdf"},
+ {".xml", "application/xml"}
+ };
+
+ if(filename) {
+ size_t len1 = strlen(filename);
+ const char *nameend = filename + len1;
+
+ for(i = 0; i < sizeof ctts / sizeof ctts[0]; i++) {
+ size_t len2 = strlen(ctts[i].extension);
+
+ if(len1 >= len2 && strcasecompare(nameend - len2, ctts[i].extension))
+ return ctts[i].type;
+ }
+ }
+ return NULL;
+}
+
+CURLcode Curl_mime_prepare_headers(curl_mimepart *part,
+ const char *contenttype,
+ const char *disposition,
+ enum mimestrategy strategy)
+{
+ curl_mime *mime = NULL;
+ const char *boundary = NULL;
+ char *s;
+ const char *cte = NULL;
+ CURLcode ret = CURLE_OK;
+
+ /* Get rid of previously prepared headers. */
+ curl_slist_free_all(part->curlheaders);
+ part->curlheaders = NULL;
+
+ /* Be sure we won't access old headers later. */
+ if(part->state.state == MIMESTATE_CURLHEADERS)
+ mimesetstate(&part->state, MIMESTATE_CURLHEADERS, NULL);
+
+ /* Build the content-type header. */
+ s = search_header(part->userheaders, "Content-Type");
+ if(s)
+ contenttype = s;
+ if(part->mimetype)
+ contenttype = part->mimetype;
+ if(!contenttype) {
+ switch(part->kind) {
+ case MIMEKIND_MULTIPART:
+ contenttype = MULTIPART_CONTENTTYPE_DEFAULT;
+ break;
+ case MIMEKIND_FILE:
+ contenttype = ContentTypeForFilename(part->filename);
+ if(!contenttype)
+ contenttype = ContentTypeForFilename(part->data);
+ if(!contenttype && part->filename)
+ contenttype = FILE_CONTENTTYPE_DEFAULT;
+ break;
+ default:
+ contenttype = ContentTypeForFilename(part->filename);
+ break;
+ }
+ }
+
+ if(part->kind == MIMEKIND_MULTIPART) {
+ mime = (curl_mime *) part->arg;
+ if(mime)
+ boundary = mime->boundary;
+ }
+ else if(contenttype && strcasecompare(contenttype, "text/plain"))
+ if(strategy == MIMESTRATEGY_MAIL || !part->filename)
+ contenttype = NULL;
+
+ /* Issue content-disposition header only if not already set by caller. */
+ if(!search_header(part->userheaders, "Content-Disposition")) {
+ if(!disposition)
+ if(part->filename || part->name ||
+ (contenttype && !strncasecompare(contenttype, "multipart/", 10)))
+ disposition = DISPOSITION_DEFAULT;
+ if(disposition && curl_strequal(disposition, "attachment") &&
+ !part->name && !part->filename)
+ disposition = NULL;
+ if(disposition) {
+ char *name = NULL;
+ char *filename = NULL;
+
+ if(part->name) {
+ name = escape_string(part->name);
+ if(!name)
+ ret = CURLE_OUT_OF_MEMORY;
+ }
+ if(!ret && part->filename) {
+ filename = escape_string(part->filename);
+ if(!filename)
+ ret = CURLE_OUT_OF_MEMORY;
+ }
+ if(!ret)
+ ret = Curl_mime_add_header(&part->curlheaders,
+ "Content-Disposition: %s%s%s%s%s%s%s",
+ disposition,
+ name? "; name=\"": "",
+ name? name: "",
+ name? "\"": "",
+ filename? "; filename=\"": "",
+ filename? filename: "",
+ filename? "\"": "");
+ Curl_safefree(name);
+ Curl_safefree(filename);
+ if(ret)
+ return ret;
+ }
+ }
+
+ /* Issue Content-Type header. */
+ if(contenttype) {
+ ret = add_content_type(&part->curlheaders, contenttype, boundary);
+ if(ret)
+ return ret;
+ }
+
+ /* Content-Transfer-Encoding header. */
+ if(!search_header(part->userheaders, "Content-Transfer-Encoding")) {
+ if(part->encoder)
+ cte = part->encoder->name;
+ else if(contenttype && strategy == MIMESTRATEGY_MAIL &&
+ part->kind != MIMEKIND_MULTIPART)
+ cte = "8bit";
+ if(cte) {
+ ret = Curl_mime_add_header(&part->curlheaders,
+ "Content-Transfer-Encoding: %s", cte);
+ if(ret)
+ return ret;
+ }
+ }
+
+ /* If we were reading curl-generated headers, restart with new ones (this
+ should not occur). */
+ if(part->state.state == MIMESTATE_CURLHEADERS)
+ mimesetstate(&part->state, MIMESTATE_CURLHEADERS, part->curlheaders);
+
+ /* Process subparts. */
+ if(part->kind == MIMEKIND_MULTIPART && mime) {
+ curl_mimepart *subpart;
+
+ disposition = NULL;
+ if(strcasecompare(contenttype, "multipart/form-data"))
+ disposition = "form-data";
+ for(subpart = mime->firstpart; subpart; subpart = subpart->nextpart) {
+ ret = Curl_mime_prepare_headers(subpart, NULL, disposition, strategy);
+ if(ret)
+ return ret;
+ }
+ }
+ return ret;
+}
+
+#else /* !CURL_DISABLE_HTTP || !CURL_DISABLE_SMTP || !CURL_DISABLE_IMAP */
+
+/* Mime not compiled in: define stubs for externally-referenced functions. */
+curl_mime *curl_mime_init(CURL *easy)
+{
+ (void) easy;
+ return NULL;
+}
+
+void curl_mime_free(curl_mime *mime)
+{
+ (void) mime;
+}
+
+curl_mimepart *curl_mime_addpart(curl_mime *mime)
+{
+ (void) mime;
+ return NULL;
+}
+
+CURLcode curl_mime_name(curl_mimepart *part, const char *name)
+{
+ (void) part;
+ (void) name;
+ return CURLE_NOT_BUILT_IN;
+}
+
+CURLcode curl_mime_filename(curl_mimepart *part, const char *filename)
+{
+ (void) part;
+ (void) filename;
+ return CURLE_NOT_BUILT_IN;
+}
+
+CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype)
+{
+ (void) part;
+ (void) mimetype;
+ return CURLE_NOT_BUILT_IN;
+}
+
+CURLcode curl_mime_encoder(curl_mimepart *part, const char *encoding)
+{
+ (void) part;
+ (void) encoding;
+ return CURLE_NOT_BUILT_IN;
+}
+
+CURLcode curl_mime_data(curl_mimepart *part,
+ const char *data, size_t datasize)
+{
+ (void) part;
+ (void) data;
+ (void) datasize;
+ return CURLE_NOT_BUILT_IN;
+}
+
+CURLcode curl_mime_filedata(curl_mimepart *part, const char *filename)
+{
+ (void) part;
+ (void) filename;
+ return CURLE_NOT_BUILT_IN;
+}
+
+CURLcode curl_mime_data_cb(curl_mimepart *part,
+ curl_off_t datasize,
+ curl_read_callback readfunc,
+ curl_seek_callback seekfunc,
+ curl_free_callback freefunc,
+ void *arg)
+{
+ (void) part;
+ (void) datasize;
+ (void) readfunc;
+ (void) seekfunc;
+ (void) freefunc;
+ (void) arg;
+ return CURLE_NOT_BUILT_IN;
+}
+
+CURLcode curl_mime_subparts(curl_mimepart *part, curl_mime *subparts)
+{
+ (void) part;
+ (void) subparts;
+ return CURLE_NOT_BUILT_IN;
+}
+
+CURLcode curl_mime_headers(curl_mimepart *part,
+ struct curl_slist *headers, int take_ownership)
+{
+ (void) part;
+ (void) headers;
+ (void) take_ownership;
+ return CURLE_NOT_BUILT_IN;
+}
+
+void Curl_mime_initpart(curl_mimepart *part, struct Curl_easy *easy)
+{
+ (void) part;
+ (void) easy;
+}
+
+void Curl_mime_cleanpart(curl_mimepart *part)
+{
+ (void) part;
+}
+
+CURLcode Curl_mime_prepare_headers(curl_mimepart *part,
+ const char *contenttype,
+ const char *disposition,
+ enum mimestrategy strategy)
+{
+ (void) part;
+ (void) contenttype;
+ (void) disposition;
+ (void) strategy;
+ return CURLE_NOT_BUILT_IN;
+}
+
+curl_off_t Curl_mime_size(curl_mimepart *part)
+{
+ (void) part;
+ return (curl_off_t) -1;
+}
+
+size_t Curl_mime_read(char *buffer, size_t size, size_t nitems, void *instream)
+{
+ (void) buffer;
+ (void) size;
+ (void) nitems;
+ (void) instream;
+ return 0;
+}
+
+CURLcode Curl_mime_rewind(curl_mimepart *part)
+{
+ (void) part;
+ return CURLE_NOT_BUILT_IN;
+}
+
+/* VARARGS2 */
+CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...)
+{
+ (void) slp;
+ (void) fmt;
+ return CURLE_NOT_BUILT_IN;
+}
+
+#endif /* !CURL_DISABLE_HTTP || !CURL_DISABLE_SMTP || !CURL_DISABLE_IMAP */
diff --git a/Utilities/cmcurl/lib/mime.h b/Utilities/cmcurl/lib/mime.h
new file mode 100644
index 000000000..a14485707
--- /dev/null
+++ b/Utilities/cmcurl/lib/mime.h
@@ -0,0 +1,135 @@
+#ifndef HEADER_CURL_MIME_H
+#define HEADER_CURL_MIME_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#define MIME_RAND_BOUNDARY_CHARS 16 /* Nb. of random boundary chars. */
+#define MAX_ENCODED_LINE_LENGTH 76 /* Maximum encoded line length. */
+#define ENCODING_BUFFER_SIZE 256 /* Encoding temp buffers size. */
+
+/* Part flags. */
+#define MIME_USERHEADERS_OWNER (1 << 0)
+#define MIME_BODY_ONLY (1 << 1)
+
+/* Part source kinds. */
+enum mimekind {
+ MIMEKIND_NONE = 0, /* Part not set. */
+ MIMEKIND_DATA, /* Allocated mime data. */
+ MIMEKIND_FILE, /* Data from file. */
+ MIMEKIND_CALLBACK, /* Data from `read' callback. */
+ MIMEKIND_MULTIPART, /* Data is a mime subpart. */
+ MIMEKIND_LAST
+};
+
+/* Readback state tokens. */
+enum mimestate {
+ MIMESTATE_BEGIN, /* Readback has not yet started. */
+ MIMESTATE_CURLHEADERS, /* In curl-generated headers. */
+ MIMESTATE_USERHEADERS, /* In caller's supplied headers. */
+ MIMESTATE_EOH, /* End of headers. */
+ MIMESTATE_BODY, /* Placeholder. */
+ MIMESTATE_BOUNDARY1, /* In boundary prefix. */
+ MIMESTATE_BOUNDARY2, /* In boundary. */
+ MIMESTATE_CONTENT, /* In content. */
+ MIMESTATE_END, /* End of part reached. */
+ MIMESTATE_LAST
+};
+
+/* Mime headers strategies. */
+enum mimestrategy {
+ MIMESTRATEGY_MAIL, /* Mime mail. */
+ MIMESTRATEGY_FORM, /* HTTP post form. */
+ MIMESTRATEGY_LAST
+};
+
+/* Content transfer encoder. */
+typedef struct {
+ const char * name; /* Encoding name. */
+ size_t (*encodefunc)(char *buffer, size_t size, bool ateof,
+ curl_mimepart *part); /* Encoded read. */
+ curl_off_t (*sizefunc)(curl_mimepart *part); /* Encoded size. */
+} mime_encoder;
+
+/* Content transfer encoder state. */
+typedef struct {
+ size_t pos; /* Position on output line. */
+ size_t bufbeg; /* Next data index in input buffer. */
+ size_t bufend; /* First unused byte index in input buffer. */
+ char buf[ENCODING_BUFFER_SIZE]; /* Input buffer. */
+} mime_encoder_state;
+
+/* Mime readback state. */
+typedef struct {
+ enum mimestate state; /* Current state token. */
+ void *ptr; /* State-dependent pointer. */
+ size_t offset; /* State-dependent offset. */
+} mime_state;
+
+/* A mime multipart. */
+struct curl_mime_s {
+ struct Curl_easy *easy; /* The associated easy handle. */
+ curl_mimepart *parent; /* Parent part. */
+ curl_mimepart *firstpart; /* First part. */
+ curl_mimepart *lastpart; /* Last part. */
+ char *boundary; /* The part boundary. */
+ mime_state state; /* Current readback state. */
+};
+
+/* A mime part. */
+struct curl_mimepart_s {
+ struct Curl_easy *easy; /* The associated easy handle. */
+ curl_mime *parent; /* Parent mime structure. */
+ curl_mimepart *nextpart; /* Forward linked list. */
+ enum mimekind kind; /* The part kind. */
+ char *data; /* Memory data or file name. */
+ curl_read_callback readfunc; /* Read function. */
+ curl_seek_callback seekfunc; /* Seek function. */
+ curl_free_callback freefunc; /* Argument free function. */
+ void *arg; /* Argument to callback functions. */
+ FILE *fp; /* File pointer. */
+ struct curl_slist *curlheaders; /* Part headers. */
+ struct curl_slist *userheaders; /* Part headers. */
+ char *mimetype; /* Part mime type. */
+ char *filename; /* Remote file name. */
+ char *name; /* Data name. */
+ curl_off_t datasize; /* Expected data size. */
+ unsigned int flags; /* Flags. */
+ mime_state state; /* Current readback state. */
+ const mime_encoder *encoder; /* Content data encoder. */
+ mime_encoder_state encstate; /* Data encoder state. */
+};
+
+
+/* Prototypes. */
+void Curl_mime_initpart(curl_mimepart *part, struct Curl_easy *easy);
+void Curl_mime_cleanpart(curl_mimepart *part);
+CURLcode Curl_mime_prepare_headers(curl_mimepart *part,
+ const char *contenttype,
+ const char *disposition,
+ enum mimestrategy strategy);
+curl_off_t Curl_mime_size(curl_mimepart *part);
+size_t Curl_mime_read(char *buffer, size_t size, size_t nitems,
+ void *instream);
+CURLcode Curl_mime_rewind(curl_mimepart *part);
+CURLcode Curl_mime_add_header(struct curl_slist **slp, const char *fmt, ...);
+
+#endif /* HEADER_CURL_MIME_H */
diff --git a/Utilities/cmcurl/lib/mprintf.c b/Utilities/cmcurl/lib/mprintf.c
index eb7ee0c6b..d2d91d743 100644
--- a/Utilities/cmcurl/lib/mprintf.c
+++ b/Utilities/cmcurl/lib/mprintf.c
@@ -46,10 +46,6 @@
* If SIZEOF_SIZE_T has not been defined, default to the size of long.
*/
-#ifndef SIZEOF_SIZE_T
-# define SIZEOF_SIZE_T CURL_SIZEOF_LONG
-#endif
-
#ifdef HAVE_LONGLONG
# define LONG_LONG_TYPE long long
# define HAVE_LONG_LONG_TYPE
@@ -111,7 +107,7 @@ static const char upper_digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
} WHILE_FALSE
/* Data type to read from the arglist */
-typedef enum {
+typedef enum {
FORMAT_UNKNOWN = 0,
FORMAT_STRING,
FORMAT_PTR,
@@ -181,7 +177,7 @@ struct asprintf {
static long dprintf_DollarString(char *input, char **end)
{
- int number=0;
+ int number = 0;
while(ISDIGIT(*input)) {
number *= 10;
number += *input-'0';
@@ -237,7 +233,7 @@ static int dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
long width;
long precision;
int flags;
- long max_param=0;
+ long max_param = 0;
long i;
while(*fmt) {
@@ -326,7 +322,7 @@ static int dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
break;
#if defined(MP_HAVE_INT_EXTENSIONS)
case 'I':
-#if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG)
+#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
flags |= FLAGS_LONGLONG;
#else
flags |= FLAGS_LONG;
@@ -348,14 +344,14 @@ static int dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
case 'z':
/* the code below generates a warning if -Wunreachable-code is
used */
-#if (SIZEOF_SIZE_T > CURL_SIZEOF_LONG)
+#if (SIZEOF_SIZE_T > SIZEOF_LONG)
flags |= FLAGS_LONGLONG;
#else
flags |= FLAGS_LONG;
#endif
break;
case 'O':
-#if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG)
+#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
flags |= FLAGS_LONGLONG;
#else
flags |= FLAGS_LONG;
@@ -380,7 +376,7 @@ static int dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
else
width = param_num;
if(width > max_param)
- max_param=width;
+ max_param = width;
break;
default:
break;
@@ -486,7 +482,7 @@ static int dprintf_Pass1(const char *format, va_stack_t *vto, char **endpos,
}
/* Read the arg list parameters into our data list */
- for(i=0; i<max_param; i++) {
+ for(i = 0; i<max_param; i++) {
/* Width/precision arguments must be read before the main argument
they are attached to */
if(vto[i].flags & FLAGS_WIDTHPARAM) {
@@ -573,7 +569,7 @@ static int dprintf_formatf(
int done = 0;
long param; /* current parameter to read */
- long param_num=0; /* parameter counter */
+ long param_num = 0; /* parameter counter */
va_stack_t vto[MAX_PARAMETERS];
char *endpos[MAX_PARAMETERS];
@@ -643,7 +639,7 @@ static int dprintf_formatf(
/* If this is a positional parameter, the position must follow immediately
after the %, thus create a %<num>$ sequence */
- param=dprintf_DollarString(f, &f);
+ param = dprintf_DollarString(f, &f);
if(!param)
param = param_num;
@@ -952,7 +948,7 @@ static int dprintf_formatf(
output characters */
(sprintf)(work, formatbuf, p->data.dnum);
DEBUGASSERT(strlen(work) <= sizeof(work));
- for(fptr=work; *fptr; fptr++)
+ for(fptr = work; *fptr; fptr++)
OUTCHAR(*fptr);
}
break;
@@ -984,7 +980,7 @@ static int dprintf_formatf(
/* fputc() look-alike */
static int addbyter(int output, FILE *data)
{
- struct nsprintf *infop=(struct nsprintf *)data;
+ struct nsprintf *infop = (struct nsprintf *)data;
unsigned char outc = (unsigned char)output;
if(infop->length < infop->max) {
@@ -1032,7 +1028,7 @@ int curl_msnprintf(char *buffer, size_t maxlength, const char *format, ...)
/* fputc() look-alike */
static int alloc_addbyter(int output, FILE *data)
{
- struct asprintf *infop=(struct asprintf *)data;
+ struct asprintf *infop = (struct asprintf *)data;
unsigned char outc = (unsigned char)output;
if(!infop->buffer) {
@@ -1042,9 +1038,9 @@ static int alloc_addbyter(int output, FILE *data)
return -1; /* fail */
}
infop->alloc = 32;
- infop->len =0;
+ infop->len = 0;
}
- else if(infop->len+1 >= infop->alloc) {
+ else if(infop->len + 1 >= infop->alloc) {
char *newptr = NULL;
size_t newsize = infop->alloc*2;
@@ -1133,7 +1129,7 @@ int curl_msprintf(char *buffer, const char *format, ...)
va_start(ap_save, format);
retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
va_end(ap_save);
- *buffer=0; /* we terminate this with a zero byte */
+ *buffer = 0; /* we terminate this with a zero byte */
return retcode;
}
@@ -1162,7 +1158,7 @@ int curl_mvsprintf(char *buffer, const char *format, va_list ap_save)
{
int retcode;
retcode = dprintf_formatf(&buffer, storebuffer, format, ap_save);
- *buffer=0; /* we terminate this with a zero byte */
+ *buffer = 0; /* we terminate this with a zero byte */
return retcode;
}
diff --git a/Utilities/cmcurl/lib/multi.c b/Utilities/cmcurl/lib/multi.c
index c3a0d122c..70aa6bcf9 100644
--- a/Utilities/cmcurl/lib/multi.c
+++ b/Utilities/cmcurl/lib/multi.c
@@ -44,6 +44,7 @@
#include "sigpipe.h"
#include "vtls/vtls.h"
#include "connect.h"
+#include "http_proxy.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
@@ -69,7 +70,7 @@ static void singlesocket(struct Curl_multi *multi,
struct Curl_easy *data);
static int update_timer(struct Curl_multi *multi);
-static CURLMcode add_next_timeout(struct timeval now,
+static CURLMcode add_next_timeout(struct curltime now,
struct Curl_multi *multi,
struct Curl_easy *d);
static CURLMcode multi_timeout(struct Curl_multi *multi,
@@ -114,6 +115,13 @@ static void mstate(struct Curl_easy *data, CURLMstate state
NULL,
NULL,
Curl_init_CONNECT, /* CONNECT */
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ Curl_connect_free /* DO */
/* the rest is NULL too */
};
@@ -584,7 +592,7 @@ static CURLcode multi_done(struct connectdata **connp,
/* if the transfer was completed in a paused state there can be buffered
data left to free */
- for(i=0; i < data->state.tempcount; i++) {
+ for(i = 0; i < data->state.tempcount; i++) {
free(data->state.tempwrite[i].buf);
}
data->state.tempcount = 0;
@@ -794,8 +802,8 @@ static int waitconnect_getsock(struct connectdata *conn,
int numsocks)
{
int i;
- int s=0;
- int rc=0;
+ int s = 0;
+ int rc = 0;
if(!numsocks)
return GETSOCK_BLANK;
@@ -805,7 +813,7 @@ static int waitconnect_getsock(struct connectdata *conn,
return Curl_ssl_getsock(conn, sock, numsocks);
#endif
- for(i=0; i<2; i++) {
+ for(i = 0; i<2; i++) {
if(conn->tempsock[i] != CURL_SOCKET_BAD) {
sock[s] = conn->tempsock[i];
rc |= GETSOCK_WRITESOCK(s++);
@@ -826,7 +834,7 @@ static int waitproxyconnect_getsock(struct connectdata *conn,
/* when we've sent a CONNECT to a proxy, we should rather wait for the
socket to become readable to be able to get the response headers */
- if(conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
+ if(conn->connect_state)
return GETSOCK_READSOCK(0);
return GETSOCK_WRITESOCK(0);
@@ -916,7 +924,7 @@ CURLMcode curl_multi_fdset(struct Curl_multi *multi,
Some easy handles may not have connected to the remote host yet,
and then we must make sure that is done. */
struct Curl_easy *data;
- int this_max_fd=-1;
+ int this_max_fd = -1;
curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
int bitmap;
int i;
@@ -925,11 +933,11 @@ CURLMcode curl_multi_fdset(struct Curl_multi *multi,
if(!GOOD_MULTI_HANDLE(multi))
return CURLM_BAD_HANDLE;
- data=multi->easyp;
+ data = multi->easyp;
while(data) {
bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
- for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {
+ for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
curl_socket_t s = CURL_SOCKET_BAD;
if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) {
@@ -986,11 +994,11 @@ CURLMcode curl_multi_wait(struct Curl_multi *multi,
timeout_ms = (int)timeout_internal;
/* Count up how many fds we have from the multi handle */
- data=multi->easyp;
+ data = multi->easyp;
while(data) {
bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
- for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {
+ for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
curl_socket_t s = CURL_SOCKET_BAD;
if(bitmap & GETSOCK_READSOCK(i)) {
@@ -1014,6 +1022,10 @@ CURLMcode curl_multi_wait(struct Curl_multi *multi,
if(nfds) {
if(nfds > NUM_POLLS_ON_STACK) {
+ /* 'nfds' is a 32 bit value and 'struct pollfd' is typically 8 bytes
+ big, so at 2^29 sockets this value might wrap. When a process gets
+ the capability to actually handle over 500 million sockets this
+ calculation needs a integer overflow check. */
ufds = malloc(nfds * sizeof(struct pollfd));
if(!ufds)
return CURLM_OUT_OF_MEMORY;
@@ -1029,11 +1041,11 @@ CURLMcode curl_multi_wait(struct Curl_multi *multi,
if(curlfds) {
/* Add the curl handles to our pollfds first */
- data=multi->easyp;
+ data = multi->easyp;
while(data) {
bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
- for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {
+ for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) {
curl_socket_t s = CURL_SOCKET_BAD;
if(bitmap & GETSOCK_READSOCK(i)) {
@@ -1217,15 +1229,15 @@ static CURLcode multi_reconnect_request(struct connectdata **connp)
*/
static void do_complete(struct connectdata *conn)
{
- conn->data->req.chunk=FALSE;
+ conn->data->req.chunk = FALSE;
conn->data->req.maxfd = (conn->sockfd>conn->writesockfd?
- conn->sockfd:conn->writesockfd)+1;
+ conn->sockfd:conn->writesockfd) + 1;
Curl_pgrsTime(conn->data, TIMER_PRETRANSFER);
}
static CURLcode multi_do(struct connectdata **connp, bool *done)
{
- CURLcode result=CURLE_OK;
+ CURLcode result = CURLE_OK;
struct connectdata *conn = *connp;
struct Curl_easy *data = conn->data;
@@ -1274,7 +1286,7 @@ static CURLcode multi_do(struct connectdata **connp, bool *done)
static CURLcode multi_do_more(struct connectdata *conn, int *complete)
{
- CURLcode result=CURLE_OK;
+ CURLcode result = CURLE_OK;
*complete = 0;
@@ -1289,7 +1301,7 @@ static CURLcode multi_do_more(struct connectdata *conn, int *complete)
}
static CURLMcode multi_runsingle(struct Curl_multi *multi,
- struct timeval now,
+ struct curltime now,
struct Curl_easy *data)
{
struct Curl_message *msg = NULL;
@@ -1403,7 +1415,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
switch(data->mstate) {
case CURLM_STATE_INIT:
/* init this transfer. */
- result=Curl_pretransfer(data);
+ result = Curl_pretransfer(data);
if(!result) {
/* after init, go CONNECT */
@@ -1455,7 +1467,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
CURLM_STATE_WAITDO:CURLM_STATE_DO);
else {
#ifndef CURL_DISABLE_HTTP
- if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
+ if(Curl_connect_ongoing(data->easy_conn))
multistate(data, CURLM_STATE_WAITPROXYCONNECT);
else
#endif
@@ -1520,7 +1532,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
CURLM_STATE_WAITDO:CURLM_STATE_DO);
else {
#ifndef CURL_DISABLE_HTTP
- if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
+ if(Curl_connect_ongoing(data->easy_conn))
multistate(data, CURLM_STATE_WAITPROXYCONNECT);
else
#endif
@@ -1552,7 +1564,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
else if(!result) {
if((data->easy_conn->http_proxy.proxytype != CURLPROXY_HTTPS ||
data->easy_conn->bits.proxy_ssl_connected[FIRSTSOCKET]) &&
- (data->easy_conn->tunnel_state[FIRSTSOCKET] != TUNNEL_CONNECT)) {
+ Curl_connect_complete(data->easy_conn)) {
rc = CURLM_CALL_MULTI_PERFORM;
/* initiate protocol connect phase */
multistate(data, CURLM_STATE_SENDPROTOCONNECT);
@@ -1568,7 +1580,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
#ifndef CURL_DISABLE_HTTP
if((data->easy_conn->http_proxy.proxytype == CURLPROXY_HTTPS &&
!data->easy_conn->bits.proxy_ssl_connected[FIRSTSOCKET]) ||
- (data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)) {
+ Curl_connect_ongoing(data->easy_conn)) {
multistate(data, CURLM_STATE_WAITPROXYCONNECT);
break;
}
@@ -1685,7 +1697,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
* back to the CONNECT phase so we can try again.
*/
char *newurl = NULL;
- followtype follow=FOLLOW_NONE;
+ followtype follow = FOLLOW_NONE;
CURLcode drc;
bool retry = FALSE;
@@ -1771,7 +1783,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
if(control) {
/* if positive, advance to DO_DONE
if negative, go back to DOING */
- multistate(data, control==1?
+ multistate(data, control == 1?
CURLM_STATE_DO_DONE:
CURLM_STATE_DOING);
rc = CURLM_CALL_MULTI_PERFORM;
@@ -1926,7 +1938,7 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
multi_done(&data->easy_conn, result, TRUE);
}
else if(done) {
- followtype follow=FOLLOW_NONE;
+ followtype follow = FOLLOW_NONE;
/* call this even if the readwrite function returned error */
Curl_posttransfer(data);
@@ -2132,14 +2144,14 @@ static CURLMcode multi_runsingle(struct Curl_multi *multi,
CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles)
{
struct Curl_easy *data;
- CURLMcode returncode=CURLM_OK;
+ CURLMcode returncode = CURLM_OK;
struct Curl_tree *t;
- struct timeval now = Curl_tvnow();
+ struct curltime now = Curl_tvnow();
if(!GOOD_MULTI_HANDLE(multi))
return CURLM_BAD_HANDLE;
- data=multi->easyp;
+ data = multi->easyp;
while(data) {
CURLMcode result;
SIGPIPE_VARIABLE(pipe_st);
@@ -2234,7 +2246,7 @@ CURLMcode curl_multi_cleanup(struct Curl_multi *multi)
/* remove all easy handles */
data = multi->easyp;
while(data) {
- nextdata=data->next;
+ nextdata = data->next;
if(data->dns.hostcachetype == HCACHE_MULTI) {
/* clear out the usage of the shared DNS cache */
Curl_hostcache_clean(data, data->dns.hostcache);
@@ -2314,7 +2326,7 @@ static void singlesocket(struct Curl_multi *multi,
int num;
unsigned int curraction;
- for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++)
+ for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++)
socks[i] = CURL_SOCKET_BAD;
/* Fill in the 'current' struct with the state as it is now: what sockets to
@@ -2326,7 +2338,7 @@ static void singlesocket(struct Curl_multi *multi,
longer supervised ones and add new ones */
/* walk over the sockets we got right now */
- for(i=0; (i< MAX_SOCKSPEREASYHANDLE) &&
+ for(i = 0; (i< MAX_SOCKSPEREASYHANDLE) &&
(curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i)));
i++) {
int action = CURL_POLL_NONE;
@@ -2370,10 +2382,10 @@ static void singlesocket(struct Curl_multi *multi,
/* when we've walked over all the sockets we should have right now, we must
make sure to detect sockets that are removed */
- for(i=0; i< data->numsocks; i++) {
+ for(i = 0; i< data->numsocks; i++) {
int j;
s = data->sockets[i];
- for(j=0; j<num; j++) {
+ for(j = 0; j<num; j++) {
if(s == socks[j]) {
/* this is still supervised */
s = CURL_SOCKET_BAD;
@@ -2484,11 +2496,11 @@ void Curl_multi_closed(struct connectdata *conn, curl_socket_t s)
* The splay tree only has each sessionhandle as a single node and the nearest
* timeout is used to sort it on.
*/
-static CURLMcode add_next_timeout(struct timeval now,
+static CURLMcode add_next_timeout(struct curltime now,
struct Curl_multi *multi,
struct Curl_easy *d)
{
- struct timeval *tv = &d->state.expiretime;
+ struct curltime *tv = &d->state.expiretime;
struct curl_llist *list = &d->state.timeoutlist;
struct curl_llist_element *e;
struct time_node *node = NULL;
@@ -2520,10 +2532,8 @@ static CURLMcode add_next_timeout(struct timeval now,
/* copy the first entry to 'tv' */
memcpy(tv, &node->time, sizeof(*tv));
- /* remove first entry from list */
- Curl_llist_remove(list, e, NULL);
-
- /* insert this node again into the splay */
+ /* Insert this node again into the splay. Keep the timer in the list in
+ case we need to recompute future timers. */
multi->timetree = Curl_splayinsert(*tv, multi->timetree,
&d->state.timenode);
}
@@ -2539,7 +2549,7 @@ static CURLMcode multi_socket(struct Curl_multi *multi,
CURLMcode result = CURLM_OK;
struct Curl_easy *data = NULL;
struct Curl_tree *t;
- struct timeval now = Curl_tvnow();
+ struct curltime now = Curl_tvnow();
if(checkall) {
/* *perform() deals with running_handles on its own */
@@ -2548,7 +2558,7 @@ static CURLMcode multi_socket(struct Curl_multi *multi,
/* walk through each easy handle and do the socket state change magic
and callbacks */
if(result != CURLM_BAD_HANDLE) {
- data=multi->easyp;
+ data = multi->easyp;
while(data) {
singlesocket(multi, data);
data = data->next;
@@ -2765,11 +2775,11 @@ CURLMcode curl_multi_socket_all(struct Curl_multi *multi, int *running_handles)
static CURLMcode multi_timeout(struct Curl_multi *multi,
long *timeout_ms)
{
- static struct timeval tv_zero = {0, 0};
+ static struct curltime tv_zero = {0, 0};
if(multi->timetree) {
/* we have a tree of expire times */
- struct timeval now = Curl_tvnow();
+ struct curltime now = Curl_tvnow();
/* splay the lowest to the bottom */
multi->timetree = Curl_splay(tv_zero, multi->timetree);
@@ -2785,7 +2795,7 @@ static CURLMcode multi_timeout(struct Curl_multi *multi,
* processors while the diff is still present but less than one
* millisecond! instead we return 1 until the time is ripe.
*/
- *timeout_ms=1;
+ *timeout_ms = 1;
}
else
/* 0 means immediately */
@@ -2821,7 +2831,7 @@ static int update_timer(struct Curl_multi *multi)
return -1;
}
if(timeout_ms < 0) {
- static const struct timeval none={0, 0};
+ static const struct curltime none = {0, 0};
if(Curl_splaycomparekeys(none, multi->timer_lastcall)) {
multi->timer_lastcall = none;
/* there's no timeout now but there was one previously, tell the app to
@@ -2872,7 +2882,7 @@ multi_deltimeout(struct Curl_easy *data, expire_id eid)
*/
static CURLMcode
multi_addtimeout(struct Curl_easy *data,
- struct timeval *stamp,
+ struct curltime *stamp,
expire_id eid)
{
struct curl_llist_element *e;
@@ -2920,9 +2930,9 @@ multi_addtimeout(struct Curl_easy *data,
void Curl_expire(struct Curl_easy *data, time_t milli, expire_id id)
{
struct Curl_multi *multi = data->multi;
- struct timeval *nowp = &data->state.expiretime;
+ struct curltime *nowp = &data->state.expiretime;
int rc;
- struct timeval set;
+ struct curltime set;
/* this is only interesting while there is still an associated multi struct
remaining! */
@@ -2932,34 +2942,33 @@ void Curl_expire(struct Curl_easy *data, time_t milli, expire_id id)
DEBUGASSERT(id < EXPIRE_LAST);
set = Curl_tvnow();
- set.tv_sec += (long)(milli/1000);
- set.tv_usec += (long)(milli%1000)*1000;
+ set.tv_sec += milli/1000;
+ set.tv_usec += (unsigned int)(milli%1000)*1000;
if(set.tv_usec >= 1000000) {
set.tv_sec++;
set.tv_usec -= 1000000;
}
+ /* Remove any timer with the same id just in case. */
+ multi_deltimeout(data, id);
+
+ /* Add it to the timer list. It must stay in the list until it has expired
+ in case we need to recompute the minimum timer later. */
+ multi_addtimeout(data, &set, id);
+
if(nowp->tv_sec || nowp->tv_usec) {
/* This means that the struct is added as a node in the splay tree.
Compare if the new time is earlier, and only remove-old/add-new if it
is. */
time_t diff = curlx_tvdiff(set, *nowp);
- /* remove the previous timer first, if there */
- multi_deltimeout(data, id);
-
if(diff > 0) {
- /* the new expire time was later so just add it to the queue
- and get out */
- multi_addtimeout(data, &set, id);
+ /* The current splay tree entry is sooner than this new expiry time.
+ We don't need to update our splay tree entry. */
return;
}
- /* the new time is newer than the presently set one, so add the current
- to the queue and update the head */
- multi_addtimeout(data, nowp, id);
-
/* Since this is an updated time, we must remove the previous entry from
the splay tree first and then re-add the new value */
rc = Curl_splayremovebyaddr(multi->timetree,
@@ -2969,6 +2978,8 @@ void Curl_expire(struct Curl_easy *data, time_t milli, expire_id id)
infof(data, "Internal error removing splay node = %d\n", rc);
}
+ /* Indicate that we are in the splay tree and insert the new timer expiry
+ value since it is our local minimum. */
*nowp = set;
data->state.timenode.payload = data;
multi->timetree = Curl_splayinsert(*nowp, multi->timetree,
@@ -2995,7 +3006,7 @@ void Curl_expire_done(struct Curl_easy *data, expire_id id)
void Curl_expire_clear(struct Curl_easy *data)
{
struct Curl_multi *multi = data->multi;
- struct timeval *nowp = &data->state.expiretime;
+ struct curltime *nowp = &data->state.expiretime;
int rc;
/* this is only interesting while there is still an associated multi struct
@@ -3104,13 +3115,13 @@ void Curl_multi_dump(struct Curl_multi *multi)
int i;
fprintf(stderr, "* Multi status: %d handles, %d alive\n",
multi->num_easy, multi->num_alive);
- for(data=multi->easyp; data; data = data->next) {
+ for(data = multi->easyp; data; data = data->next) {
if(data->mstate < CURLM_STATE_COMPLETED) {
/* only display handles that are not completed */
fprintf(stderr, "handle %p, state %s, %d sockets\n",
(void *)data,
statename[data->mstate], data->numsocks);
- for(i=0; i < data->numsocks; i++) {
+ for(i = 0; i < data->numsocks; i++) {
curl_socket_t s = data->sockets[i];
struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s);
diff --git a/Utilities/cmcurl/lib/multihandle.h b/Utilities/cmcurl/lib/multihandle.h
index e6ffbf5b6..405753947 100644
--- a/Utilities/cmcurl/lib/multihandle.h
+++ b/Utilities/cmcurl/lib/multihandle.h
@@ -148,7 +148,7 @@ struct Curl_multi {
/* timer callback and user data pointer for the *socket() API */
curl_multi_timer_callback timer_cb;
void *timer_userp;
- struct timeval timer_lastcall; /* the fixed time for the timeout for the
+ struct curltime timer_lastcall; /* the fixed time for the timeout for the
previous callback */
};
diff --git a/Utilities/cmcurl/lib/netrc.c b/Utilities/cmcurl/lib/netrc.c
index 996711d11..dbcc59ac9 100644
--- a/Utilities/cmcurl/lib/netrc.c
+++ b/Utilities/cmcurl/lib/netrc.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -56,14 +56,15 @@ int Curl_parsenetrc(const char *host,
char *netrcfile)
{
FILE *file;
- int retcode=1;
+ int retcode = 1;
int specific_login = (*loginp && **loginp != 0);
bool netrc_alloc = FALSE;
- enum host_lookup_state state=NOTHING;
+ enum host_lookup_state state = NOTHING;
- char state_login=0; /* Found a login keyword */
- char state_password=0; /* Found a password keyword */
- int state_our_login=FALSE; /* With specific_login, found *our* login name */
+ char state_login = 0; /* Found a login keyword */
+ char state_password = 0; /* Found a password keyword */
+ int state_our_login = FALSE; /* With specific_login, found *our* login
+ name */
#define NETRC DOT_CHAR "netrc"
@@ -88,7 +89,7 @@ int Curl_parsenetrc(const char *host,
}
else {
struct passwd *pw;
- pw= getpwuid(geteuid());
+ pw = getpwuid(geteuid());
if(pw) {
home = pw->pw_dir;
}
@@ -113,16 +114,19 @@ int Curl_parsenetrc(const char *host,
if(file) {
char *tok;
char *tok_buf;
- bool done=FALSE;
+ bool done = FALSE;
char netrcbuffer[256];
int netrcbuffsize = (int)sizeof(netrcbuffer);
while(!done && fgets(netrcbuffer, netrcbuffsize, file)) {
- tok=strtok_r(netrcbuffer, " \t\n", &tok_buf);
+ tok = strtok_r(netrcbuffer, " \t\n", &tok_buf);
+ if(tok && *tok == '#')
+ /* treat an initial hash as a comment line */
+ continue;
while(!done && tok) {
if((*loginp && **loginp) && (*passwordp && **passwordp)) {
- done=TRUE;
+ done = TRUE;
break;
}
@@ -133,22 +137,22 @@ int Curl_parsenetrc(const char *host,
delimiter that starts the stuff entered for this machine,
after this we need to search for 'login' and
'password'. */
- state=HOSTFOUND;
+ state = HOSTFOUND;
}
else if(strcasecompare("default", tok)) {
- state=HOSTVALID;
- retcode=0; /* we did find our host */
+ state = HOSTVALID;
+ retcode = 0; /* we did find our host */
}
break;
case HOSTFOUND:
if(strcasecompare(host, tok)) {
/* and yes, this is our host! */
- state=HOSTVALID;
- retcode=0; /* we did find our host */
+ state = HOSTVALID;
+ retcode = 0; /* we did find our host */
}
else
/* not our host */
- state=NOTHING;
+ state = NOTHING;
break;
case HOSTVALID:
/* we are now parsing sub-keywords concerning "our" host */
@@ -164,7 +168,7 @@ int Curl_parsenetrc(const char *host,
goto out;
}
}
- state_login=0;
+ state_login = 0;
}
else if(state_password) {
if(state_our_login || !specific_login) {
@@ -175,12 +179,12 @@ int Curl_parsenetrc(const char *host,
goto out;
}
}
- state_password=0;
+ state_password = 0;
}
else if(strcasecompare("login", tok))
- state_login=1;
+ state_login = 1;
else if(strcasecompare("password", tok))
- state_password=1;
+ state_password = 1;
else if(strcasecompare("machine", tok)) {
/* ok, there's machine here go => */
state = HOSTFOUND;
diff --git a/Utilities/cmcurl/lib/non-ascii.c b/Utilities/cmcurl/lib/non-ascii.c
index 2f5de4c68..92b2f8d73 100644
--- a/Utilities/cmcurl/lib/non-ascii.c
+++ b/Utilities/cmcurl/lib/non-ascii.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -82,7 +82,7 @@ CURLcode Curl_convert_clone(struct Curl_easy *data,
CURLcode Curl_convert_to_network(struct Curl_easy *data,
char *buffer, size_t length)
{
- if(data->set.convtonetwork) {
+ if(data && data->set.convtonetwork) {
/* use translation callback */
CURLcode result = data->set.convtonetwork(buffer, length);
if(result) {
@@ -96,34 +96,37 @@ CURLcode Curl_convert_to_network(struct Curl_easy *data,
else {
#ifdef HAVE_ICONV
/* do the translation ourselves */
+ iconv_t tmpcd = (iconv_t) -1;
+ iconv_t *cd = &tmpcd;
char *input_ptr, *output_ptr;
size_t in_bytes, out_bytes, rc;
- int error;
/* open an iconv conversion descriptor if necessary */
- if(data->outbound_cd == (iconv_t)-1) {
- data->outbound_cd = iconv_open(CURL_ICONV_CODESET_OF_NETWORK,
- CURL_ICONV_CODESET_OF_HOST);
- if(data->outbound_cd == (iconv_t)-1) {
- error = ERRNO;
+ if(data)
+ cd = &data->outbound_cd;
+ if(*cd == (iconv_t)-1) {
+ *cd = iconv_open(CURL_ICONV_CODESET_OF_NETWORK,
+ CURL_ICONV_CODESET_OF_HOST);
+ if(*cd == (iconv_t)-1) {
failf(data,
"The iconv_open(\"%s\", \"%s\") call failed with errno %i: %s",
CURL_ICONV_CODESET_OF_NETWORK,
CURL_ICONV_CODESET_OF_HOST,
- error, strerror(error));
+ errno, strerror(errno));
return CURLE_CONV_FAILED;
}
}
/* call iconv */
input_ptr = output_ptr = buffer;
in_bytes = out_bytes = length;
- rc = iconv(data->outbound_cd, (const char **)&input_ptr, &in_bytes,
+ rc = iconv(*cd, &input_ptr, &in_bytes,
&output_ptr, &out_bytes);
+ if(!data)
+ iconv_close(tmpcd);
if((rc == ICONV_ERROR) || (in_bytes != 0)) {
- error = ERRNO;
failf(data,
"The Curl_convert_to_network iconv call failed with errno %i: %s",
- error, strerror(error));
+ errno, strerror(errno));
return CURLE_CONV_FAILED;
}
#else
@@ -142,7 +145,7 @@ CURLcode Curl_convert_to_network(struct Curl_easy *data,
CURLcode Curl_convert_from_network(struct Curl_easy *data,
char *buffer, size_t length)
{
- if(data->set.convfromnetwork) {
+ if(data && data->set.convfromnetwork) {
/* use translation callback */
CURLcode result = data->set.convfromnetwork(buffer, length);
if(result) {
@@ -156,34 +159,37 @@ CURLcode Curl_convert_from_network(struct Curl_easy *data,
else {
#ifdef HAVE_ICONV
/* do the translation ourselves */
+ iconv_t tmpcd = (iconv_t) -1;
+ iconv_t *cd = &tmpcd;
char *input_ptr, *output_ptr;
size_t in_bytes, out_bytes, rc;
- int error;
/* open an iconv conversion descriptor if necessary */
- if(data->inbound_cd == (iconv_t)-1) {
- data->inbound_cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
- CURL_ICONV_CODESET_OF_NETWORK);
- if(data->inbound_cd == (iconv_t)-1) {
- error = ERRNO;
+ if(data)
+ cd = &data->inbound_cd;
+ if(*cd == (iconv_t)-1) {
+ *cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
+ CURL_ICONV_CODESET_OF_NETWORK);
+ if(*cd == (iconv_t)-1) {
failf(data,
"The iconv_open(\"%s\", \"%s\") call failed with errno %i: %s",
CURL_ICONV_CODESET_OF_HOST,
CURL_ICONV_CODESET_OF_NETWORK,
- error, strerror(error));
+ errno, strerror(errno));
return CURLE_CONV_FAILED;
}
}
/* call iconv */
input_ptr = output_ptr = buffer;
in_bytes = out_bytes = length;
- rc = iconv(data->inbound_cd, (const char **)&input_ptr, &in_bytes,
+ rc = iconv(*cd, &input_ptr, &in_bytes,
&output_ptr, &out_bytes);
+ if(!data)
+ iconv_close(tmpcd);
if((rc == ICONV_ERROR) || (in_bytes != 0)) {
- error = ERRNO;
failf(data,
"Curl_convert_from_network iconv call failed with errno %i: %s",
- error, strerror(error));
+ errno, strerror(errno));
return CURLE_CONV_FAILED;
}
#else
@@ -202,7 +208,7 @@ CURLcode Curl_convert_from_network(struct Curl_easy *data,
CURLcode Curl_convert_from_utf8(struct Curl_easy *data,
char *buffer, size_t length)
{
- if(data->set.convfromutf8) {
+ if(data && data->set.convfromutf8) {
/* use translation callback */
CURLcode result = data->set.convfromutf8(buffer, length);
if(result) {
@@ -216,35 +222,38 @@ CURLcode Curl_convert_from_utf8(struct Curl_easy *data,
else {
#ifdef HAVE_ICONV
/* do the translation ourselves */
- const char *input_ptr;
+ iconv_t tmpcd = (iconv_t) -1;
+ iconv_t *cd = &tmpcd;
+ char *input_ptr;
char *output_ptr;
size_t in_bytes, out_bytes, rc;
- int error;
/* open an iconv conversion descriptor if necessary */
- if(data->utf8_cd == (iconv_t)-1) {
- data->utf8_cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
- CURL_ICONV_CODESET_FOR_UTF8);
- if(data->utf8_cd == (iconv_t)-1) {
- error = ERRNO;
+ if(data)
+ cd = &data->utf8_cd;
+ if(*cd == (iconv_t)-1) {
+ *cd = iconv_open(CURL_ICONV_CODESET_OF_HOST,
+ CURL_ICONV_CODESET_FOR_UTF8);
+ if(*cd == (iconv_t)-1) {
failf(data,
"The iconv_open(\"%s\", \"%s\") call failed with errno %i: %s",
CURL_ICONV_CODESET_OF_HOST,
CURL_ICONV_CODESET_FOR_UTF8,
- error, strerror(error));
+ errno, strerror(errno));
return CURLE_CONV_FAILED;
}
}
/* call iconv */
input_ptr = output_ptr = buffer;
in_bytes = out_bytes = length;
- rc = iconv(data->utf8_cd, &input_ptr, &in_bytes,
+ rc = iconv(*cd, &input_ptr, &in_bytes,
&output_ptr, &out_bytes);
+ if(!data)
+ iconv_close(tmpcd);
if((rc == ICONV_ERROR) || (in_bytes != 0)) {
- error = ERRNO;
failf(data,
"The Curl_convert_from_utf8 iconv call failed with errno %i: %s",
- error, strerror(error));
+ errno, strerror(errno));
return CURLE_CONV_FAILED;
}
if(output_ptr < input_ptr) {
@@ -310,29 +319,4 @@ void Curl_convert_close(struct Curl_easy *data)
#endif /* HAVE_ICONV */
}
-/*
- * Curl_convert_form() is used from http.c, this converts any form items that
- need to be sent in the network encoding. Returns CURLE_OK on success.
- */
-CURLcode Curl_convert_form(struct Curl_easy *data, struct FormData *form)
-{
- CURLcode result;
-
- if(!data)
- return CURLE_BAD_FUNCTION_ARGUMENT;
-
- while(form) {
- if(form->type == FORM_DATA) {
- result = Curl_convert_to_network(data, form->line, form->length);
- /* Curl_convert_to_network calls failf if unsuccessful */
- if(result)
- return result;
- }
-
- form = form->next;
- }
-
- return CURLE_OK;
-}
-
#endif /* CURL_DOES_CONVERSIONS */
diff --git a/Utilities/cmcurl/lib/non-ascii.h b/Utilities/cmcurl/lib/non-ascii.h
index e27f1f41f..5fb5771e0 100644
--- a/Utilities/cmcurl/lib/non-ascii.h
+++ b/Utilities/cmcurl/lib/non-ascii.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2011, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -48,7 +48,6 @@ CURLcode Curl_convert_from_network(struct Curl_easy *data,
char *buffer, size_t length);
CURLcode Curl_convert_from_utf8(struct Curl_easy *data,
char *buffer, size_t length);
-CURLcode Curl_convert_form(struct Curl_easy *data, struct FormData *form);
#else
#define Curl_convert_clone(a,b,c,d) ((void)a, CURLE_OK)
#define Curl_convert_init(x) Curl_nop_stmt
@@ -57,7 +56,6 @@ CURLcode Curl_convert_form(struct Curl_easy *data, struct FormData *form);
#define Curl_convert_to_network(a,b,c) ((void)a, CURLE_OK)
#define Curl_convert_from_network(a,b,c) ((void)a, CURLE_OK)
#define Curl_convert_from_utf8(a,b,c) ((void)a, CURLE_OK)
-#define Curl_convert_form(a,b) CURLE_OK
#endif
#endif /* HEADER_CURL_NON_ASCII_H */
diff --git a/Utilities/cmcurl/lib/openldap.c b/Utilities/cmcurl/lib/openldap.c
index 4b8cfb9c2..f2944033b 100644
--- a/Utilities/cmcurl/lib/openldap.c
+++ b/Utilities/cmcurl/lib/openldap.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 2010, Howard Chu, <hyc@openldap.org>
+ * Copyright (C) 2010, 2017, Howard Chu, <hyc@openldap.org>
* Copyright (C) 2011 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
@@ -85,6 +85,7 @@ const struct Curl_handler Curl_handler_ldap = {
ZERO_NULL, /* perform_getsock */
ldap_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_LDAP, /* defport */
CURLPROTO_LDAP, /* protocol */
PROTOPT_NONE /* flags */
@@ -110,6 +111,7 @@ const struct Curl_handler Curl_handler_ldaps = {
ZERO_NULL, /* perform_getsock */
ldap_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_LDAPS, /* defport */
CURLPROTO_LDAP, /* protocol */
PROTOPT_SSL /* flags */
@@ -150,7 +152,7 @@ static CURLcode ldap_setup_connection(struct connectdata *conn)
{
ldapconninfo *li;
LDAPURLDesc *lud;
- struct Curl_easy *data=conn->data;
+ struct Curl_easy *data = conn->data;
int rc, proto;
CURLcode status;
@@ -196,7 +198,7 @@ static CURLcode ldap_connect(struct connectdata *conn, bool *done)
(void)done;
strcpy(hosturl, "ldap");
- ptr = hosturl+4;
+ ptr = hosturl + 4;
if(conn->handler->flags & PROTOPT_SSL)
*ptr++ = 's';
snprintf(ptr, sizeof(hosturl)-(ptr-hosturl), "://%s:%d",
@@ -352,7 +354,7 @@ static CURLcode ldap_do(struct connectdata *conn, bool *done)
int rc = 0;
LDAPURLDesc *ludp = NULL;
int msgid;
- struct Curl_easy *data=conn->data;
+ struct Curl_easy *data = conn->data;
connkeep(conn, "OpenLDAP do");
@@ -517,7 +519,7 @@ static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf,
else
binary = 0;
- for(i=0; bvals[i].bv_val != NULL; i++) {
+ for(i = 0; bvals[i].bv_val != NULL; i++) {
int binval = 0;
writeerr = Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\t", 1);
if(writeerr) {
@@ -547,7 +549,7 @@ static ssize_t ldap_recv(struct connectdata *conn, int sockindex, char *buf,
else {
/* check for unprintable characters */
unsigned int j;
- for(j=0; j<bvals[i].bv_len; j++)
+ for(j = 0; j<bvals[i].bv_len; j++)
if(!ISPRINT(bvals[i].bv_val[j])) {
binval = 1;
break;
diff --git a/Utilities/cmcurl/lib/parsedate.c b/Utilities/cmcurl/lib/parsedate.c
index 3c783be48..b82605bbe 100644
--- a/Utilities/cmcurl/lib/parsedate.c
+++ b/Utilities/cmcurl/lib/parsedate.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -167,20 +167,20 @@ static const struct tzinfo tz[]= {
RFC 1123) had their signs wrong. Here we use the correct signs to match
actual military usage.
*/
- {"A", +1 * 60}, /* Alpha */
- {"B", +2 * 60}, /* Bravo */
- {"C", +3 * 60}, /* Charlie */
- {"D", +4 * 60}, /* Delta */
- {"E", +5 * 60}, /* Echo */
- {"F", +6 * 60}, /* Foxtrot */
- {"G", +7 * 60}, /* Golf */
- {"H", +8 * 60}, /* Hotel */
- {"I", +9 * 60}, /* India */
+ {"A", 1 * 60}, /* Alpha */
+ {"B", 2 * 60}, /* Bravo */
+ {"C", 3 * 60}, /* Charlie */
+ {"D", 4 * 60}, /* Delta */
+ {"E", 5 * 60}, /* Echo */
+ {"F", 6 * 60}, /* Foxtrot */
+ {"G", 7 * 60}, /* Golf */
+ {"H", 8 * 60}, /* Hotel */
+ {"I", 9 * 60}, /* India */
/* "J", Juliet is not used as a timezone, to indicate the observer's local
time */
- {"K", +10 * 60}, /* Kilo */
- {"L", +11 * 60}, /* Lima */
- {"M", +12 * 60}, /* Mike */
+ {"K", 10 * 60}, /* Kilo */
+ {"L", 11 * 60}, /* Lima */
+ {"M", 12 * 60}, /* Mike */
{"N", -1 * 60}, /* November */
{"O", -2 * 60}, /* Oscar */
{"P", -3 * 60}, /* Papa */
@@ -205,14 +205,14 @@ static int checkday(const char *check, size_t len)
{
int i;
const char * const *what;
- bool found= FALSE;
+ bool found = FALSE;
if(len > 3)
what = &weekday[0];
else
what = &Curl_wkday[0];
- for(i=0; i<7; i++) {
+ for(i = 0; i<7; i++) {
if(strcasecompare(check, what[0])) {
- found=TRUE;
+ found = TRUE;
break;
}
what++;
@@ -224,12 +224,12 @@ static int checkmonth(const char *check)
{
int i;
const char * const *what;
- bool found= FALSE;
+ bool found = FALSE;
what = &Curl_month[0];
- for(i=0; i<12; i++) {
+ for(i = 0; i<12; i++) {
if(strcasecompare(check, what[0])) {
- found=TRUE;
+ found = TRUE;
break;
}
what++;
@@ -244,12 +244,12 @@ static int checktz(const char *check)
{
unsigned int i;
const struct tzinfo *what;
- bool found= FALSE;
+ bool found = FALSE;
what = tz;
- for(i=0; i< sizeof(tz)/sizeof(tz[0]); i++) {
+ for(i = 0; i< sizeof(tz)/sizeof(tz[0]); i++) {
if(strcasecompare(check, what->name)) {
- found=TRUE;
+ found = TRUE;
break;
}
what++;
@@ -331,21 +331,21 @@ static time_t my_timegm(struct my_tm *tm)
static int parsedate(const char *date, time_t *output)
{
time_t t = 0;
- int wdaynum=-1; /* day of the week number, 0-6 (mon-sun) */
- int monnum=-1; /* month of the year number, 0-11 */
- int mdaynum=-1; /* day of month, 1 - 31 */
- int hournum=-1;
- int minnum=-1;
- int secnum=-1;
- int yearnum=-1;
- int tzoff=-1;
+ int wdaynum = -1; /* day of the week number, 0-6 (mon-sun) */
+ int monnum = -1; /* month of the year number, 0-11 */
+ int mdaynum = -1; /* day of month, 1 - 31 */
+ int hournum = -1;
+ int minnum = -1;
+ int secnum = -1;
+ int yearnum = -1;
+ int tzoff = -1;
struct my_tm tm;
enum assume dignext = DATE_MDAY;
const char *indate = date; /* save the original pointer */
int part = 0; /* max 6 parts */
while(*date && (part < 6)) {
- bool found=FALSE;
+ bool found = FALSE;
skip(&date);
@@ -386,7 +386,7 @@ static int parsedate(const char *date, time_t *output)
/* a digit */
int val;
char *end;
- int len=0;
+ int len = 0;
if((secnum == -1) &&
(3 == sscanf(date, "%02d:%02d:%02d%n",
&hournum, &minnum, &secnum, &len))) {
@@ -404,12 +404,12 @@ static int parsedate(const char *date, time_t *output)
int error;
int old_errno;
- old_errno = ERRNO;
- SET_ERRNO(0);
+ old_errno = errno;
+ errno = 0;
lval = strtol(date, &end, 10);
- error = ERRNO;
- if(error != old_errno)
- SET_ERRNO(old_errno);
+ error = errno;
+ if(errno != old_errno)
+ errno = old_errno;
if(error)
return PARSEDATE_FAIL;
diff --git a/Utilities/cmcurl/lib/pingpong.c b/Utilities/cmcurl/lib/pingpong.c
index 5ed79b718..b8f214005 100644
--- a/Utilities/cmcurl/lib/pingpong.c
+++ b/Utilities/cmcurl/lib/pingpong.c
@@ -47,10 +47,10 @@
time_t Curl_pp_state_timeout(struct pingpong *pp)
{
struct connectdata *conn = pp->conn;
- struct Curl_easy *data=conn->data;
+ struct Curl_easy *data = conn->data;
time_t timeout_ms; /* in milliseconds */
time_t timeout2_ms; /* in milliseconds */
- long response_time= (data->set.server_response_timeout)?
+ long response_time = (data->set.server_response_timeout)?
data->set.server_response_timeout: pp->response_time;
/* if CURLOPT_SERVER_RESPONSE_TIMEOUT is set, use that to determine
@@ -85,10 +85,10 @@ CURLcode Curl_pp_statemach(struct pingpong *pp, bool block)
int rc;
time_t interval_ms;
time_t timeout_ms = Curl_pp_state_timeout(pp);
- struct Curl_easy *data=conn->data;
+ struct Curl_easy *data = conn->data;
CURLcode result = CURLE_OK;
- if(timeout_ms <=0) {
+ if(timeout_ms <= 0) {
failf(data, "server response timeout");
return CURLE_OPERATION_TIMEDOUT; /* already too little time */
}
@@ -270,7 +270,7 @@ CURLcode Curl_pp_readresp(curl_socket_t sockfd,
size_t *size) /* size of the response */
{
ssize_t perline; /* count bytes per line */
- bool keepon=TRUE;
+ bool keepon = TRUE;
ssize_t gotbytes;
char *ptr;
struct connectdata *conn = pp->conn;
@@ -281,7 +281,7 @@ CURLcode Curl_pp_readresp(curl_socket_t sockfd,
*code = 0; /* 0 for errors or not done */
*size = 0;
- ptr=buf + pp->nread_resp;
+ ptr = buf + pp->nread_resp;
/* number of bytes in the current line, so far */
perline = (ssize_t)(ptr-pp->linestart_resp);
@@ -297,7 +297,7 @@ CURLcode Curl_pp_readresp(curl_socket_t sockfd,
* it would have been populated with something of size int to begin
* with, even though its datatype may be larger than an int.
*/
- DEBUGASSERT((ptr+pp->cache_size) <= (buf+data->set.buffer_size+1));
+ DEBUGASSERT((ptr + pp->cache_size) <= (buf + data->set.buffer_size + 1));
memcpy(ptr, pp->cache, pp->cache_size);
gotbytes = (ssize_t)pp->cache_size;
free(pp->cache); /* free the cache */
@@ -351,7 +351,7 @@ CURLcode Curl_pp_readresp(curl_socket_t sockfd,
pp->nread_resp += gotbytes;
for(i = 0; i < gotbytes; ptr++, i++) {
perline++;
- if(*ptr=='\n') {
+ if(*ptr == '\n') {
/* a newline is CRLF in pp-talk, so the CR is ignored as
the line isn't really terminated until the LF comes */
@@ -378,17 +378,17 @@ CURLcode Curl_pp_readresp(curl_socket_t sockfd,
start of the buffer and zero terminate, for old times sake */
size_t n = ptr - pp->linestart_resp;
memmove(buf, pp->linestart_resp, n);
- buf[n]=0; /* zero terminate */
- keepon=FALSE;
- pp->linestart_resp = ptr+1; /* advance pointer */
+ buf[n] = 0; /* zero terminate */
+ keepon = FALSE;
+ pp->linestart_resp = ptr + 1; /* advance pointer */
i++; /* skip this before getting out */
*size = pp->nread_resp; /* size of the response */
pp->nread_resp = 0; /* restart */
break;
}
- perline=0; /* line starts over here */
- pp->linestart_resp = ptr+1;
+ perline = 0; /* line starts over here */
+ pp->linestart_resp = ptr + 1;
}
}
@@ -490,7 +490,7 @@ CURLcode Curl_pp_flushsend(struct pingpong *pp)
}
else {
free(pp->sendthis);
- pp->sendthis=NULL;
+ pp->sendthis = NULL;
pp->sendleft = pp->sendsize = 0;
pp->response = Curl_tvnow();
}
diff --git a/Utilities/cmcurl/lib/pingpong.h b/Utilities/cmcurl/lib/pingpong.h
index ee1a59b51..a2c8ff592 100644
--- a/Utilities/cmcurl/lib/pingpong.h
+++ b/Utilities/cmcurl/lib/pingpong.h
@@ -58,7 +58,7 @@ struct pingpong {
server */
size_t sendleft; /* number of bytes left to send from the sendthis buffer */
size_t sendsize; /* total size of the sendthis buffer */
- struct timeval response; /* set to Curl_tvnow() when a command has been sent
+ struct curltime response; /* set to Curl_tvnow() when a command has been sent
off, used to time-out response reading */
long response_time; /* When no timeout is given, this is the amount of
milliseconds we await for a server response. */
diff --git a/Utilities/cmcurl/lib/pipeline.c b/Utilities/cmcurl/lib/pipeline.c
index b8d203745..4d41b0413 100644
--- a/Utilities/cmcurl/lib/pipeline.c
+++ b/Utilities/cmcurl/lib/pipeline.c
@@ -230,28 +230,27 @@ CURLMcode Curl_pipeline_set_site_blacklist(char **sites,
return CURLM_OK;
}
+struct blacklist_node {
+ struct curl_llist_element list;
+ char server_name[1];
+};
+
bool Curl_pipeline_server_blacklisted(struct Curl_easy *handle,
char *server_name)
{
if(handle->multi && server_name) {
- struct curl_llist *blacklist =
+ struct curl_llist *list =
Curl_multi_pipelining_server_bl(handle->multi);
- if(blacklist) {
- struct curl_llist_element *curr;
-
- curr = blacklist->head;
- while(curr) {
- char *bl_server_name;
-
- bl_server_name = curr->ptr;
- if(strncasecompare(bl_server_name, server_name,
- strlen(bl_server_name))) {
- infof(handle, "Server %s is blacklisted\n", server_name);
- return TRUE;
- }
- curr = curr->next;
+ struct curl_llist_element *e = list->head;
+ while(e) {
+ struct blacklist_node *bl = (struct blacklist_node *)e;
+ if(strncasecompare(bl->server_name, server_name,
+ strlen(bl->server_name))) {
+ infof(handle, "Server %s is blacklisted\n", server_name);
+ return TRUE;
}
+ e = e->next;
}
DEBUGF(infof(handle, "Server %s is not blacklisted\n", server_name));
@@ -259,11 +258,6 @@ bool Curl_pipeline_server_blacklisted(struct Curl_easy *handle,
return FALSE;
}
-struct blacklist_node {
- struct curl_llist_element list;
- char server_name[1];
-};
-
CURLMcode Curl_pipeline_set_server_blacklist(char **servers,
struct curl_llist *list)
{
@@ -286,8 +280,7 @@ CURLMcode Curl_pipeline_set_server_blacklist(char **servers,
}
strcpy(n->server_name, *servers);
- Curl_llist_insert_next(list, list->tail, n->server_name,
- &n->list);
+ Curl_llist_insert_next(list, list->tail, n, &n->list);
servers++;
}
}
diff --git a/Utilities/cmcurl/lib/pop3.c b/Utilities/cmcurl/lib/pop3.c
index 3feb3be83..5792a4a6f 100644
--- a/Utilities/cmcurl/lib/pop3.c
+++ b/Utilities/cmcurl/lib/pop3.c
@@ -125,6 +125,7 @@ const struct Curl_handler Curl_handler_pop3 = {
ZERO_NULL, /* perform_getsock */
pop3_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_POP3, /* defport */
CURLPROTO_POP3, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY | /* flags */
@@ -151,6 +152,7 @@ const struct Curl_handler Curl_handler_pop3s = {
ZERO_NULL, /* perform_getsock */
pop3_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_POP3S, /* defport */
CURLPROTO_POP3S, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_SSL
@@ -158,58 +160,6 @@ const struct Curl_handler Curl_handler_pop3s = {
};
#endif
-#ifndef CURL_DISABLE_HTTP
-/*
- * HTTP-proxyed POP3 protocol handler.
- */
-
-static const struct Curl_handler Curl_handler_pop3_proxy = {
- "POP3", /* scheme */
- Curl_http_setup_conn, /* setup_connection */
- Curl_http, /* do_it */
- Curl_http_done, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
- PORT_POP3, /* defport */
- CURLPROTO_HTTP, /* protocol */
- PROTOPT_NONE /* flags */
-};
-
-#ifdef USE_SSL
-/*
- * HTTP-proxyed POP3S protocol handler.
- */
-
-static const struct Curl_handler Curl_handler_pop3s_proxy = {
- "POP3S", /* scheme */
- Curl_http_setup_conn, /* setup_connection */
- Curl_http, /* do_it */
- Curl_http_done, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
- PORT_POP3S, /* defport */
- CURLPROTO_HTTP, /* protocol */
- PROTOPT_NONE /* flags */
-};
-#endif
-#endif
-
/* SASL parameters for the pop3 protocol */
static const struct SASLproto saslpop3 = {
"pop", /* The service name */
@@ -1355,31 +1305,6 @@ static CURLcode pop3_setup_connection(struct connectdata *conn)
/* Clear the TLS upgraded flag */
conn->tls_upgraded = FALSE;
-
- /* Set up the proxy if necessary */
- if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
- /* Unless we have asked to tunnel POP3 operations through the proxy, we
- switch and use HTTP operations only */
-#ifndef CURL_DISABLE_HTTP
- if(conn->handler == &Curl_handler_pop3)
- conn->handler = &Curl_handler_pop3_proxy;
- else {
-#ifdef USE_SSL
- conn->handler = &Curl_handler_pop3s_proxy;
-#else
- failf(data, "POP3S not supported!");
- return CURLE_UNSUPPORTED_PROTOCOL;
-#endif
- }
-
- /* set it up as an HTTP connection instead */
- return conn->handler->setup_connection(conn);
-#else
- failf(data, "POP3 over http proxy requires HTTP support built-in!");
- return CURLE_UNSUPPORTED_PROTOCOL;
-#endif
- }
-
data->state.path++; /* don't include the initial slash */
return CURLE_OK;
diff --git a/Utilities/cmcurl/lib/progress.c b/Utilities/cmcurl/lib/progress.c
index cfaf4049e..00609d9ee 100644
--- a/Utilities/cmcurl/lib/progress.c
+++ b/Utilities/cmcurl/lib/progress.c
@@ -134,7 +134,7 @@ int Curl_pgrsDone(struct connectdata *conn)
{
int rc;
struct Curl_easy *data = conn->data;
- data->progress.lastshow=0;
+ data->progress.lastshow = 0;
rc = Curl_pgrsUpdate(conn); /* the final (forced) update */
if(rc)
return rc;
@@ -149,21 +149,20 @@ int Curl_pgrsDone(struct connectdata *conn)
return 0;
}
-/* reset all times except redirect, and reset the known transfer sizes */
-void Curl_pgrsResetTimesSizes(struct Curl_easy *data)
+/* reset the known transfer sizes */
+void Curl_pgrsResetTransferSizes(struct Curl_easy *data)
{
- data->progress.t_nslookup = 0.0;
- data->progress.t_connect = 0.0;
- data->progress.t_pretransfer = 0.0;
- data->progress.t_starttransfer = 0.0;
-
Curl_pgrsSetDownloadSize(data, -1);
Curl_pgrsSetUploadSize(data, -1);
}
+/*
+ * @unittest: 1399
+ */
void Curl_pgrsTime(struct Curl_easy *data, timerid timer)
{
- struct timeval now = Curl_tvnow();
+ struct curltime now = Curl_tvnow();
+ time_t *delta = NULL;
switch(timer) {
default:
@@ -177,45 +176,58 @@ void Curl_pgrsTime(struct Curl_easy *data, timerid timer)
case TIMER_STARTSINGLE:
/* This is set at the start of each single fetch */
data->progress.t_startsingle = now;
+ data->progress.is_t_startransfer_set = false;
break;
-
case TIMER_STARTACCEPT:
- data->progress.t_acceptdata = Curl_tvnow();
+ data->progress.t_acceptdata = now;
break;
-
case TIMER_NAMELOOKUP:
- data->progress.t_nslookup =
- Curl_tvdiff_secs(now, data->progress.t_startsingle);
+ delta = &data->progress.t_nslookup;
break;
case TIMER_CONNECT:
- data->progress.t_connect =
- Curl_tvdiff_secs(now, data->progress.t_startsingle);
+ delta = &data->progress.t_connect;
break;
case TIMER_APPCONNECT:
- data->progress.t_appconnect =
- Curl_tvdiff_secs(now, data->progress.t_startsingle);
+ delta = &data->progress.t_appconnect;
break;
case TIMER_PRETRANSFER:
- data->progress.t_pretransfer =
- Curl_tvdiff_secs(now, data->progress.t_startsingle);
+ delta = &data->progress.t_pretransfer;
break;
case TIMER_STARTTRANSFER:
- data->progress.t_starttransfer =
- Curl_tvdiff_secs(now, data->progress.t_startsingle);
- break;
+ delta = &data->progress.t_starttransfer;
+ /* prevent updating t_starttransfer unless:
+ * 1) this is the first time we're setting t_starttransfer
+ * 2) a redirect has occurred since the last time t_starttransfer was set
+ * This prevents repeated invocations of the function from incorrectly
+ * changing the t_starttransfer time.
+ */
+ if(data->progress.is_t_startransfer_set) {
+ return;
+ }
+ else {
+ data->progress.is_t_startransfer_set = true;
+ break;
+ }
case TIMER_POSTRANSFER:
/* this is the normal end-of-transfer thing */
break;
case TIMER_REDIRECT:
- data->progress.t_redirect = Curl_tvdiff_secs(now, data->progress.start);
+ data->progress.t_redirect = Curl_tvdiff_us(now, data->progress.start);
break;
}
+ if(delta) {
+ time_t us = Curl_tvdiff_us(now, data->progress.t_startsingle);
+ if(!us)
+ us++; /* make sure at least one microsecond passed */
+ *delta += us;
+ }
}
void Curl_pgrsStartNow(struct Curl_easy *data)
{
data->progress.speeder_c = 0; /* reset the progress meter display */
data->progress.start = Curl_tvnow();
+ data->progress.is_t_startransfer_set = false;
data->progress.ul_limit_start.tv_sec = 0;
data->progress.ul_limit_start.tv_usec = 0;
data->progress.dl_limit_start.tv_sec = 0;
@@ -246,8 +258,8 @@ void Curl_pgrsStartNow(struct Curl_easy *data)
long Curl_pgrsLimitWaitTime(curl_off_t cursize,
curl_off_t startsize,
curl_off_t limit,
- struct timeval start,
- struct timeval now)
+ struct curltime start,
+ struct curltime now)
{
curl_off_t size = cursize - startsize;
time_t minimum;
@@ -273,7 +285,7 @@ long Curl_pgrsLimitWaitTime(curl_off_t cursize,
void Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size)
{
- struct timeval now = Curl_tvnow();
+ struct curltime now = Curl_tvnow();
data->progress.downloaded = size;
@@ -291,7 +303,7 @@ void Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size)
void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size)
{
- struct timeval now = Curl_tvnow();
+ struct curltime now = Curl_tvnow();
data->progress.uploaded = size;
@@ -337,12 +349,12 @@ void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size)
*/
int Curl_pgrsUpdate(struct connectdata *conn)
{
- struct timeval now;
+ struct curltime now;
int result;
char max5[6][10];
- curl_off_t dlpercen=0;
- curl_off_t ulpercen=0;
- curl_off_t total_percen=0;
+ curl_off_t dlpercen = 0;
+ curl_off_t ulpercen = 0;
+ curl_off_t total_percen = 0;
curl_off_t total_transfer;
curl_off_t total_expected_transfer;
curl_off_t timespent;
@@ -353,26 +365,26 @@ int Curl_pgrsUpdate(struct connectdata *conn)
char time_left[10];
char time_total[10];
char time_spent[10];
- curl_off_t ulestimate=0;
- curl_off_t dlestimate=0;
+ curl_off_t ulestimate = 0;
+ curl_off_t dlestimate = 0;
curl_off_t total_estimate;
- bool shownow=FALSE;
+ bool shownow = FALSE;
now = Curl_tvnow(); /* what time is it */
/* The time spent so far (from the start) */
- data->progress.timespent = curlx_tvdiff_secs(now, data->progress.start);
- timespent = (curl_off_t)data->progress.timespent;
+ data->progress.timespent = Curl_tvdiff_us(now, data->progress.start);
+ timespent = (curl_off_t)data->progress.timespent/1000000; /* seconds */
/* The average download speed this far */
data->progress.dlspeed = (curl_off_t)
- ((double)data->progress.downloaded/
- (data->progress.timespent>0?data->progress.timespent:1));
+ (data->progress.downloaded/
+ (timespent>0?timespent:1));
/* The average upload speed this far */
data->progress.ulspeed = (curl_off_t)
- ((double)data->progress.uploaded/
- (data->progress.timespent>0?data->progress.timespent:1));
+ (data->progress.uploaded/
+ (timespent>0?timespent:1));
/* Calculations done at most once a second, unless end is reached */
if(data->progress.lastshow != now.tv_sec) {
@@ -380,11 +392,10 @@ int Curl_pgrsUpdate(struct connectdata *conn)
data->progress.lastshow = now.tv_sec;
- /* Let's do the "current speed" thing, which should use the fastest
- of the dl/ul speeds. Store the faster speed at entry 'nowindex'. */
+ /* Let's do the "current speed" thing, with the dl + ul speeds
+ combined. Store the speed at entry 'nowindex'. */
data->progress.speeder[ nowindex ] =
- data->progress.downloaded>data->progress.uploaded?
- data->progress.downloaded:data->progress.uploaded;
+ data->progress.downloaded + data->progress.uploaded;
/* remember the exact time for this moment */
data->progress.speeder_time [ nowindex ] = now;
@@ -397,7 +408,7 @@ int Curl_pgrsUpdate(struct connectdata *conn)
array. With N_ENTRIES filled in, we have about N_ENTRIES-1 seconds of
transfer. Imagine, after one second we have filled in two entries,
after two seconds we've filled in three entries etc. */
- countindex = ((data->progress.speeder_c>=CURR_TIME)?
+ countindex = ((data->progress.speeder_c >= CURR_TIME)?
CURR_TIME:data->progress.speeder_c) - 1;
/* first of all, we don't do this if there's no counted seconds yet */
@@ -407,14 +418,14 @@ int Curl_pgrsUpdate(struct connectdata *conn)
/* Get the index position to compare with the 'nowindex' position.
Get the oldest entry possible. While we have less than CURR_TIME
entries, the first entry will remain the oldest. */
- checkindex = (data->progress.speeder_c>=CURR_TIME)?
+ checkindex = (data->progress.speeder_c >= CURR_TIME)?
data->progress.speeder_c%CURR_TIME:0;
/* Figure out the exact time for the time span */
span_ms = Curl_tvdiff(now,
data->progress.speeder_time[checkindex]);
if(0 == span_ms)
- span_ms=1; /* at least one millisecond MUST have passed */
+ span_ms = 1; /* at least one millisecond MUST have passed */
/* Calculate the average speed the last 'span_ms' milliseconds */
{
@@ -433,10 +444,9 @@ int Curl_pgrsUpdate(struct connectdata *conn)
}
}
else
- /* the first second we use the main average */
+ /* the first second we use the average */
data->progress.current_speed =
- (data->progress.ulspeed>data->progress.dlspeed)?
- data->progress.ulspeed:data->progress.dlspeed;
+ data->progress.ulspeed + data->progress.dlspeed;
} /* Calculations end */
@@ -445,22 +455,22 @@ int Curl_pgrsUpdate(struct connectdata *conn)
if(data->set.fxferinfo) {
/* There's a callback set, call that */
- result= data->set.fxferinfo(data->set.progress_client,
- data->progress.size_dl,
- data->progress.downloaded,
- data->progress.size_ul,
- data->progress.uploaded);
+ result = data->set.fxferinfo(data->set.progress_client,
+ data->progress.size_dl,
+ data->progress.downloaded,
+ data->progress.size_ul,
+ data->progress.uploaded);
if(result)
failf(data, "Callback aborted");
return result;
}
if(data->set.fprogress) {
/* The older deprecated callback is set, call that */
- result= data->set.fprogress(data->set.progress_client,
- (double)data->progress.size_dl,
- (double)data->progress.downloaded,
- (double)data->progress.size_ul,
- (double)data->progress.uploaded);
+ result = data->set.fprogress(data->set.progress_client,
+ (double)data->progress.size_dl,
+ (double)data->progress.downloaded,
+ (double)data->progress.size_ul,
+ (double)data->progress.uploaded);
if(result)
failf(data, "Callback aborted");
return result;
diff --git a/Utilities/cmcurl/lib/progress.h b/Utilities/cmcurl/lib/progress.h
index 155ff04fe..9333ab25c 100644
--- a/Utilities/cmcurl/lib/progress.h
+++ b/Utilities/cmcurl/lib/progress.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -47,13 +47,13 @@ void Curl_pgrsSetUploadSize(struct Curl_easy *data, curl_off_t size);
void Curl_pgrsSetDownloadCounter(struct Curl_easy *data, curl_off_t size);
void Curl_pgrsSetUploadCounter(struct Curl_easy *data, curl_off_t size);
int Curl_pgrsUpdate(struct connectdata *);
-void Curl_pgrsResetTimesSizes(struct Curl_easy *data);
+void Curl_pgrsResetTransferSizes(struct Curl_easy *data);
void Curl_pgrsTime(struct Curl_easy *data, timerid timer);
long Curl_pgrsLimitWaitTime(curl_off_t cursize,
curl_off_t startsize,
curl_off_t limit,
- struct timeval start,
- struct timeval now);
+ struct curltime start,
+ struct curltime now);
/* Don't show progress for sizes smaller than: */
#define LEAST_SIZE_PROGRESS BUFSIZE
diff --git a/Utilities/cmcurl/lib/rand.c b/Utilities/cmcurl/lib/rand.c
index b6f40ac0a..2713a0aa3 100644
--- a/Utilities/cmcurl/lib/rand.c
+++ b/Utilities/cmcurl/lib/rand.c
@@ -86,7 +86,7 @@ static CURLcode randit(struct Curl_easy *data, unsigned int *rnd)
#endif
if(!seeded) {
- struct timeval now = curlx_tvnow();
+ struct curltime now = curlx_tvnow();
infof(data, "WARNING: Using weak random seed\n");
randseed += (unsigned int)now.tv_usec + (unsigned int)now.tv_sec;
randseed = randseed * 1103515245 + 12345;
diff --git a/Utilities/cmcurl/lib/rtsp.c b/Utilities/cmcurl/lib/rtsp.c
index 1810cdafb..925da2c1a 100644
--- a/Utilities/cmcurl/lib/rtsp.c
+++ b/Utilities/cmcurl/lib/rtsp.c
@@ -81,6 +81,9 @@ static CURLcode rtsp_rtp_readwrite(struct Curl_easy *data,
static CURLcode rtsp_setup_connection(struct connectdata *conn);
+bool rtsp_connisdead(struct connectdata *check);
+static unsigned int rtsp_conncheck(struct connectdata *check,
+ unsigned int checks_to_perform);
/* this returns the socket to wait for in the DO and DOING state for the multi
interface and then we're always _sending_ a request and thus we wait for
@@ -117,6 +120,7 @@ const struct Curl_handler Curl_handler_rtsp = {
ZERO_NULL, /* perform_getsock */
rtsp_disconnect, /* disconnect */
rtsp_rtp_readwrite, /* readwrite */
+ rtsp_conncheck, /* connection_check */
PORT_RTSP, /* defport */
CURLPROTO_RTSP, /* protocol */
PROTOPT_NONE /* flags */
@@ -143,7 +147,7 @@ static CURLcode rtsp_setup_connection(struct connectdata *conn)
* Instead, if it is readable, run Curl_connalive() to peek at the socket
* and distinguish between closed and data.
*/
-bool Curl_rtsp_connisdead(struct connectdata *check)
+bool rtsp_connisdead(struct connectdata *check)
{
int sval;
bool ret_val = TRUE;
@@ -165,6 +169,23 @@ bool Curl_rtsp_connisdead(struct connectdata *check)
return ret_val;
}
+/*
+ * Function to check on various aspects of a connection.
+ */
+static unsigned int rtsp_conncheck(struct connectdata *check,
+ unsigned int checks_to_perform)
+{
+ unsigned int ret_val = CONNRESULT_NONE;
+
+ if(checks_to_perform & CONNCHECK_ISDEAD) {
+ if(rtsp_connisdead(check))
+ ret_val |= CONNRESULT_DEAD;
+ }
+
+ return ret_val;
+}
+
+
static CURLcode rtsp_connect(struct connectdata *conn, bool *done)
{
CURLcode httpStatus;
@@ -229,7 +250,7 @@ static CURLcode rtsp_done(struct connectdata *conn,
static CURLcode rtsp_do(struct connectdata *conn, bool *done)
{
struct Curl_easy *data = conn->data;
- CURLcode result=CURLE_OK;
+ CURLcode result = CURLE_OK;
Curl_RtspReq rtspreq = data->set.rtspreq;
struct RTSP *rtsp = data->req.protop;
struct HTTP *http;
@@ -728,14 +749,28 @@ CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len)
struct Curl_easy *data = conn->data;
size_t wrote;
curl_write_callback writeit;
+ void *user_ptr;
if(len == 0) {
failf(data, "Cannot write a 0 size RTP packet.");
return CURLE_WRITE_ERROR;
}
- writeit = data->set.fwrite_rtp?data->set.fwrite_rtp:data->set.fwrite_func;
- wrote = writeit(ptr, 1, len, data->set.rtp_out);
+ /* If the user has configured CURLOPT_INTERLEAVEFUNCTION then use that
+ function and any configured CURLOPT_INTERLEAVEDATA to write out the RTP
+ data. Otherwise, use the CURLOPT_WRITEFUNCTION with the CURLOPT_WRITEDATA
+ pointer to write out the RTP data. */
+ if(data->set.fwrite_rtp) {
+ writeit = data->set.fwrite_rtp;
+ user_ptr = data->set.rtp_out;
+ }
+ else
+ {
+ writeit = data->set.fwrite_func;
+ user_ptr = data->set.out;
+ }
+
+ wrote = writeit(ptr, 1, len, user_ptr);
if(CURL_WRITEFUNC_PAUSE == wrote) {
failf(data, "Cannot pause RTP");
diff --git a/Utilities/cmcurl/lib/rtsp.h b/Utilities/cmcurl/lib/rtsp.h
index 5a8d5556f..8375a5317 100644
--- a/Utilities/cmcurl/lib/rtsp.h
+++ b/Utilities/cmcurl/lib/rtsp.h
@@ -25,13 +25,11 @@
extern const struct Curl_handler Curl_handler_rtsp;
-bool Curl_rtsp_connisdead(struct connectdata *check);
CURLcode Curl_rtsp_parseheader(struct connectdata *conn, char *header);
#else
/* disabled */
#define Curl_rtsp_parseheader(x,y) CURLE_NOT_BUILT_IN
-#define Curl_rtsp_connisdead(x) TRUE
#endif /* CURL_DISABLE_RTSP */
diff --git a/Utilities/cmcurl/lib/security.c b/Utilities/cmcurl/lib/security.c
index f4a876341..a2e4a35c8 100644
--- a/Utilities/cmcurl/lib/security.c
+++ b/Utilities/cmcurl/lib/security.c
@@ -7,7 +7,7 @@
* rewrite to work around the paragraph 2 in the BSD licenses as explained
* below.
*
- * Copyright (c) 1998, 1999 Kungliga Tekniska Högskolan
+ * Copyright (c) 1998, 1999, 2017 Kungliga Tekniska Högskolan
* (Royal Institute of Technology, Stockholm, Sweden).
*
* Copyright (C) 2001 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al.
@@ -115,7 +115,7 @@ static char level_to_char(int level)
static int ftp_send_command(struct connectdata *conn, const char *message, ...)
{
int ftp_code;
- ssize_t nread=0;
+ ssize_t nread = 0;
va_list args;
char print_buffer[50];
diff --git a/Utilities/cmcurl/lib/select.c b/Utilities/cmcurl/lib/select.c
index 443007227..b8e1868d0 100644
--- a/Utilities/cmcurl/lib/select.c
+++ b/Utilities/cmcurl/lib/select.c
@@ -78,7 +78,7 @@ int Curl_wait_ms(int timeout_ms)
#ifndef HAVE_POLL_FINE
struct timeval pending_tv;
#endif
- struct timeval initial_tv;
+ struct curltime initial_tv;
int pending_ms;
int error;
#endif
@@ -158,7 +158,7 @@ int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */
fd_set fds_err;
curl_socket_t maxfd;
#endif
- struct timeval initial_tv = {0, 0};
+ struct curltime initial_tv = {0, 0};
int pending_ms = 0;
int error;
int r;
@@ -398,7 +398,7 @@ int Curl_poll(struct pollfd ufds[], unsigned int nfds, int timeout_ms)
fd_set fds_err;
curl_socket_t maxfd;
#endif
- struct timeval initial_tv = {0, 0};
+ struct curltime initial_tv = {0, 0};
bool fds_none = TRUE;
unsigned int i;
int pending_ms = 0;
@@ -571,8 +571,8 @@ int Curl_poll(struct pollfd ufds[], unsigned int nfds, int timeout_ms)
*
* Return values are the same as select's.
*/
-int tpf_select_libcurl(int maxfds, fd_set* reads, fd_set* writes,
- fd_set* excepts, struct timeval* tv)
+int tpf_select_libcurl(int maxfds, fd_set *reads, fd_set *writes,
+ fd_set *excepts, struct timeval *tv)
{
int rc;
diff --git a/Utilities/cmcurl/lib/select.h b/Utilities/cmcurl/lib/select.h
index 4ed5dd2f8..4351786c3 100644
--- a/Utilities/cmcurl/lib/select.h
+++ b/Utilities/cmcurl/lib/select.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -36,7 +36,8 @@
#if !defined(HAVE_STRUCT_POLLFD) && \
!defined(HAVE_SYS_POLL_H) && \
- !defined(HAVE_POLL_H)
+ !defined(HAVE_POLL_H) && \
+ !defined(POLLIN)
#define POLLIN 0x01
#define POLLPRI 0x02
diff --git a/Utilities/cmcurl/lib/sendf.c b/Utilities/cmcurl/lib/sendf.c
index 595c36177..7564cb3d0 100644
--- a/Utilities/cmcurl/lib/sendf.c
+++ b/Utilities/cmcurl/lib/sendf.c
@@ -63,7 +63,7 @@ static size_t convert_lineends(struct Curl_easy *data,
if(*startPtr == '\n') {
/* This block of incoming data starts with the
previous block's LF so get rid of it */
- memmove(startPtr, startPtr+1, size-1);
+ memmove(startPtr, startPtr + 1, size-1);
size--;
/* and it wasn't a bare CR but a CRLF conversion instead */
data->state.crlf_conversions++;
@@ -75,7 +75,7 @@ static size_t convert_lineends(struct Curl_easy *data,
inPtr = outPtr = memchr(startPtr, '\r', size);
if(inPtr) {
/* at least one CR, now look for CRLF */
- while(inPtr < (startPtr+size-1)) {
+ while(inPtr < (startPtr + size-1)) {
/* note that it's size-1, so we'll never look past the last byte */
if(memcmp(inPtr, "\r\n", 2) == 0) {
/* CRLF found, bump past the CR and copy the NL */
@@ -98,7 +98,7 @@ static size_t convert_lineends(struct Curl_easy *data,
inPtr++;
} /* end of while loop */
- if(inPtr < startPtr+size) {
+ if(inPtr < startPtr + size) {
/* handle last byte */
if(*inPtr == '\r') {
/* deal with a CR at the end of the buffer */
@@ -112,7 +112,7 @@ static size_t convert_lineends(struct Curl_easy *data,
}
outPtr++;
}
- if(outPtr < startPtr+size)
+ if(outPtr < startPtr + size)
/* tidy up by null terminating the now shorter data */
*outPtr = '\0';
@@ -279,7 +279,7 @@ CURLcode Curl_sendf(curl_socket_t sockfd, struct connectdata *conn,
if(!s)
return CURLE_OUT_OF_MEMORY; /* failure */
- bytes_written=0;
+ bytes_written = 0;
write_len = strlen(s);
sptr = s;
@@ -387,7 +387,7 @@ ssize_t Curl_send_plain(struct connectdata *conn, int num,
#endif
) {
/* this is just a case of EWOULDBLOCK */
- bytes_written=0;
+ bytes_written = 0;
*code = CURLE_AGAIN;
}
else {
@@ -480,7 +480,7 @@ static CURLcode pausewrite(struct Curl_easy *data,
bool newtype = TRUE;
if(s->tempcount) {
- for(i=0; i< s->tempcount; i++) {
+ for(i = 0; i< s->tempcount; i++) {
if(s->tempwrite[i].type == type) {
/* data for this type exists */
newtype = FALSE;
@@ -704,7 +704,7 @@ CURLcode Curl_read(struct connectdata *conn, /* connection data */
us use the correct ssl handle. */
int num = (sockfd == conn->sock[SECONDARYSOCKET]);
- *n=0; /* reset amount to zero */
+ *n = 0; /* reset amount to zero */
/* If session can pipeline, check connection buffer */
if(pipelining) {
@@ -823,8 +823,8 @@ int Curl_debug(struct Curl_easy *data, curl_infotype type,
int rc;
if(data->set.printhost && conn && conn->host.dispname) {
char buffer[160];
- const char *t=NULL;
- const char *w="Data";
+ const char *t = NULL;
+ const char *w = "Data";
switch(type) {
case CURLINFO_HEADER_IN:
w = "Header";
diff --git a/Utilities/cmcurl/lib/smb.c b/Utilities/cmcurl/lib/smb.c
index 5b1ffa9b7..13dfd514b 100644
--- a/Utilities/cmcurl/lib/smb.c
+++ b/Utilities/cmcurl/lib/smb.c
@@ -34,7 +34,7 @@
#include <process.h>
#ifdef CURL_WINDOWS_APP
#define getpid GetCurrentProcessId
-#else
+#elif !defined(MSDOS)
#define getpid _getpid
#endif
#endif
@@ -85,6 +85,7 @@ const struct Curl_handler Curl_handler_smb = {
ZERO_NULL, /* perform_getsock */
smb_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_SMB, /* defport */
CURLPROTO_SMB, /* protocol */
PROTOPT_NONE /* flags */
@@ -109,6 +110,7 @@ const struct Curl_handler Curl_handler_smbs = {
ZERO_NULL, /* perform_getsock */
smb_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_SMBS, /* defport */
CURLPROTO_SMBS, /* protocol */
PROTOPT_SSL /* flags */
@@ -713,6 +715,23 @@ static CURLcode smb_connection_state(struct connectdata *conn, bool *done)
return CURLE_OK;
}
+/*
+ * Convert a timestamp from the Windows world (100 nsec units from
+ * 1 Jan 1601) to Posix time.
+ */
+static void get_posix_time(long *_out, const void *_in)
+{
+#ifdef HAVE_LONGLONG
+ long long timestamp = *(long long *) _in;
+#else
+ unsigned __int64 timestamp = *(unsigned __int64 *) _in;
+#endif
+
+ timestamp -= 116444736000000000ULL;
+ timestamp /= 10000000;
+ *_out = (long) timestamp;
+}
+
static CURLcode smb_request_state(struct connectdata *conn, bool *done)
{
struct smb_request *req = conn->data->req.protop;
@@ -723,6 +742,7 @@ static CURLcode smb_request_state(struct connectdata *conn, bool *done)
unsigned short off;
CURLcode result;
void *msg = NULL;
+ const struct smb_nt_create_response *smb_m;
/* Start the request */
if(req->state == SMB_REQUESTING) {
@@ -765,7 +785,8 @@ static CURLcode smb_request_state(struct connectdata *conn, bool *done)
next_state = SMB_TREE_DISCONNECT;
break;
}
- req->fid = smb_swap16(((struct smb_nt_create_response *)msg)->fid);
+ smb_m = (const struct smb_nt_create_response*) msg;
+ req->fid = smb_swap16(smb_m->fid);
conn->data->req.offset = 0;
if(conn->data->set.upload) {
conn->data->req.size = conn->data->state.infilesize;
@@ -773,9 +794,11 @@ static CURLcode smb_request_state(struct connectdata *conn, bool *done)
next_state = SMB_UPLOAD;
}
else {
- conn->data->req.size =
- smb_swap64(((struct smb_nt_create_response *)msg)->end_of_file);
+ smb_m = (const struct smb_nt_create_response*) msg;
+ conn->data->req.size = smb_swap64(smb_m->end_of_file);
Curl_pgrsSetDownloadSize(conn->data, conn->data->req.size);
+ if(conn->data->set.get_filetime)
+ get_posix_time(&conn->data->info.filetime, &smb_m->last_change_time);
next_state = SMB_DOWNLOAD;
}
break;
diff --git a/Utilities/cmcurl/lib/smtp.c b/Utilities/cmcurl/lib/smtp.c
index fe064cb2f..de2dd3356 100644
--- a/Utilities/cmcurl/lib/smtp.c
+++ b/Utilities/cmcurl/lib/smtp.c
@@ -67,6 +67,7 @@
#include "transfer.h"
#include "escape.h"
#include "http.h" /* for HTTP proxy tunnel stuff */
+#include "mime.h"
#include "socks.h"
#include "smtp.h"
#include "strtoofft.h"
@@ -124,6 +125,7 @@ const struct Curl_handler Curl_handler_smtp = {
ZERO_NULL, /* perform_getsock */
smtp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_SMTP, /* defport */
CURLPROTO_SMTP, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_NOURLQUERY | /* flags */
@@ -150,6 +152,7 @@ const struct Curl_handler Curl_handler_smtps = {
ZERO_NULL, /* perform_getsock */
smtp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_SMTPS, /* defport */
CURLPROTO_SMTPS, /* protocol */
PROTOPT_CLOSEACTION | PROTOPT_SSL
@@ -157,58 +160,6 @@ const struct Curl_handler Curl_handler_smtps = {
};
#endif
-#ifndef CURL_DISABLE_HTTP
-/*
- * HTTP-proxyed SMTP protocol handler.
- */
-
-static const struct Curl_handler Curl_handler_smtp_proxy = {
- "SMTP", /* scheme */
- Curl_http_setup_conn, /* setup_connection */
- Curl_http, /* do_it */
- Curl_http_done, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
- PORT_SMTP, /* defport */
- CURLPROTO_HTTP, /* protocol */
- PROTOPT_NONE /* flags */
-};
-
-#ifdef USE_SSL
-/*
- * HTTP-proxyed SMTPS protocol handler.
- */
-
-static const struct Curl_handler Curl_handler_smtps_proxy = {
- "SMTPS", /* scheme */
- Curl_http_setup_conn, /* setup_connection */
- Curl_http, /* do_it */
- Curl_http_done, /* done */
- ZERO_NULL, /* do_more */
- ZERO_NULL, /* connect_it */
- ZERO_NULL, /* connecting */
- ZERO_NULL, /* doing */
- ZERO_NULL, /* proto_getsock */
- ZERO_NULL, /* doing_getsock */
- ZERO_NULL, /* domore_getsock */
- ZERO_NULL, /* perform_getsock */
- ZERO_NULL, /* disconnect */
- ZERO_NULL, /* readwrite */
- PORT_SMTPS, /* defport */
- CURLPROTO_HTTP, /* protocol */
- PROTOPT_NONE /* flags */
-};
-#endif
-#endif
-
/* SASL parameters for the smtp protocol */
static const struct SASLproto saslsmtp = {
"smtp", /* The service name */
@@ -580,8 +531,40 @@ static CURLcode smtp_perform_mail(struct connectdata *conn)
}
}
+ /* Prepare the mime data if some. */
+ if(data->set.mimepost.kind != MIMEKIND_NONE) {
+ /* Use the whole structure as data. */
+ data->set.mimepost.flags &= ~MIME_BODY_ONLY;
+
+ /* Add external headers and mime version. */
+ curl_mime_headers(&data->set.mimepost, data->set.headers, 0);
+ result = Curl_mime_prepare_headers(&data->set.mimepost, NULL,
+ NULL, MIMESTRATEGY_MAIL);
+
+ if(!result)
+ if(!Curl_checkheaders(conn, "Mime-Version"))
+ result = Curl_mime_add_header(&data->set.mimepost.curlheaders,
+ "Mime-Version: 1.0");
+
+ /* Make sure we will read the entire mime structure. */
+ if(!result)
+ result = Curl_mime_rewind(&data->set.mimepost);
+
+ if(result) {
+ free(from);
+ free(auth);
+ return result;
+ }
+
+ data->state.infilesize = Curl_mime_size(&data->set.mimepost);
+
+ /* Read from mime structure. */
+ data->state.fread_func = (curl_read_callback) Curl_mime_read;
+ data->state.in = (void *) &data->set.mimepost;
+ }
+
/* Calculate the optional SIZE parameter */
- if(conn->proto.smtpc.size_supported && conn->data->state.infilesize > 0) {
+ if(conn->proto.smtpc.size_supported && data->state.infilesize > 0) {
size = aprintf("%" CURL_FORMAT_CURL_OFF_T, data->state.infilesize);
if(!size) {
@@ -1209,7 +1192,8 @@ static CURLcode smtp_done(struct connectdata *conn, CURLcode status,
connclose(conn, "SMTP done with bad status"); /* marked for closure */
result = status; /* use the already set error code */
}
- else if(!data->set.connect_only && data->set.upload && data->set.mail_rcpt) {
+ else if(!data->set.connect_only && data->set.mail_rcpt &&
+ (data->set.upload || data->set.mimepost.kind)) {
/* Calculate the EOB taking into account any terminating CRLF from the
previous line of the email or the CRLF of the DATA command when there
is "no mail data". RFC-5321, sect. 4.1.1.4.
@@ -1299,7 +1283,7 @@ static CURLcode smtp_perform(struct connectdata *conn, bool *connected,
smtp->rcpt = data->set.mail_rcpt;
/* Start the first command in the DO phase */
- if(data->set.upload && data->set.mail_rcpt)
+ if((data->set.upload || data->set.mimepost.kind) && data->set.mail_rcpt)
/* MAIL transfer */
result = smtp_perform_mail(conn);
else
@@ -1451,30 +1435,6 @@ static CURLcode smtp_setup_connection(struct connectdata *conn)
/* Clear the TLS upgraded flag */
conn->tls_upgraded = FALSE;
- /* Set up the proxy if necessary */
- if(conn->bits.httpproxy && !data->set.tunnel_thru_httpproxy) {
- /* Unless we have asked to tunnel SMTP operations through the proxy, we
- switch and use HTTP operations only */
-#ifndef CURL_DISABLE_HTTP
- if(conn->handler == &Curl_handler_smtp)
- conn->handler = &Curl_handler_smtp_proxy;
- else {
-#ifdef USE_SSL
- conn->handler = &Curl_handler_smtps_proxy;
-#else
- failf(data, "SMTPS not supported!");
- return CURLE_UNSUPPORTED_PROTOCOL;
-#endif
- }
- /* set it up as a HTTP connection instead */
- return conn->handler->setup_connection(conn);
-
-#else
- failf(data, "SMTP over http proxy requires HTTP support built-in!");
- return CURLE_UNSUPPORTED_PROTOCOL;
-#endif
- }
-
/* Initialise the SMTP layer */
result = smtp_init(conn);
if(result)
diff --git a/Utilities/cmcurl/lib/socks.c b/Utilities/cmcurl/lib/socks.c
index 97a44b296..e64cb98d4 100644
--- a/Utilities/cmcurl/lib/socks.c
+++ b/Utilities/cmcurl/lib/socks.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -105,7 +105,7 @@ int Curl_blockread_all(struct connectdata *conn, /* connection data */
* Set protocol4a=true for "SOCKS 4A (Simple Extension to SOCKS 4 Protocol)"
* Nonsupport "Identification Protocol (RFC1413)"
*/
-CURLcode Curl_SOCKS4(const char *proxy_name,
+CURLcode Curl_SOCKS4(const char *proxy_user,
const char *hostname,
int remote_port,
int sockindex,
@@ -154,7 +154,7 @@ CURLcode Curl_SOCKS4(const char *proxy_name,
/* DNS resolve only for SOCKS4, not SOCKS4a */
if(!protocol4a) {
struct Curl_dns_entry *dns;
- Curl_addrinfo *hp=NULL;
+ Curl_addrinfo *hp = NULL;
int rc;
rc = Curl_resolv(conn, hostname, remote_port, &dns);
@@ -171,7 +171,7 @@ CURLcode Curl_SOCKS4(const char *proxy_name,
* returns a Curl_addrinfo pointer that may not always look the same.
*/
if(dns)
- hp=dns->addr;
+ hp = dns->addr;
if(hp) {
char buf[64];
Curl_printable_address(hp, buf, sizeof(buf));
@@ -206,14 +206,14 @@ CURLcode Curl_SOCKS4(const char *proxy_name,
* This is currently not supporting "Identification Protocol (RFC1413)".
*/
socksreq[8] = 0; /* ensure empty userid is NUL-terminated */
- if(proxy_name) {
- size_t plen = strlen(proxy_name);
+ if(proxy_user) {
+ size_t plen = strlen(proxy_user);
if(plen >= sizeof(socksreq) - 8) {
failf(data, "Too long SOCKS proxy name, can't use!\n");
return CURLE_COULDNT_CONNECT;
}
/* copy the proxy name WITH trailing zero */
- memcpy(socksreq + 8, proxy_name, plen+1);
+ memcpy(socksreq + 8, proxy_user, plen + 1);
}
/*
@@ -306,7 +306,7 @@ CURLcode Curl_SOCKS4(const char *proxy_name,
", request rejected or failed.",
(unsigned char)socksreq[4], (unsigned char)socksreq[5],
(unsigned char)socksreq[6], (unsigned char)socksreq[7],
- (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]),
+ (((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]),
(unsigned char)socksreq[1]);
return CURLE_COULDNT_CONNECT;
case 92:
@@ -316,7 +316,7 @@ CURLcode Curl_SOCKS4(const char *proxy_name,
"identd on the client.",
(unsigned char)socksreq[4], (unsigned char)socksreq[5],
(unsigned char)socksreq[6], (unsigned char)socksreq[7],
- (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]),
+ (((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]),
(unsigned char)socksreq[1]);
return CURLE_COULDNT_CONNECT;
case 93:
@@ -326,7 +326,7 @@ CURLcode Curl_SOCKS4(const char *proxy_name,
"report different user-ids.",
(unsigned char)socksreq[4], (unsigned char)socksreq[5],
(unsigned char)socksreq[6], (unsigned char)socksreq[7],
- (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]),
+ (((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]),
(unsigned char)socksreq[1]);
return CURLE_COULDNT_CONNECT;
default:
@@ -335,7 +335,7 @@ CURLcode Curl_SOCKS4(const char *proxy_name,
", Unknown.",
(unsigned char)socksreq[4], (unsigned char)socksreq[5],
(unsigned char)socksreq[6], (unsigned char)socksreq[7],
- (((unsigned char)socksreq[8] << 8) | (unsigned char)socksreq[9]),
+ (((unsigned char)socksreq[2] << 8) | (unsigned char)socksreq[3]),
(unsigned char)socksreq[1]);
return CURLE_COULDNT_CONNECT;
}
@@ -350,7 +350,7 @@ CURLcode Curl_SOCKS4(const char *proxy_name,
* This function logs in to a SOCKS5 proxy and sends the specifics to the final
* destination server.
*/
-CURLcode Curl_SOCKS5(const char *proxy_name,
+CURLcode Curl_SOCKS5(const char *proxy_user,
const char *proxy_password,
const char *hostname,
int remote_port,
@@ -375,6 +375,7 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
*/
unsigned char socksreq[600]; /* room for large user/pw (255 max each) */
+ int idx;
ssize_t actualread;
ssize_t written;
int result;
@@ -386,6 +387,8 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
(conn->socks_proxy.proxytype == CURLPROXY_SOCKS5) ? TRUE : FALSE;
const size_t hostname_len = strlen(hostname);
ssize_t len = 0;
+ const unsigned long auth = data->set.socks5auth;
+ bool allow_gssapi = FALSE;
if(conn->bits.httpproxy)
infof(conn->data, "SOCKS5: connecting to HTTP proxy %s port %d\n",
@@ -426,18 +429,29 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
return CURLE_COULDNT_CONNECT;
}
- socksreq[0] = 5; /* version */
+ if(auth & ~(CURLAUTH_BASIC | CURLAUTH_GSSAPI))
+ infof(conn->data,
+ "warning: unsupported value passed to CURLOPT_SOCKS5_AUTH: %lu\n",
+ auth);
+ if(!(auth & CURLAUTH_BASIC))
+ /* disable username/password auth */
+ proxy_user = NULL;
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
- socksreq[1] = (char)(proxy_name ? 3 : 2); /* number of methods (below) */
- socksreq[2] = 0; /* no authentication */
- socksreq[3] = 1; /* GSS-API */
- socksreq[4] = 2; /* username/password */
-#else
- socksreq[1] = (char)(proxy_name ? 2 : 1); /* number of methods (below) */
- socksreq[2] = 0; /* no authentication */
- socksreq[3] = 2; /* username/password */
+ if(auth & CURLAUTH_GSSAPI)
+ allow_gssapi = TRUE;
#endif
+ idx = 0;
+ socksreq[idx++] = 5; /* version */
+ idx++; /* reserve for the number of authentication methods */
+ socksreq[idx++] = 0; /* no authentication */
+ if(allow_gssapi)
+ socksreq[idx++] = 1; /* GSS-API */
+ if(proxy_user)
+ socksreq[idx++] = 2; /* username/password */
+ /* write the number of authentication methods */
+ socksreq[1] = (unsigned char) (idx - 2);
+
(void)curlx_nonblock(sock, FALSE);
infof(data, "SOCKS5 communication to %s:%d\n", hostname, remote_port);
@@ -469,7 +483,7 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
(void)curlx_nonblock(sock, FALSE);
- result=Curl_blockread_all(conn, sock, (char *)socksreq, 2, &actualread);
+ result = Curl_blockread_all(conn, sock, (char *)socksreq, 2, &actualread);
if(result || (actualread != 2)) {
failf(data, "Unable to receive initial SOCKS5 response.");
return CURLE_COULDNT_CONNECT;
@@ -484,7 +498,7 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
;
}
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
- else if(socksreq[1] == 1) {
+ else if(allow_gssapi && (socksreq[1] == 1)) {
code = Curl_SOCKS5_gssapi_negotiate(sockindex, conn);
if(code) {
failf(data, "Unable to negotiate SOCKS5 GSS-API context.");
@@ -494,13 +508,13 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
#endif
else if(socksreq[1] == 2) {
/* Needs user name and password */
- size_t proxy_name_len, proxy_password_len;
- if(proxy_name && proxy_password) {
- proxy_name_len = strlen(proxy_name);
+ size_t proxy_user_len, proxy_password_len;
+ if(proxy_user && proxy_password) {
+ proxy_user_len = strlen(proxy_user);
proxy_password_len = strlen(proxy_password);
}
else {
- proxy_name_len = 0;
+ proxy_user_len = 0;
proxy_password_len = 0;
}
@@ -513,10 +527,10 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
*/
len = 0;
socksreq[len++] = 1; /* username/pw subnegotiation version */
- socksreq[len++] = (unsigned char) proxy_name_len;
- if(proxy_name && proxy_name_len)
- memcpy(socksreq + len, proxy_name, proxy_name_len);
- len += proxy_name_len;
+ socksreq[len++] = (unsigned char) proxy_user_len;
+ if(proxy_user && proxy_user_len)
+ memcpy(socksreq + len, proxy_user, proxy_user_len);
+ len += proxy_user_len;
socksreq[len++] = (unsigned char) proxy_password_len;
if(proxy_password && proxy_password_len)
memcpy(socksreq + len, proxy_password, proxy_password_len);
@@ -528,7 +542,7 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
return CURLE_COULDNT_CONNECT;
}
- result=Curl_blockread_all(conn, sock, (char *)socksreq, 2, &actualread);
+ result = Curl_blockread_all(conn, sock, (char *)socksreq, 2, &actualread);
if(result || (actualread != 2)) {
failf(data, "Unable to receive SOCKS5 sub-negotiation response.");
return CURLE_COULDNT_CONNECT;
@@ -545,17 +559,13 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
}
else {
/* error */
-#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
- if(socksreq[1] == 255) {
-#else
- if(socksreq[1] == 1) {
+ if(!allow_gssapi && (socksreq[1] == 1)) {
failf(data,
"SOCKS5 GSSAPI per-message authentication is not supported.");
return CURLE_COULDNT_CONNECT;
}
if(socksreq[1] == 255) {
-#endif
- if(!proxy_name || !*proxy_name) {
+ if(!proxy_user || !*proxy_user) {
failf(data,
"No authentication method was acceptable. (It is quite likely"
" that the SOCKS5 server wanted a username/password, since none"
@@ -605,7 +615,7 @@ CURLcode Curl_SOCKS5(const char *proxy_name,
* returns a Curl_addrinfo pointer that may not always look the same.
*/
if(dns)
- hp=dns->addr;
+ hp = dns->addr;
if(hp) {
int i;
char buf[64];
diff --git a/Utilities/cmcurl/lib/socks_gssapi.c b/Utilities/cmcurl/lib/socks_gssapi.c
index 54d063504..96948ac4b 100644
--- a/Utilities/cmcurl/lib/socks_gssapi.c
+++ b/Utilities/cmcurl/lib/socks_gssapi.c
@@ -5,8 +5,8 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 2009, 2011, Markus Moeller, <markus_moeller@compuserve.com>
- * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 2009, Markus Moeller, <markus_moeller@compuserve.com>
+ * Copyright (C) 2012 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -65,7 +65,7 @@ static int check_gss_err(struct Curl_easy *data,
&msg_ctx, &status_string);
if(maj_stat == GSS_S_COMPLETE) {
if(sizeof(buf) > len + status_string.length + 1) {
- strcpy(buf+len, (char *) status_string.value);
+ strcpy(buf + len, (char *) status_string.value);
len += status_string.length;
}
gss_release_buffer(&min_stat, &status_string);
@@ -74,7 +74,7 @@ static int check_gss_err(struct Curl_easy *data,
gss_release_buffer(&min_stat, &status_string);
}
if(sizeof(buf) > len + 3) {
- strcpy(buf+len, ".\n");
+ strcpy(buf + len, ".\n");
len += 2;
}
msg_ctx = 0;
@@ -86,7 +86,7 @@ static int check_gss_err(struct Curl_easy *data,
&msg_ctx, &status_string);
if(maj_stat == GSS_S_COMPLETE) {
if(sizeof(buf) > len + status_string.length)
- strcpy(buf+len, (char *) status_string.value);
+ strcpy(buf + len, (char *) status_string.value);
gss_release_buffer(&min_stat, &status_string);
break;
}
@@ -119,7 +119,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
gss_name_t server = GSS_C_NO_NAME;
gss_name_t gss_client_name = GSS_C_NO_NAME;
unsigned short us_length;
- char *user=NULL;
+ char *user = NULL;
unsigned char socksreq[4]; /* room for GSS-API exchange header only */
const char *serviceptr = data->set.str[STRING_PROXY_SERVICE_NAME] ?
data->set.str[STRING_PROXY_SERVICE_NAME] : "rcmd";
@@ -146,11 +146,12 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
}
else {
service.value = malloc(serviceptr_length +
- strlen(conn->socks_proxy.host.name)+2);
+ strlen(conn->socks_proxy.host.name) + 2);
if(!service.value)
return CURLE_OUT_OF_MEMORY;
- service.length = serviceptr_length + strlen(conn->socks_proxy.host.name)+1;
- snprintf(service.value, service.length+1, "%s@%s",
+ service.length = serviceptr_length +
+ strlen(conn->socks_proxy.host.name) + 1;
+ snprintf(service.value, service.length + 1, "%s@%s",
serviceptr, conn->socks_proxy.host.name);
gss_major_status = gss_import_name(&gss_minor_status, &service,
@@ -196,7 +197,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
socksreq[0] = 1; /* GSS-API subnegotiation version */
socksreq[1] = 1; /* authentication message type */
us_length = htons((short)gss_send_token.length);
- memcpy(socksreq+2, &us_length, sizeof(short));
+ memcpy(socksreq + 2, &us_length, sizeof(short));
code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written);
if(code || (4 != written)) {
@@ -236,7 +237,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
* +----+------+-----+----------------+
*/
- result=Curl_blockread_all(conn, sock, (char *)socksreq, 4, &actualread);
+ result = Curl_blockread_all(conn, sock, (char *)socksreq, 4, &actualread);
if(result || (actualread != 4)) {
failf(data, "Failed to receive GSS-API authentication response.");
gss_release_name(&gss_status, &server);
@@ -261,11 +262,11 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
return CURLE_COULDNT_CONNECT;
}
- memcpy(&us_length, socksreq+2, sizeof(short));
+ memcpy(&us_length, socksreq + 2, sizeof(short));
us_length = ntohs(us_length);
- gss_recv_token.length=us_length;
- gss_recv_token.value=malloc(us_length);
+ gss_recv_token.length = us_length;
+ gss_recv_token.value = malloc(us_length);
if(!gss_recv_token.value) {
failf(data,
"Could not allocate memory for GSS-API authentication "
@@ -275,8 +276,8 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
return CURLE_OUT_OF_MEMORY;
}
- result=Curl_blockread_all(conn, sock, (char *)gss_recv_token.value,
- gss_recv_token.length, &actualread);
+ result = Curl_blockread_all(conn, sock, (char *)gss_recv_token.value,
+ gss_recv_token.length, &actualread);
if(result || (actualread != us_length)) {
failf(data, "Failed to receive GSS-API authentication token.");
@@ -312,7 +313,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
failf(data, "Failed to determine user name.");
return CURLE_COULDNT_CONNECT;
}
- user=malloc(gss_send_token.length+1);
+ user = malloc(gss_send_token.length + 1);
if(!user) {
gss_delete_sec_context(&gss_status, &gss_context, NULL);
gss_release_name(&gss_status, &gss_client_name);
@@ -326,7 +327,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
gss_release_buffer(&gss_status, &gss_send_token);
infof(data, "SOCKS5 server authencticated user %s with GSS-API.\n",user);
free(user);
- user=NULL;
+ user = NULL;
/* Do encryption */
socksreq[0] = 1; /* GSS-API subnegotiation version */
@@ -341,7 +342,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
gss_enc = 1;
infof(data, "SOCKS5 server supports GSS-API %s data protection.\n",
- (gss_enc==0)?"no":((gss_enc==1)?"integrity":"confidentiality"));
+ (gss_enc == 0)?"no":((gss_enc==1)?"integrity":"confidentiality"));
/* force for the moment to no data protection */
gss_enc = 0;
/*
@@ -376,7 +377,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
*/
if(data->set.socks5_gssapi_nec) {
us_length = htons((short)1);
- memcpy(socksreq+2, &us_length, sizeof(short));
+ memcpy(socksreq + 2, &us_length, sizeof(short));
}
else {
gss_send_token.length = 1;
@@ -401,7 +402,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
gss_release_buffer(&gss_status, &gss_send_token);
us_length = htons((short)gss_w_token.length);
- memcpy(socksreq+2, &us_length, sizeof(short));
+ memcpy(socksreq + 2, &us_length, sizeof(short));
}
code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written);
@@ -433,7 +434,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
gss_release_buffer(&gss_status, &gss_w_token);
}
- result=Curl_blockread_all(conn, sock, (char *)socksreq, 4, &actualread);
+ result = Curl_blockread_all(conn, sock, (char *)socksreq, 4, &actualread);
if(result || (actualread != 4)) {
failf(data, "Failed to receive GSS-API encryption response.");
gss_delete_sec_context(&gss_status, &gss_context, NULL);
@@ -455,17 +456,17 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
return CURLE_COULDNT_CONNECT;
}
- memcpy(&us_length, socksreq+2, sizeof(short));
+ memcpy(&us_length, socksreq + 2, sizeof(short));
us_length = ntohs(us_length);
- gss_recv_token.length= us_length;
- gss_recv_token.value=malloc(gss_recv_token.length);
+ gss_recv_token.length = us_length;
+ gss_recv_token.value = malloc(gss_recv_token.length);
if(!gss_recv_token.value) {
gss_delete_sec_context(&gss_status, &gss_context, NULL);
return CURLE_OUT_OF_MEMORY;
}
- result=Curl_blockread_all(conn, sock, (char *)gss_recv_token.value,
- gss_recv_token.length, &actualread);
+ result = Curl_blockread_all(conn, sock, (char *)gss_recv_token.value,
+ gss_recv_token.length, &actualread);
if(result || (actualread != us_length)) {
failf(data, "Failed to receive GSS-API encryptrion type.");
@@ -513,8 +514,8 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
}
infof(data, "SOCKS5 access with%s protection granted.\n",
- (socksreq[0]==0)?"out GSS-API data":
- ((socksreq[0]==1)?" GSS-API integrity":" GSS-API confidentiality"));
+ (socksreq[0] == 0)?"out GSS-API data":
+ ((socksreq[0] == 1)?" GSS-API integrity":" GSS-API confidentiality"));
conn->socks5_gssapi_enctype = socksreq[0];
if(socksreq[0] == 0)
diff --git a/Utilities/cmcurl/lib/socks_sspi.c b/Utilities/cmcurl/lib/socks_sspi.c
index edc73ad2e..34699d374 100644
--- a/Utilities/cmcurl/lib/socks_sspi.c
+++ b/Utilities/cmcurl/lib/socks_sspi.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 2012 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
* Copyright (C) 2009, 2011, Markus Moeller, <markus_moeller@compuserve.com>
*
* This software is licensed as described in the file COPYING, which
@@ -108,7 +108,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
if(!service_name)
return CURLE_OUT_OF_MEMORY;
snprintf(service_name, service_length +
- strlen(conn->socks_proxy.host.name)+2, "%s/%s",
+ strlen(conn->socks_proxy.host.name) + 2, "%s/%s",
service, conn->socks_proxy.host.name);
}
@@ -199,7 +199,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
socksreq[0] = 1; /* GSS-API subnegotiation version */
socksreq[1] = 1; /* authentication message type */
us_length = htons((short)sspi_send_token.cbBuffer);
- memcpy(socksreq+2, &us_length, sizeof(short));
+ memcpy(socksreq + 2, &us_length, sizeof(short));
code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written);
if(code || (4 != written)) {
@@ -283,7 +283,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
return CURLE_COULDNT_CONNECT;
}
- memcpy(&us_length, socksreq+2, sizeof(short));
+ memcpy(&us_length, socksreq + 2, sizeof(short));
us_length = ntohs(us_length);
sspi_recv_token.cbBuffer = us_length;
@@ -341,7 +341,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
gss_enc = 1;
infof(data, "SOCKS5 server supports GSS-API %s data protection.\n",
- (gss_enc==0)?"no":((gss_enc==1)?"integrity":"confidentiality") );
+ (gss_enc == 0)?"no":((gss_enc == 1)?"integrity":"confidentiality") );
/* force to no data protection, avoid encryption/decryption for now */
gss_enc = 0;
/*
@@ -377,7 +377,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
if(data->set.socks5_gssapi_nec) {
us_length = htons((short)1);
- memcpy(socksreq+2, &us_length, sizeof(short));
+ memcpy(socksreq + 2, &us_length, sizeof(short));
}
else {
status = s_pSecFn->QueryContextAttributes(&sspi_context,
@@ -445,8 +445,8 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
memcpy((PUCHAR) sspi_send_token.pvBuffer +(int)sspi_w_token[0].cbBuffer,
sspi_w_token[1].pvBuffer, sspi_w_token[1].cbBuffer);
memcpy((PUCHAR) sspi_send_token.pvBuffer
- +sspi_w_token[0].cbBuffer
- +sspi_w_token[1].cbBuffer,
+ + sspi_w_token[0].cbBuffer
+ + sspi_w_token[1].cbBuffer,
sspi_w_token[2].pvBuffer, sspi_w_token[2].cbBuffer);
s_pSecFn->FreeContextBuffer(sspi_w_token[0].pvBuffer);
@@ -460,7 +460,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
sspi_w_token[2].cbBuffer = 0;
us_length = htons((short)sspi_send_token.cbBuffer);
- memcpy(socksreq+2, &us_length, sizeof(short));
+ memcpy(socksreq + 2, &us_length, sizeof(short));
}
code = Curl_write_plain(conn, sock, (char *)socksreq, 4, &written);
@@ -517,7 +517,7 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
return CURLE_COULDNT_CONNECT;
}
- memcpy(&us_length, socksreq+2, sizeof(short));
+ memcpy(&us_length, socksreq + 2, sizeof(short));
us_length = ntohs(us_length);
sspi_w_token[0].cbBuffer = us_length;
@@ -588,8 +588,8 @@ CURLcode Curl_SOCKS5_gssapi_negotiate(int sockindex,
}
infof(data, "SOCKS5 access with%s protection granted.\n",
- (socksreq[0]==0)?"out GSS-API data":
- ((socksreq[0]==1)?" GSS-API integrity":" GSS-API confidentiality"));
+ (socksreq[0] == 0)?"out GSS-API data":
+ ((socksreq[0] == 1)?" GSS-API integrity":" GSS-API confidentiality"));
/* For later use if encryption is required
conn->socks5_gssapi_enctype = socksreq[0];
diff --git a/Utilities/cmcurl/lib/speedcheck.c b/Utilities/cmcurl/lib/speedcheck.c
index 8addedde5..fe669f11a 100644
--- a/Utilities/cmcurl/lib/speedcheck.c
+++ b/Utilities/cmcurl/lib/speedcheck.c
@@ -30,14 +30,14 @@
void Curl_speedinit(struct Curl_easy *data)
{
- memset(&data->state.keeps_speed, 0, sizeof(struct timeval));
+ memset(&data->state.keeps_speed, 0, sizeof(struct curltime));
}
/*
* @unittest: 1606
*/
CURLcode Curl_speedcheck(struct Curl_easy *data,
- struct timeval now)
+ struct curltime now)
{
if((data->progress.current_speed >= 0) && data->set.low_speed_time) {
if(data->progress.current_speed < data->set.low_speed_limit) {
diff --git a/Utilities/cmcurl/lib/speedcheck.h b/Utilities/cmcurl/lib/speedcheck.h
index 7dbe3d6d7..5c2dc9a22 100644
--- a/Utilities/cmcurl/lib/speedcheck.h
+++ b/Utilities/cmcurl/lib/speedcheck.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -28,6 +28,6 @@
void Curl_speedinit(struct Curl_easy *data);
CURLcode Curl_speedcheck(struct Curl_easy *data,
- struct timeval now);
+ struct curltime now);
#endif /* HEADER_CURL_SPEEDCHECK_H */
diff --git a/Utilities/cmcurl/lib/splay.c b/Utilities/cmcurl/lib/splay.c
index 1b301f95d..69af446eb 100644
--- a/Utilities/cmcurl/lib/splay.c
+++ b/Utilities/cmcurl/lib/splay.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1997 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1997 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -37,7 +37,7 @@
* Splay using the key i (which may or may not be in the tree.) The starting
* root is t.
*/
-struct Curl_tree *Curl_splay(struct timeval i,
+struct Curl_tree *Curl_splay(struct curltime i,
struct Curl_tree *t)
{
struct Curl_tree N, *l, *r, *y;
@@ -97,24 +97,26 @@ struct Curl_tree *Curl_splay(struct timeval i,
*
* @unittest: 1309
*/
-struct Curl_tree *Curl_splayinsert(struct timeval i,
+struct Curl_tree *Curl_splayinsert(struct curltime i,
struct Curl_tree *t,
struct Curl_tree *node)
{
- static const struct timeval KEY_NOTUSED = {-1, -1}; /* will *NEVER* appear */
+ static const struct curltime KEY_NOTUSED = {
+ (time_t)-1, (unsigned int)-1
+ }; /* will *NEVER* appear */
if(node == NULL)
return t;
if(t != NULL) {
t = Curl_splay(i, t);
- if(compare(i, t->key)==0) {
+ if(compare(i, t->key) == 0) {
/* There already exists a node in the tree with the very same key. Build
a doubly-linked circular list of nodes. We add the new 'node' struct
to the end of this list. */
node->key = KEY_NOTUSED; /* we set the key in the sub node to NOTUSED
- to quickly identify this node as a subnode */
+ to quickly identify this node as a subnode */
node->samen = t;
node->samep = t->samep;
t->samep->samen = node;
@@ -149,11 +151,11 @@ struct Curl_tree *Curl_splayinsert(struct timeval i,
/* Finds and deletes the best-fit node from the tree. Return a pointer to the
resulting tree. best-fit means the smallest node if it is not larger than
the key */
-struct Curl_tree *Curl_splaygetbest(struct timeval i,
- struct Curl_tree *t,
- struct Curl_tree **removed)
+struct Curl_tree *Curl_splaygetbest(struct curltime i,
+ struct Curl_tree *t,
+ struct Curl_tree **removed)
{
- static struct timeval tv_zero = {0, 0};
+ static struct curltime tv_zero = {0, 0};
struct Curl_tree *x;
if(!t) {
@@ -209,7 +211,9 @@ int Curl_splayremovebyaddr(struct Curl_tree *t,
struct Curl_tree *removenode,
struct Curl_tree **newroot)
{
- static const struct timeval KEY_NOTUSED = {-1, -1}; /* will *NEVER* appear */
+ static const struct curltime KEY_NOTUSED = {
+ (time_t)-1, (unsigned int)-1
+ }; /* will *NEVER* appear */
struct Curl_tree *x;
if(!t || !removenode)
diff --git a/Utilities/cmcurl/lib/splay.h b/Utilities/cmcurl/lib/splay.h
index da81894d1..4612ec271 100644
--- a/Utilities/cmcurl/lib/splay.h
+++ b/Utilities/cmcurl/lib/splay.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1997 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1997 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -22,30 +22,31 @@
*
***************************************************************************/
#include "curl_setup.h"
+#include "timeval.h"
struct Curl_tree {
struct Curl_tree *smaller; /* smaller node */
struct Curl_tree *larger; /* larger node */
struct Curl_tree *samen; /* points to the next node with identical key */
struct Curl_tree *samep; /* points to the prev node with identical key */
- struct timeval key; /* this node's "sort" key */
+ struct curltime key; /* this node's "sort" key */
void *payload; /* data the splay code doesn't care about */
};
-struct Curl_tree *Curl_splay(struct timeval i,
+struct Curl_tree *Curl_splay(struct curltime i,
struct Curl_tree *t);
-struct Curl_tree *Curl_splayinsert(struct timeval key,
+struct Curl_tree *Curl_splayinsert(struct curltime key,
struct Curl_tree *t,
struct Curl_tree *newnode);
#if 0
-struct Curl_tree *Curl_splayremove(struct timeval key,
+struct Curl_tree *Curl_splayremove(struct curltime key,
struct Curl_tree *t,
struct Curl_tree **removed);
#endif
-struct Curl_tree *Curl_splaygetbest(struct timeval key,
+struct Curl_tree *Curl_splaygetbest(struct curltime key,
struct Curl_tree *t,
struct Curl_tree **removed);
@@ -53,8 +54,8 @@ int Curl_splayremovebyaddr(struct Curl_tree *t,
struct Curl_tree *removenode,
struct Curl_tree **newroot);
-#define Curl_splaycomparekeys(i,j) ( ((i.tv_sec) < (j.tv_sec)) ? -1 : \
- ( ((i.tv_sec) > (j.tv_sec)) ? 1 : \
+#define Curl_splaycomparekeys(i,j) ( ((i.tv_sec) < (j.tv_sec)) ? -1 : \
+ ( ((i.tv_sec) > (j.tv_sec)) ? 1 : \
( ((i.tv_usec) < (j.tv_usec)) ? -1 : \
( ((i.tv_usec) > (j.tv_usec)) ? 1 : 0))))
diff --git a/Utilities/cmcurl/lib/ssh.c b/Utilities/cmcurl/lib/ssh.c
index 00aeca978..5406bf073 100644
--- a/Utilities/cmcurl/lib/ssh.c
+++ b/Utilities/cmcurl/lib/ssh.c
@@ -177,6 +177,7 @@ const struct Curl_handler Curl_handler_scp = {
ssh_perform_getsock, /* perform_getsock */
scp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_SSH, /* defport */
CURLPROTO_SCP, /* protocol */
PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION
@@ -203,6 +204,7 @@ const struct Curl_handler Curl_handler_sftp = {
ssh_perform_getsock, /* perform_getsock */
sftp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_SSH, /* defport */
CURLPROTO_SFTP, /* protocol */
PROTOPT_DIRLOCK | PROTOPT_CLOSEACTION
@@ -426,14 +428,14 @@ static CURLcode ssh_getworkingpath(struct connectdata *conn,
/* Check for /~/, indicating relative to the user's home directory */
if(conn->handler->protocol & CURLPROTO_SCP) {
- real_path = malloc(working_path_len+1);
+ real_path = malloc(working_path_len + 1);
if(real_path == NULL) {
free(working_path);
return CURLE_OUT_OF_MEMORY;
}
if((working_path_len > 3) && (!memcmp(working_path, "/~/", 3)))
/* It is referenced to the home directory, so strip the leading '/~/' */
- memcpy(real_path, working_path+3, 4 + working_path_len-3);
+ memcpy(real_path, working_path + 3, 4 + working_path_len-3);
else
memcpy(real_path, working_path, 1 + working_path_len);
}
@@ -449,19 +451,19 @@ static CURLcode ssh_getworkingpath(struct connectdata *conn,
leading '/' */
memcpy(real_path, homedir, homelen);
real_path[homelen] = '/';
- real_path[homelen+1] = '\0';
+ real_path[homelen + 1] = '\0';
if(working_path_len > 3) {
- memcpy(real_path+homelen+1, working_path + 3,
+ memcpy(real_path + homelen + 1, working_path + 3,
1 + working_path_len -3);
}
}
else {
- real_path = malloc(working_path_len+1);
+ real_path = malloc(working_path_len + 1);
if(real_path == NULL) {
free(working_path);
return CURLE_OUT_OF_MEMORY;
}
- memcpy(real_path, working_path, 1+working_path_len);
+ memcpy(real_path, working_path, 1 + working_path_len);
}
}
@@ -1811,7 +1813,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
zero even though libssh2_sftp_open() failed previously! We need
to work around that! */
sshc->actualcode = CURLE_SSH;
- err=-1;
+ err = -1;
}
failf(data, "Upload failed: %s (%d/%d)",
err>= LIBSSH2_FX_OK?sftp_libssh2_strerror(err):"ssh error",
@@ -1829,7 +1831,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
}
if(seekerr != CURL_SEEKFUNC_OK) {
- curl_off_t passed=0;
+ curl_off_t passed = 0;
if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
failf(data, "Could not seek stream");
@@ -1981,13 +1983,13 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
sshc->actualcode = result?result:CURLE_SSH;
break;
}
- sshc->readdir_filename = malloc(PATH_MAX+1);
+ sshc->readdir_filename = malloc(PATH_MAX + 1);
if(!sshc->readdir_filename) {
state(conn, SSH_SFTP_CLOSE);
sshc->actualcode = CURLE_OUT_OF_MEMORY;
break;
}
- sshc->readdir_longentry = malloc(PATH_MAX+1);
+ sshc->readdir_longentry = malloc(PATH_MAX + 1);
if(!sshc->readdir_longentry) {
Curl_safefree(sshc->readdir_filename);
state(conn, SSH_SFTP_CLOSE);
@@ -2021,7 +2023,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
break;
}
result = Curl_client_write(conn, CLIENTWRITE_BODY,
- tmpLine, sshc->readdir_len+1);
+ tmpLine, sshc->readdir_len + 1);
free(tmpLine);
if(result) {
@@ -2030,7 +2032,7 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
}
/* since this counts what we send to the client, we include the
newline in this counter */
- data->req.bytecount += sshc->readdir_len+1;
+ data->req.bytecount += sshc->readdir_len + 1;
/* output debug output if that is requested */
if(data->set.verbose) {
@@ -2231,18 +2233,25 @@ static CURLcode ssh_statemach_act(struct connectdata *conn, bool *block)
curl_off_t from, to;
char *ptr;
char *ptr2;
+ CURLofft to_t;
+ CURLofft from_t;
- from=curlx_strtoofft(conn->data->state.range, &ptr, 0);
- while(*ptr && (ISSPACE(*ptr) || (*ptr=='-')))
+ from_t = curlx_strtoofft(conn->data->state.range, &ptr, 0, &from);
+ if(from_t == CURL_OFFT_FLOW)
+ return CURLE_RANGE_ERROR;
+ while(*ptr && (ISSPACE(*ptr) || (*ptr == '-')))
ptr++;
- to=curlx_strtoofft(ptr, &ptr2, 0);
- if((ptr == ptr2) /* no "to" value given */
+ to_t = curlx_strtoofft(ptr, &ptr2, 0, &to);
+ if(to_t == CURL_OFFT_FLOW)
+ return CURLE_RANGE_ERROR;
+ if((to_t == CURL_OFFT_INVAL) /* no "to" value given */
|| (to >= size)) {
to = size - 1;
}
- if(from < 0) {
+ if(from_t) {
/* from is relative to end of file */
- from += size;
+ from = size - to;
+ to = size - 1;
}
if(from > size) {
failf(data, "Offset (%"
@@ -2825,7 +2834,7 @@ static CURLcode ssh_block_statemach(struct connectdata *conn,
while((sshc->state != SSH_STOP) && !result) {
bool block;
time_t left = 1000;
- struct timeval now = Curl_tvnow();
+ struct curltime now = Curl_tvnow();
result = ssh_statemach_act(conn, &block);
if(result)
@@ -2933,6 +2942,13 @@ static CURLcode ssh_connect(struct connectdata *conn, bool *done)
return CURLE_FAILED_INIT;
}
+ if(data->set.ssh_compression) {
+#if LIBSSH2_VERSION_NUM >= 0x010208
+ if(libssh2_session_flag(ssh->ssh_session, LIBSSH2_FLAG_COMPRESS, 1) < 0)
+#endif
+ infof(data, "Failed to enable compression for ssh session\n");
+ }
+
#ifdef HAVE_LIBSSH2_KNOWNHOST_API
if(data->set.str[STRING_SSH_KNOWNHOSTS]) {
int rc;
@@ -3029,8 +3045,8 @@ static CURLcode ssh_do(struct connectdata *conn, bool *done)
data->req.size = -1; /* make sure this is unknown at this point */
sshc->actualcode = CURLE_OK; /* reset error code */
- sshc->secondCreateDirs =0; /* reset the create dir attempt state
- variable */
+ sshc->secondCreateDirs = 0; /* reset the create dir attempt state
+ variable */
Curl_pgrsSetUploadCounter(data, 0);
Curl_pgrsSetDownloadCounter(data, 0);
diff --git a/Utilities/cmcurl/lib/strcase.c b/Utilities/cmcurl/lib/strcase.c
index a74a4be57..24bcca932 100644
--- a/Utilities/cmcurl/lib/strcase.c
+++ b/Utilities/cmcurl/lib/strcase.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -94,10 +94,11 @@ char Curl_raw_toupper(char in)
}
/*
- * Curl_raw_equal() is for doing "raw" case insensitive strings. This is meant
- * to be locale independent and only compare strings we know are safe for
- * this. See https://daniel.haxx.se/blog/2008/10/15/strcasecmp-in-turkish/ for
- * some further explanation to why this function is necessary.
+ * Curl_strcasecompare() is for doing "raw" case insensitive strings. This is
+ * meant to be locale independent and only compare strings we know are safe
+ * for this. See
+ * https://daniel.haxx.se/blog/2008/10/15/strcasecmp-in-turkish/ for some
+ * further explanation to why this function is necessary.
*
* The function is capable of comparing a-z case insensitively even for
* non-ascii.
diff --git a/Utilities/cmcurl/lib/strdup.c b/Utilities/cmcurl/lib/strdup.c
index 136b69377..19cb04416 100644
--- a/Utilities/cmcurl/lib/strdup.c
+++ b/Utilities/cmcurl/lib/strdup.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -44,11 +44,11 @@ char *curlx_strdup(const char *str)
if(len >= ((size_t)-1) / sizeof(char))
return (char *)NULL;
- newstr = malloc((len+1)*sizeof(char));
+ newstr = malloc((len + 1)*sizeof(char));
if(!newstr)
return (char *)NULL;
- memcpy(newstr, str, (len+1)*sizeof(char));
+ memcpy(newstr, str, (len + 1)*sizeof(char));
return newstr;
diff --git a/Utilities/cmcurl/lib/strerror.c b/Utilities/cmcurl/lib/strerror.c
index 7e5cde47b..83a96dda1 100644
--- a/Utilities/cmcurl/lib/strerror.c
+++ b/Utilities/cmcurl/lib/strerror.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 2004 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 2004 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -49,6 +49,10 @@
#include "curl_memory.h"
#include "memdebug.h"
+#if defined(WIN32) || defined(_WIN32_WCE)
+#define PRESERVE_WINDOWS_ERROR_CODE
+#endif
+
const char *
curl_easy_strerror(CURLcode error)
{
@@ -432,6 +436,10 @@ curl_share_strerror(CURLSHcode error)
static const char *
get_winsock_error (int err, char *buf, size_t len)
{
+#ifdef PRESERVE_WINDOWS_ERROR_CODE
+ DWORD old_win_err = GetLastError();
+#endif
+ int old_errno = errno;
const char *p;
#ifndef CURL_DISABLE_VERBOSE_STRINGS
@@ -611,6 +619,15 @@ get_winsock_error (int err, char *buf, size_t len)
#endif
strncpy(buf, p, len);
buf [len-1] = '\0';
+
+ if(errno != old_errno)
+ errno = old_errno;
+
+#ifdef PRESERVE_WINDOWS_ERROR_CODE
+ if(old_win_err != GetLastError())
+ SetLastError(old_win_err);
+#endif
+
return buf;
}
#endif /* USE_WINSOCK */
@@ -628,9 +645,12 @@ get_winsock_error (int err, char *buf, size_t len)
*/
const char *Curl_strerror(struct connectdata *conn, int err)
{
+#ifdef PRESERVE_WINDOWS_ERROR_CODE
+ DWORD old_win_err = GetLastError();
+#endif
+ int old_errno = errno;
char *buf, *p;
size_t max;
- int old_errno = ERRNO;
DEBUGASSERT(conn);
DEBUGASSERT(err >= 0);
@@ -722,8 +742,13 @@ const char *Curl_strerror(struct connectdata *conn, int err)
if(p && (p - buf) >= 1)
*p = '\0';
- if(old_errno != ERRNO)
- SET_ERRNO(old_errno);
+ if(errno != old_errno)
+ errno = old_errno;
+
+#ifdef PRESERVE_WINDOWS_ERROR_CODE
+ if(old_win_err != GetLastError())
+ SetLastError(old_win_err);
+#endif
return buf;
}
@@ -731,16 +756,19 @@ const char *Curl_strerror(struct connectdata *conn, int err)
#ifdef USE_WINDOWS_SSPI
const char *Curl_sspi_strerror (struct connectdata *conn, int err)
{
+#ifdef PRESERVE_WINDOWS_ERROR_CODE
+ DWORD old_win_err = GetLastError();
+#endif
+ int old_errno = errno;
+ const char *txt;
+ char *outbuf;
+ size_t outmax;
#ifndef CURL_DISABLE_VERBOSE_STRINGS
char txtbuf[80];
char msgbuf[sizeof(conn->syserr_buf)];
char *p, *str, *msg = NULL;
bool msg_formatted = FALSE;
- int old_errno;
#endif
- const char *txt;
- char *outbuf;
- size_t outmax;
DEBUGASSERT(conn);
@@ -750,8 +778,6 @@ const char *Curl_sspi_strerror (struct connectdata *conn, int err)
#ifndef CURL_DISABLE_VERBOSE_STRINGS
- old_errno = ERRNO;
-
switch(err) {
case SEC_E_OK:
txt = "No error";
@@ -1051,9 +1077,6 @@ const char *Curl_sspi_strerror (struct connectdata *conn, int err)
strncpy(outbuf, str, outmax);
}
- if(old_errno != ERRNO)
- SET_ERRNO(old_errno);
-
#else
if(err == SEC_E_OK)
@@ -1067,6 +1090,14 @@ const char *Curl_sspi_strerror (struct connectdata *conn, int err)
outbuf[outmax] = '\0';
+ if(errno != old_errno)
+ errno = old_errno;
+
+#ifdef PRESERVE_WINDOWS_ERROR_CODE
+ if(old_win_err != GetLastError())
+ SetLastError(old_win_err);
+#endif
+
return outbuf;
}
#endif /* USE_WINDOWS_SSPI */
diff --git a/Utilities/cmcurl/lib/strtoofft.c b/Utilities/cmcurl/lib/strtoofft.c
index b854bf4de..807fc5454 100644
--- a/Utilities/cmcurl/lib/strtoofft.c
+++ b/Utilities/cmcurl/lib/strtoofft.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -20,6 +20,7 @@
*
***************************************************************************/
+#include <errno.h>
#include "curl_setup.h"
#include "strtoofft.h"
@@ -29,10 +30,32 @@
*
* In the ISO C standard (IEEE Std 1003.1), there is a strtoimax() function we
* could use in case strtoll() doesn't exist... See
- * http://www.opengroup.org/onlinepubs/009695399/functions/strtoimax.html
+ * https://www.opengroup.org/onlinepubs/009695399/functions/strtoimax.html
*/
-#ifdef NEED_CURL_STRTOLL
+#if (SIZEOF_CURL_OFF_T > SIZEOF_LONG)
+# ifdef HAVE_STRTOLL
+# define strtooff strtoll
+# else
+# if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_INTEGRAL_MAX_BITS >= 64)
+# if defined(_SAL_VERSION)
+ _Check_return_ _CRTIMP __int64 __cdecl _strtoi64(
+ _In_z_ const char *_String,
+ _Out_opt_ _Deref_post_z_ char **_EndPtr, _In_ int _Radix);
+# else
+ _CRTIMP __int64 __cdecl _strtoi64(const char *_String,
+ char **_EndPtr, int _Radix);
+# endif
+# define strtooff _strtoi64
+# else
+# define PRIVATE_STRTOOFF 1
+# endif
+# endif
+#else
+# define strtooff strtol
+#endif
+
+#ifdef PRIVATE_STRTOOFF
/* Range tests can be used for alphanum decoding if characters are consecutive,
like in ASCII. Else an array is scanned. Determine this condition now. */
@@ -48,11 +71,10 @@ static const char valchars[] =
static int get_char(char c, int base);
/**
- * Emulated version of the strtoll function. This extracts a long long
+ * Custom version of the strtooff function. This extracts a curl_off_t
* value from the given input string and returns it.
*/
-curl_off_t
-curlx_strtoll(const char *nptr, char **endptr, int base)
+static curl_off_t strtooff(const char *nptr, char **endptr, int base)
{
char *end;
int is_negative = 0;
@@ -132,7 +154,7 @@ curlx_strtoll(const char *nptr, char **endptr, int base)
else
value = CURL_OFF_T_MAX;
- SET_ERRNO(ERANGE);
+ errno = ERANGE;
}
if(endptr)
@@ -186,3 +208,34 @@ static int get_char(char c, int base)
return value;
}
#endif /* Only present if we need strtoll, but don't have it. */
+
+/*
+ * Parse a *positive* up to 64 bit number written in ascii.
+ */
+CURLofft curlx_strtoofft(const char *str, char **endp, int base,
+ curl_off_t *num)
+{
+ char *end;
+ curl_off_t number;
+ errno = 0;
+ *num = 0; /* clear by default */
+ while(str && *str && ISSPACE(*str))
+ str++;
+ if('-' == *str) {
+ if(endp)
+ *endp = (char *)str; /* didn't actually move */
+ return CURL_OFFT_INVAL; /* nothing parsed */
+ }
+ number = strtooff(str, &end, base);
+ if(endp)
+ *endp = end;
+ if(errno == ERANGE)
+ /* overflow/underflow */
+ return CURL_OFFT_FLOW;
+ else if(str == end)
+ /* nothing parsed */
+ return CURL_OFFT_INVAL;
+
+ *num = number;
+ return CURL_OFFT_OK;
+}
diff --git a/Utilities/cmcurl/lib/strtoofft.h b/Utilities/cmcurl/lib/strtoofft.h
index f4039f3a3..244411a87 100644
--- a/Utilities/cmcurl/lib/strtoofft.h
+++ b/Utilities/cmcurl/lib/strtoofft.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -40,31 +40,7 @@
* of 'long' the conversion function to use is strtol().
*/
-#if (CURL_SIZEOF_CURL_OFF_T > CURL_SIZEOF_LONG)
-# ifdef HAVE_STRTOLL
-# define curlx_strtoofft strtoll
-# else
-# if defined(_MSC_VER) && (_MSC_VER >= 1300) && (_INTEGRAL_MAX_BITS >= 64)
-# if defined(_SAL_VERSION)
- _Check_return_ _CRTIMP __int64 __cdecl _strtoi64(
- _In_z_ const char *_String,
- _Out_opt_ _Deref_post_z_ char **_EndPtr, _In_ int _Radix);
-# else
- _CRTIMP __int64 __cdecl _strtoi64(const char *_String,
- char **_EndPtr, int _Radix);
-# endif
-# define curlx_strtoofft _strtoi64
-# else
- curl_off_t curlx_strtoll(const char *nptr, char **endptr, int base);
-# define curlx_strtoofft curlx_strtoll
-# define NEED_CURL_STRTOLL 1
-# endif
-# endif
-#else
-# define curlx_strtoofft strtol
-#endif
-
-#if (CURL_SIZEOF_CURL_OFF_T == 4)
+#if (SIZEOF_CURL_OFF_T == 4)
# define CURL_OFF_T_MAX CURL_OFF_T_C(0x7FFFFFFF)
#else
/* assume CURL_SIZEOF_CURL_OFF_T == 8 */
@@ -72,4 +48,13 @@
#endif
#define CURL_OFF_T_MIN (-CURL_OFF_T_MAX - CURL_OFF_T_C(1))
+typedef enum {
+ CURL_OFFT_OK, /* parsed fine */
+ CURL_OFFT_FLOW, /* over or underflow */
+ CURL_OFFT_INVAL /* nothing was parsed */
+} CURLofft;
+
+CURLofft curlx_strtoofft(const char *str, char **endp, int base,
+ curl_off_t *num);
+
#endif /* HEADER_CURL_STRTOOFFT_H */
diff --git a/Utilities/cmcurl/lib/telnet.c b/Utilities/cmcurl/lib/telnet.c
index 155d4b260..a7bed3da1 100644
--- a/Utilities/cmcurl/lib/telnet.c
+++ b/Utilities/cmcurl/lib/telnet.c
@@ -76,7 +76,7 @@
} WHILE_FALSE
#define CURL_SB_ACCUM(x,c) \
do { \
- if(x->subpointer < (x->subbuffer+sizeof x->subbuffer)) \
+ if(x->subpointer < (x->subbuffer + sizeof x->subbuffer)) \
*x->subpointer++ = (c); \
} WHILE_FALSE
@@ -192,6 +192,7 @@ const struct Curl_handler Curl_handler_telnet = {
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_TELNET, /* defport */
CURLPROTO_TELNET, /* protocol */
PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */
@@ -294,8 +295,8 @@ static void negotiate(struct connectdata *conn)
int i;
struct TELNET *tn = (struct TELNET *) conn->data->req.protop;
- for(i = 0;i < CURL_NTELOPTS;i++) {
- if(i==CURL_TELOPT_ECHO)
+ for(i = 0; i < CURL_NTELOPTS; i++) {
+ if(i == CURL_TELOPT_ECHO)
continue;
if(tn->us_preferred[i] == CURL_YES)
@@ -791,7 +792,7 @@ static void printsub(struct Curl_easy *data,
case CURL_TELOPT_NEW_ENVIRON:
if(pointer[1] == CURL_TELQUAL_IS) {
infof(data, " ");
- for(i = 3;i < length;i++) {
+ for(i = 3; i < length; i++) {
switch(pointer[i]) {
case CURL_NEW_ENV_VAR:
infof(data, ", ");
@@ -842,7 +843,7 @@ static CURLcode check_telnet_options(struct connectdata *conn)
tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES;
}
- for(head = data->set.telnet_options; head; head=head->next) {
+ for(head = data->set.telnet_options; head; head = head->next) {
if(sscanf(head->data, "%127[^= ]%*[ =]%255s",
option_keyword, option_arg) == 2) {
@@ -889,8 +890,8 @@ static CURLcode check_telnet_options(struct connectdata *conn)
/* To take care or not of the 8th bit in data exchange */
if(strcasecompare(option_keyword, "BINARY")) {
- binary_option=atoi(option_arg);
- if(binary_option!=1) {
+ binary_option = atoi(option_arg);
+ if(binary_option != 1) {
tn->us_preferred[CURL_TELOPT_BINARY] = CURL_NO;
tn->him_preferred[CURL_TELOPT_BINARY] = CURL_NO;
}
@@ -898,7 +899,7 @@ static CURLcode check_telnet_options(struct connectdata *conn)
}
failf(data, "Unknown telnet option %s", head->data);
- result = CURLE_UNKNOWN_TELNET_OPTION;
+ result = CURLE_UNKNOWN_OPTION;
break;
}
failf(data, "Syntax error in telnet option: %s", head->data);
@@ -934,7 +935,7 @@ static void suboption(struct connectdata *conn)
struct Curl_easy *data = conn->data;
struct TELNET *tn = (struct TELNET *)data->req.protop;
- printsub(data, '<', (unsigned char *)tn->subbuffer, CURL_SB_LEN(tn)+2);
+ printsub(data, '<', (unsigned char *)tn->subbuffer, CURL_SB_LEN(tn) + 2);
switch(CURL_SB_GET(tn)) {
case CURL_TELOPT_TTYPE:
len = strlen(tn->subopt_ttype) + 4 + 2;
@@ -966,7 +967,7 @@ static void suboption(struct connectdata *conn)
CURL_TELQUAL_IS);
len = 4;
- for(v = tn->telnet_vars;v;v = v->next) {
+ for(v = tn->telnet_vars; v; v = v->next) {
tmplen = (strlen(v->data) + 1);
/* Add the variable only if it fits */
if(len + tmplen < (int)sizeof(temp)-6) {
@@ -1018,8 +1019,8 @@ static void sendsuboption(struct connectdata *conn, int option)
CURL_SB_ACCUM(tn, CURL_TELOPT_NAWS);
/* We must deal either with litte or big endian processors */
/* Window size must be sent according to the 'network order' */
- x=htons(tn->subopt_wsx);
- y=htons(tn->subopt_wsy);
+ x = htons(tn->subopt_wsx);
+ y = htons(tn->subopt_wsy);
uc1 = (unsigned char *)&x;
uc2 = (unsigned char *)&y;
CURL_SB_ACCUM(tn, uc1[0]);
@@ -1032,7 +1033,7 @@ static void sendsuboption(struct connectdata *conn, int option)
CURL_SB_TERM(tn);
/* data suboption is now ready */
- printsub(data, '>', (unsigned char *)tn->subbuffer+2,
+ printsub(data, '>', (unsigned char *)tn->subbuffer + 2,
CURL_SB_LEN(tn)-2);
/* we send the header of the suboption... */
@@ -1043,9 +1044,9 @@ static void sendsuboption(struct connectdata *conn, int option)
}
/* ... then the window size with the send_telnet_data() function
to deal with 0xFF cases ... */
- send_telnet_data(conn, (char *)tn->subbuffer+3, 4);
+ send_telnet_data(conn, (char *)tn->subbuffer + 3, 4);
/* ... and the footer */
- bytes_written = swrite(conn->sock[FIRSTSOCKET], tn->subbuffer+7, 2);
+ bytes_written = swrite(conn->sock[FIRSTSOCKET], tn->subbuffer + 7, 2);
if(bytes_written < 0) {
err = SOCKERRNO;
failf(data, "Sending data failed (%d)", err);
@@ -1063,7 +1064,7 @@ CURLcode telrcv(struct connectdata *conn,
unsigned char c;
CURLcode result;
int in = 0;
- int startwrite=-1;
+ int startwrite = -1;
struct Curl_easy *data = conn->data;
struct TELNET *tn = (struct TELNET *)data->req.protop;
@@ -1326,7 +1327,7 @@ static CURLcode telnet_do(struct connectdata *conn, bool *done)
curl_off_t total_ul = 0;
#endif
ssize_t nread;
- struct timeval now;
+ struct curltime now;
bool keepon = TRUE;
char *buf = data->state.buffer;
struct TELNET *tn;
@@ -1356,14 +1357,14 @@ static CURLcode telnet_do(struct connectdata *conn, bool *done)
/* load ws2_32.dll and get the function pointers we need. */
wsock2 = Curl_load_library(TEXT("WS2_32.DLL"));
if(wsock2 == NULL) {
- failf(data, "failed to load WS2_32.DLL (%d)", ERRNO);
+ failf(data, "failed to load WS2_32.DLL (%u)", GetLastError());
return CURLE_FAILED_INIT;
}
/* Grab a pointer to WSACreateEvent */
create_event_func = GetProcAddress(wsock2, "WSACreateEvent");
if(create_event_func == NULL) {
- failf(data, "failed to find WSACreateEvent function (%d)", ERRNO);
+ failf(data, "failed to find WSACreateEvent function (%u)", GetLastError());
FreeLibrary(wsock2);
return CURLE_FAILED_INIT;
}
@@ -1371,7 +1372,7 @@ static CURLcode telnet_do(struct connectdata *conn, bool *done)
/* And WSACloseEvent */
close_event_func = GetProcAddress(wsock2, "WSACloseEvent");
if(close_event_func == NULL) {
- failf(data, "failed to find WSACloseEvent function (%d)", ERRNO);
+ failf(data, "failed to find WSACloseEvent function (%u)", GetLastError());
FreeLibrary(wsock2);
return CURLE_FAILED_INIT;
}
@@ -1379,7 +1380,7 @@ static CURLcode telnet_do(struct connectdata *conn, bool *done)
/* And WSAEventSelect */
event_select_func = GetProcAddress(wsock2, "WSAEventSelect");
if(event_select_func == NULL) {
- failf(data, "failed to find WSAEventSelect function (%d)", ERRNO);
+ failf(data, "failed to find WSAEventSelect function (%u)", GetLastError());
FreeLibrary(wsock2);
return CURLE_FAILED_INIT;
}
@@ -1387,7 +1388,8 @@ static CURLcode telnet_do(struct connectdata *conn, bool *done)
/* And WSAEnumNetworkEvents */
enum_netevents_func = GetProcAddress(wsock2, "WSAEnumNetworkEvents");
if(enum_netevents_func == NULL) {
- failf(data, "failed to find WSAEnumNetworkEvents function (%d)", ERRNO);
+ failf(data, "failed to find WSAEnumNetworkEvents function (%u)",
+ GetLastError());
FreeLibrary(wsock2);
return CURLE_FAILED_INIT;
}
@@ -1580,7 +1582,7 @@ static CURLcode telnet_do(struct connectdata *conn, bool *done)
/* We called LoadLibrary, so call FreeLibrary */
if(!FreeLibrary(wsock2))
- infof(data, "FreeLibrary(wsock2) failed (%d)", ERRNO);
+ infof(data, "FreeLibrary(wsock2) failed (%u)", GetLastError());
#else
pfd[0].fd = sockfd;
pfd[0].events = POLLIN;
diff --git a/Utilities/cmcurl/lib/tftp.c b/Utilities/cmcurl/lib/tftp.c
index b2b3efe0c..4e599fd27 100644
--- a/Utilities/cmcurl/lib/tftp.c
+++ b/Utilities/cmcurl/lib/tftp.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -76,12 +76,12 @@
#define TFTP_OPTION_INTERVAL "timeout"
typedef enum {
- TFTP_MODE_NETASCII=0,
+ TFTP_MODE_NETASCII = 0,
TFTP_MODE_OCTET
} tftp_mode_t;
typedef enum {
- TFTP_STATE_START=0,
+ TFTP_STATE_START = 0,
TFTP_STATE_RX,
TFTP_STATE_TX,
TFTP_STATE_FIN
@@ -100,7 +100,7 @@ typedef enum {
} tftp_event_t;
typedef enum {
- TFTP_ERR_UNDEF=0,
+ TFTP_ERR_UNDEF = 0,
TFTP_ERR_NOTFOUND,
TFTP_ERR_PERM,
TFTP_ERR_DISKFULL,
@@ -181,6 +181,7 @@ const struct Curl_handler Curl_handler_tftp = {
ZERO_NULL, /* perform_getsock */
tftp_disconnect, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
PORT_TFTP, /* defport */
CURLPROTO_TFTP, /* protocol */
PROTOPT_NONE | PROTOPT_NOURLQUERY /* flags */
@@ -216,7 +217,7 @@ static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
if(start) {
maxtime = (time_t)(timeout_ms + 500) / 1000;
- state->max_time = state->start_time+maxtime;
+ state->max_time = state->start_time + maxtime;
/* Set per-block timeout to total */
timeout = maxtime;
@@ -231,7 +232,7 @@ static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
/* Compute the re-start interval to suit the timeout */
state->retry_time = (int)timeout/state->retry_max;
if(state->retry_time<1)
- state->retry_time=1;
+ state->retry_time = 1;
}
else {
@@ -240,7 +241,7 @@ static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
else
maxtime = 3600;
- state->max_time = state->start_time+maxtime;
+ state->max_time = state->start_time + maxtime;
/* Set per-block timeout to total */
timeout = maxtime;
@@ -250,15 +251,15 @@ static CURLcode tftp_set_timeouts(tftp_state_data_t *state)
}
/* But bound the total number */
if(state->retry_max<3)
- state->retry_max=3;
+ state->retry_max = 3;
if(state->retry_max>50)
- state->retry_max=50;
+ state->retry_max = 50;
/* Compute the re-ACK interval to suit the timeout */
state->retry_time = (int)(timeout/state->retry_max);
if(state->retry_time<1)
- state->retry_time=1;
+ state->retry_time = 1;
infof(state->conn->data,
"set timeouts for state %d; Total %ld, retry %d maxtry %d\n",
@@ -320,7 +321,7 @@ static const char *tftp_option_get(const char *buf, size_t len,
return NULL;
*option = buf;
- loc += Curl_strnlen(buf+loc, len-loc);
+ loc += Curl_strnlen(buf + loc, len-loc);
loc++; /* NULL term */
if(loc > len)
@@ -474,7 +475,7 @@ static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
/* If we are uploading, send an WRQ */
setpacketevent(&state->spacket, TFTP_EVENT_WRQ);
state->conn->data->req.upload_fromhere =
- (char *)state->spacket.data+4;
+ (char *)state->spacket.data + 4;
if(data->state.infilesize != -1)
Curl_pgrsSetUploadSize(data, data->state.infilesize);
}
@@ -490,7 +491,13 @@ static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
if(result)
return result;
- snprintf((char *)state->spacket.data+2,
+ if(strlen(filename) > (state->blksize - strlen(mode) - 4)) {
+ failf(data, "TFTP file name too long\n");
+ free(filename);
+ return CURLE_TFTP_ILLEGAL; /* too long file name field */
+ }
+
+ snprintf((char *)state->spacket.data + 2,
state->blksize,
"%s%c%s%c", filename, '\0', mode, '\0');
sbytes = 4 + strlen(filename) + strlen(mode);
@@ -505,25 +512,25 @@ static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
strcpy(buf, "0"); /* the destination is large enough */
sbytes += tftp_option_add(state, sbytes,
- (char *)state->spacket.data+sbytes,
+ (char *)state->spacket.data + sbytes,
TFTP_OPTION_TSIZE);
sbytes += tftp_option_add(state, sbytes,
- (char *)state->spacket.data+sbytes, buf);
+ (char *)state->spacket.data + sbytes, buf);
/* add blksize option */
snprintf(buf, sizeof(buf), "%d", state->requested_blksize);
sbytes += tftp_option_add(state, sbytes,
- (char *)state->spacket.data+sbytes,
+ (char *)state->spacket.data + sbytes,
TFTP_OPTION_BLKSIZE);
sbytes += tftp_option_add(state, sbytes,
- (char *)state->spacket.data+sbytes, buf);
+ (char *)state->spacket.data + sbytes, buf);
/* add timeout option */
snprintf(buf, sizeof(buf), "%d", state->retry_time);
sbytes += tftp_option_add(state, sbytes,
- (char *)state->spacket.data+sbytes,
+ (char *)state->spacket.data + sbytes,
TFTP_OPTION_INTERVAL);
sbytes += tftp_option_add(state, sbytes,
- (char *)state->spacket.data+sbytes, buf);
+ (char *)state->spacket.data + sbytes, buf);
}
/* the typecase for the 3rd argument is mostly for systems that do
@@ -569,7 +576,7 @@ static CURLcode tftp_send_first(tftp_state_data_t *state, tftp_event_t event)
/* the next blocknum is x + 1 but it needs to wrap at an unsigned 16bit
boundary */
-#define NEXT_BLOCKNUM(x) (((x)+1)&0xffff)
+#define NEXT_BLOCKNUM(x) (((x) + 1)&0xffff)
/**********************************************************
*
@@ -620,7 +627,7 @@ static CURLcode tftp_rx(tftp_state_data_t *state, tftp_event_t event)
}
/* Check if completed (That is, a less than full packet is received) */
- if(state->rbytes < (ssize_t)state->blksize+4) {
+ if(state->rbytes < (ssize_t)state->blksize + 4) {
state->state = TFTP_STATE_FIN;
}
else {
@@ -736,7 +743,7 @@ static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
else {
/* Re-send the data packet */
sbytes = sendto(state->sockfd, (void *)state->spacket.data,
- 4+state->sbytes, SEND_4TH_ARG,
+ 4 + state->sbytes, SEND_4TH_ARG,
(struct sockaddr *)&state->remote_addr,
state->remote_addrlen);
/* Check all sbytes were sent */
@@ -769,7 +776,7 @@ static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
* data block.
* */
state->sbytes = 0;
- state->conn->data->req.upload_fromhere = (char *)state->spacket.data+4;
+ state->conn->data->req.upload_fromhere = (char *)state->spacket.data + 4;
do {
result = Curl_fillreadbuffer(state->conn, state->blksize - state->sbytes,
&cb);
@@ -806,7 +813,7 @@ static CURLcode tftp_tx(tftp_state_data_t *state, tftp_event_t event)
else {
/* Re-send the data packet */
sbytes = sendto(state->sockfd, (void *)state->spacket.data,
- 4+state->sbytes, SEND_4TH_ARG,
+ 4 + state->sbytes, SEND_4TH_ARG,
(struct sockaddr *)&state->remote_addr,
state->remote_addrlen);
/* Check all sbytes were sent */
@@ -1102,11 +1109,11 @@ static CURLcode tftp_receive_packet(struct connectdata *conn)
fromlen = sizeof(fromaddr);
state->rbytes = (int)recvfrom(state->sockfd,
(void *)state->rpacket.data,
- state->blksize+4,
+ state->blksize + 4,
0,
(struct sockaddr *)&fromaddr,
&fromlen);
- if(state->remote_addrlen==0) {
+ if(state->remote_addrlen == 0) {
memcpy(&state->remote_addr, &fromaddr, fromlen);
state->remote_addrlen = fromlen;
}
@@ -1128,7 +1135,7 @@ static CURLcode tftp_receive_packet(struct connectdata *conn)
if(state->rbytes > 4 &&
(NEXT_BLOCKNUM(state->block) == getrpacketblock(&state->rpacket))) {
result = Curl_client_write(conn, CLIENTWRITE_BODY,
- (char *)state->rpacket.data+4,
+ (char *)state->rpacket.data + 4,
state->rbytes-4);
if(result) {
tftp_state_machine(state, TFTP_EVENT_ERROR);
@@ -1142,14 +1149,14 @@ static CURLcode tftp_receive_packet(struct connectdata *conn)
{
unsigned short error = getrpacketblock(&state->rpacket);
state->error = (tftp_error_t)error;
- infof(data, "%s\n", (const char *)state->rpacket.data+4);
+ infof(data, "%s\n", (const char *)state->rpacket.data + 4);
break;
}
case TFTP_EVENT_ACK:
break;
case TFTP_EVENT_OACK:
result = tftp_parse_option_ack(state,
- (const char *)state->rpacket.data+2,
+ (const char *)state->rpacket.data + 2,
state->rbytes-2);
if(result)
return result;
@@ -1193,7 +1200,7 @@ static long tftp_state_timeout(struct connectdata *conn, tftp_event_t *event)
state->state = TFTP_STATE_FIN;
return 0;
}
- if(current > state->rx_time+state->retry_time) {
+ if(current > state->rx_time + state->retry_time) {
if(event)
*event = TFTP_EVENT_TIMEOUT;
time(&state->rx_time); /* update even though we received nothing */
@@ -1344,7 +1351,7 @@ static CURLcode tftp_do(struct connectdata *conn, bool *done)
state = (tftp_state_data_t *)conn->proto.tftpc;
if(!state)
- return CURLE_BAD_CALLING_ORDER;
+ return CURLE_TFTP_ILLEGAL;
result = tftp_perform(conn, done);
diff --git a/Utilities/cmcurl/lib/timeval.c b/Utilities/cmcurl/lib/timeval.c
index bed44c573..d7207b3a2 100644
--- a/Utilities/cmcurl/lib/timeval.c
+++ b/Utilities/cmcurl/lib/timeval.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -24,14 +24,14 @@
#if defined(WIN32) && !defined(MSDOS)
-struct timeval curlx_tvnow(void)
+struct curltime curlx_tvnow(void)
{
/*
** GetTickCount() is available on _all_ Windows versions from W95 up
** to nowadays. Returns milliseconds elapsed since last system boot,
** increases monotonically and wraps once 49.7 days have elapsed.
*/
- struct timeval now;
+ struct curltime now;
#if !defined(_WIN32_WINNT) || !defined(_WIN32_WINNT_VISTA) || \
(_WIN32_WINNT < _WIN32_WINNT_VISTA)
DWORD milliseconds = GetTickCount();
@@ -39,8 +39,8 @@ struct timeval curlx_tvnow(void)
now.tv_usec = (milliseconds % 1000) * 1000;
#else
ULONGLONG milliseconds = GetTickCount64();
- now.tv_sec = (long) (milliseconds / 1000);
- now.tv_usec = (long) (milliseconds % 1000) * 1000;
+ now.tv_sec = (time_t) (milliseconds / 1000);
+ now.tv_usec = (unsigned int) (milliseconds % 1000) * 1000;
#endif
return now;
@@ -48,7 +48,7 @@ struct timeval curlx_tvnow(void)
#elif defined(HAVE_CLOCK_GETTIME_MONOTONIC)
-struct timeval curlx_tvnow(void)
+struct curltime curlx_tvnow(void)
{
/*
** clock_gettime() is granted to be increased monotonically when the
@@ -58,10 +58,11 @@ struct timeval curlx_tvnow(void)
** system has started up.
*/
struct timeval now;
+ struct curltime cnow;
struct timespec tsnow;
if(0 == clock_gettime(CLOCK_MONOTONIC, &tsnow)) {
- now.tv_sec = tsnow.tv_sec;
- now.tv_usec = tsnow.tv_nsec / 1000;
+ cnow.tv_sec = tsnow.tv_sec;
+ cnow.tv_usec = (unsigned int)(tsnow.tv_nsec / 1000);
}
/*
** Even when the configure process has truly detected monotonic clock
@@ -69,20 +70,23 @@ struct timeval curlx_tvnow(void)
** run-time. When this occurs simply fallback to other time source.
*/
#ifdef HAVE_GETTIMEOFDAY
- else
+ else {
(void)gettimeofday(&now, NULL);
+ cnow.tv_sec = now.tv_sec;
+ cnow.tv_usec = (unsigned int)now.tv_usec;
+ }
#else
else {
- now.tv_sec = (long)time(NULL);
- now.tv_usec = 0;
+ cnow.tv_sec = time(NULL);
+ cnow.tv_usec = 0;
}
#endif
- return now;
+ return cnow;
}
#elif defined(HAVE_GETTIMEOFDAY)
-struct timeval curlx_tvnow(void)
+struct curltime curlx_tvnow(void)
{
/*
** gettimeofday() is not granted to be increased monotonically, due to
@@ -90,19 +94,22 @@ struct timeval curlx_tvnow(void)
** forward or backward in time.
*/
struct timeval now;
+ struct curltime ret;
(void)gettimeofday(&now, NULL);
- return now;
+ ret.tv_sec = now.tv_sec;
+ ret.tv_usec = now.tv_usec;
+ return ret;
}
#else
-struct timeval curlx_tvnow(void)
+struct curltime curlx_tvnow(void)
{
/*
** time() returns the value of time in seconds since the Epoch.
*/
- struct timeval now;
- now.tv_sec = (long)time(NULL);
+ struct curltime now;
+ now.tv_sec = time(NULL);
now.tv_usec = 0;
return now;
}
@@ -115,8 +122,10 @@ struct timeval curlx_tvnow(void)
*
* Returns: the time difference in number of milliseconds. For large diffs it
* returns 0x7fffffff on 32bit time_t systems.
+ *
+ * @unittest: 1323
*/
-time_t curlx_tvdiff(struct timeval newer, struct timeval older)
+time_t curlx_tvdiff(struct curltime newer, struct curltime older)
{
#if SIZEOF_TIME_T < 8
/* for 32bit time_t systems, add a precaution to avoid overflow for really
@@ -126,18 +135,28 @@ time_t curlx_tvdiff(struct timeval newer, struct timeval older)
return 0x7fffffff;
#endif
return (newer.tv_sec-older.tv_sec)*1000+
- (time_t)(newer.tv_usec-older.tv_usec)/1000;
+ (int)(newer.tv_usec-older.tv_usec)/1000;
}
/*
- * Same as curlx_tvdiff but with full usec resolution.
+ * Make sure that the first argument is the more recent time, as otherwise
+ * we'll get a weird negative time-diff back...
*
- * Returns: the time difference in seconds with subsecond resolution.
+ * Returns: the time difference in number of microseconds. For too large diffs
+ * it returns max value.
*/
-double curlx_tvdiff_secs(struct timeval newer, struct timeval older)
+time_t Curl_tvdiff_us(struct curltime newer, struct curltime older)
{
- if(newer.tv_sec != older.tv_sec)
- return (double)(newer.tv_sec-older.tv_sec)+
- (double)(newer.tv_usec-older.tv_usec)/1000000.0;
- return (double)(newer.tv_usec-older.tv_usec)/1000000.0;
+ time_t diff = newer.tv_sec-older.tv_sec;
+#if SIZEOF_TIME_T < 8
+ /* for 32bit time_t systems */
+ if(diff >= (0x7fffffff/1000000))
+ return 0x7fffffff;
+#else
+ /* for 64bit time_t systems */
+ if(diff >= (0x7fffffffffffffffLL/1000000))
+ return 0x7fffffffffffffffLL;
+#endif
+ return (newer.tv_sec-older.tv_sec)*1000000+
+ (int)(newer.tv_usec-older.tv_usec);
}
diff --git a/Utilities/cmcurl/lib/timeval.h b/Utilities/cmcurl/lib/timeval.h
index 33969354d..1ee4b3044 100644
--- a/Utilities/cmcurl/lib/timeval.h
+++ b/Utilities/cmcurl/lib/timeval.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -29,7 +29,12 @@
#include "curl_setup.h"
-struct timeval curlx_tvnow(void);
+struct curltime {
+ time_t tv_sec; /* seconds */
+ unsigned int tv_usec; /* microseconds */
+};
+
+struct curltime curlx_tvnow(void);
/*
* Make sure that the first argument (t1) is the more recent time and t2 is
@@ -37,20 +42,20 @@ struct timeval curlx_tvnow(void);
*
* Returns: the time difference in number of milliseconds.
*/
-time_t curlx_tvdiff(struct timeval t1, struct timeval t2);
+time_t curlx_tvdiff(struct curltime t1, struct curltime t2);
/*
- * Same as curlx_tvdiff but with full usec resolution.
+ * Make sure that the first argument (t1) is the more recent time and t2 is
+ * the older time, as otherwise you get a weird negative time-diff back...
*
- * Returns: the time difference in seconds with subsecond resolution.
+ * Returns: the time difference in number of microseconds.
*/
-double curlx_tvdiff_secs(struct timeval t1, struct timeval t2);
+time_t Curl_tvdiff_us(struct curltime newer, struct curltime older);
/* These two defines below exist to provide the older API for library
internals only. */
#define Curl_tvnow() curlx_tvnow()
#define Curl_tvdiff(x,y) curlx_tvdiff(x,y)
-#define Curl_tvdiff_secs(x,y) curlx_tvdiff_secs(x,y)
#endif /* HEADER_CURL_TIMEVAL_H */
diff --git a/Utilities/cmcurl/lib/transfer.c b/Utilities/cmcurl/lib/transfer.c
index 43e8f64aa..8e66d0d80 100644
--- a/Utilities/cmcurl/lib/transfer.c
+++ b/Utilities/cmcurl/lib/transfer.c
@@ -73,12 +73,38 @@
#include "connect.h"
#include "non-ascii.h"
#include "http2.h"
+#include "mime.h"
+#include "strcase.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
+#if !defined(CURL_DISABLE_HTTP) || !defined(CURL_DISABLE_SMTP) || \
+ !defined(CURL_DISABLE_IMAP)
+/*
+ * checkheaders() checks the linked list of custom headers for a
+ * particular header (prefix).
+ *
+ * Returns a pointer to the first matching header or NULL if none matched.
+ */
+char *Curl_checkheaders(const struct connectdata *conn,
+ const char *thisheader)
+{
+ struct curl_slist *head;
+ size_t thislen = strlen(thisheader);
+ struct Curl_easy *data = conn->data;
+
+ for(head = data->set.headers; head; head = head->next) {
+ if(strncasecompare(head->data, thisheader, thislen))
+ return head->data;
+ }
+
+ return NULL;
+}
+#endif
+
/*
* This function will call the read callback to fill our buffer with data
* to upload.
@@ -195,27 +221,28 @@ CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp)
strlen(endofline_network));
#ifdef CURL_DOES_CONVERSIONS
- CURLcode result;
- int length;
- if(data->set.prefer_ascii) {
- /* translate the protocol and data */
- length = nread;
- }
- else {
- /* just translate the protocol portion */
- length = strlen(hexbuffer);
+ {
+ CURLcode result;
+ int length;
+ if(data->set.prefer_ascii)
+ /* translate the protocol and data */
+ length = nread;
+ else
+ /* just translate the protocol portion */
+ length = (int)strlen(hexbuffer);
+ result = Curl_convert_to_network(data, data->req.upload_fromhere,
+ length);
+ /* Curl_convert_to_network calls failf if unsuccessful */
+ if(result)
+ return result;
}
- result = Curl_convert_to_network(data, data->req.upload_fromhere, length);
- /* Curl_convert_to_network calls failf if unsuccessful */
- if(result)
- return result;
#endif /* CURL_DOES_CONVERSIONS */
if((nread - hexlen) == 0)
/* mark this as done once this chunk is transferred */
data->req.upload_done = TRUE;
- nread+=(int)strlen(endofline_native); /* for the added end of line */
+ nread += (int)strlen(endofline_native); /* for the added end of line */
}
#ifdef CURL_DOES_CONVERSIONS
else if((data->set.prefer_ascii) && (!sending_http_headers)) {
@@ -241,6 +268,7 @@ CURLcode Curl_fillreadbuffer(struct connectdata *conn, int bytes, int *nreadp)
CURLcode Curl_readrewind(struct connectdata *conn)
{
struct Curl_easy *data = conn->data;
+ curl_mimepart *mimepart = &data->set.mimepost;
conn->bits.rewindaftersend = FALSE; /* we rewind now */
@@ -253,9 +281,21 @@ CURLcode Curl_readrewind(struct connectdata *conn)
/* We have sent away data. If not using CURLOPT_POSTFIELDS or
CURLOPT_HTTPPOST, call app to rewind
*/
- if(data->set.postfields ||
- (data->set.httpreq == HTTPREQ_POST_FORM))
+ if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
+ struct HTTP *http = data->req.protop;
+
+ if(http->sendit)
+ mimepart = http->sendit;
+ }
+ if(data->set.postfields)
; /* do nothing */
+ else if(data->set.httpreq == HTTPREQ_POST_MIME ||
+ data->set.httpreq == HTTPREQ_POST_FORM) {
+ if(Curl_mime_rewind(mimepart)) {
+ failf(data, "Cannot rewind mime/post data");
+ return CURLE_SEND_FAIL_REWIND;
+ }
+ }
else {
if(data->set.seek_func) {
int err;
@@ -560,7 +600,7 @@ static CURLcode readwrite_data(struct Curl_easy *data,
infof(data, "Ignoring the response-body\n");
}
if(data->state.resume_from && !k->content_range &&
- (data->set.httpreq==HTTPREQ_GET) &&
+ (data->set.httpreq == HTTPREQ_GET) &&
!k->ignorebody) {
if(k->size == data->state.resume_from) {
@@ -915,7 +955,7 @@ static CURLcode readwrite_upload(struct Curl_easy *data,
/* this is a paused transfer */
break;
}
- if(nread<=0) {
+ if(nread <= 0) {
result = done_sending(conn, k);
if(result)
return result;
@@ -1055,7 +1095,7 @@ CURLcode Curl_readwrite(struct connectdata *conn,
{
struct SingleRequest *k = &data->req;
CURLcode result;
- int didwhat=0;
+ int didwhat = 0;
curl_socket_t fd_read;
curl_socket_t fd_write;
@@ -1288,6 +1328,13 @@ CURLcode Curl_pretransfer(struct Curl_easy *data)
failf(data, "No URL set!");
return CURLE_URL_MALFORMAT;
}
+ /* since the URL may have been redirected in a previous use of this handle */
+ if(data->change.url_alloc) {
+ /* the already set URL is allocated, free it first! */
+ Curl_safefree(data->change.url);
+ data->change.url_alloc = FALSE;
+ }
+ data->change.url = data->set.str[STRING_SET_URL];
/* Init the SSL session ID cache here. We do it here since we want to do it
after the *_setopt() calls (that could specify the size of the cache) but
@@ -1296,7 +1343,7 @@ CURLcode Curl_pretransfer(struct Curl_easy *data)
if(result)
return result;
- data->set.followlocation=0; /* reset the location-follow counter */
+ data->set.followlocation = 0; /* reset the location-follow counter */
data->state.this_is_a_follow = FALSE; /* reset this */
data->state.errorbuf = FALSE; /* no error has occurred */
data->state.httpversion = 0; /* don't assume any particular server version */
@@ -1338,7 +1385,7 @@ CURLcode Curl_pretransfer(struct Curl_easy *data)
#endif
Curl_initinfo(data); /* reset session-specific information "variables" */
- Curl_pgrsResetTimesSizes(data);
+ Curl_pgrsResetTransferSizes(data);
Curl_pgrsStartNow(data);
if(data->set.timeout)
@@ -1384,19 +1431,59 @@ CURLcode Curl_posttransfer(struct Curl_easy *data)
#ifndef CURL_DISABLE_HTTP
/*
+ * Find the separator at the end of the host name, or the '?' in cases like
+ * http://www.url.com?id=2380
+ */
+static const char *find_host_sep(const char *url)
+{
+ const char *sep;
+ const char *query;
+
+ /* Find the start of the hostname */
+ sep = strstr(url, "//");
+ if(!sep)
+ sep = url;
+ else
+ sep += 2;
+
+ query = strchr(sep, '?');
+ sep = strchr(sep, '/');
+
+ if(!sep)
+ sep = url + strlen(url);
+
+ if(!query)
+ query = url + strlen(url);
+
+ return sep < query ? sep : query;
+}
+
+/*
* strlen_url() returns the length of the given URL if the spaces within the
* URL were properly URL encoded.
+ * URL encoding should be skipped for host names, otherwise IDN resolution
+ * will fail.
*/
-static size_t strlen_url(const char *url)
+static size_t strlen_url(const char *url, bool relative)
{
const unsigned char *ptr;
- size_t newlen=0;
- bool left=TRUE; /* left side of the ? */
+ size_t newlen = 0;
+ bool left = TRUE; /* left side of the ? */
+ const unsigned char *host_sep = (const unsigned char *) url;
+
+ if(!relative)
+ host_sep = (const unsigned char *) find_host_sep(url);
+
+ for(ptr = (unsigned char *)url; *ptr; ptr++) {
+
+ if(ptr < host_sep) {
+ ++newlen;
+ continue;
+ }
- for(ptr=(unsigned char *)url; *ptr; ptr++) {
switch(*ptr) {
case '?':
- left=FALSE;
+ left = FALSE;
/* fall through */
default:
if(*ptr >= 0x80)
@@ -1405,7 +1492,7 @@ static size_t strlen_url(const char *url)
break;
case ' ':
if(left)
- newlen+=3;
+ newlen += 3;
else
newlen++;
break;
@@ -1416,19 +1503,32 @@ static size_t strlen_url(const char *url)
/* strcpy_url() copies a url to a output buffer and URL-encodes the spaces in
* the source URL accordingly.
+ * URL encoding should be skipped for host names, otherwise IDN resolution
+ * will fail.
*/
-static void strcpy_url(char *output, const char *url)
+static void strcpy_url(char *output, const char *url, bool relative)
{
/* we must add this with whitespace-replacing */
- bool left=TRUE;
+ bool left = TRUE;
const unsigned char *iptr;
char *optr = output;
+ const unsigned char *host_sep = (const unsigned char *) url;
+
+ if(!relative)
+ host_sep = (const unsigned char *) find_host_sep(url);
+
for(iptr = (unsigned char *)url; /* read from here */
*iptr; /* until zero byte */
iptr++) {
+
+ if(iptr < host_sep) {
+ *optr++ = *iptr;
+ continue;
+ }
+
switch(*iptr) {
case '?':
- left=FALSE;
+ left = FALSE;
/* fall through */
default:
if(*iptr >= 0x80) {
@@ -1449,7 +1549,7 @@ static void strcpy_url(char *output, const char *url)
break;
}
}
- *optr=0; /* zero terminate output buffer */
+ *optr = 0; /* zero terminate output buffer */
}
@@ -1481,32 +1581,33 @@ static char *concat_url(const char *base, const char *relurl)
char *protsep;
char *pathsep;
size_t newlen;
+ bool host_changed = FALSE;
const char *useurl = relurl;
size_t urllen;
/* we must make our own copy of the URL to play with, as it may
point to read-only data */
- char *url_clone=strdup(base);
+ char *url_clone = strdup(base);
if(!url_clone)
return NULL; /* skip out of this NOW */
/* protsep points to the start of the host name */
- protsep=strstr(url_clone, "//");
+ protsep = strstr(url_clone, "//");
if(!protsep)
- protsep=url_clone;
+ protsep = url_clone;
else
- protsep+=2; /* pass the slashes */
+ protsep += 2; /* pass the slashes */
if('/' != relurl[0]) {
- int level=0;
+ int level = 0;
/* First we need to find out if there's a ?-letter in the URL,
and cut it and the right-side of that off */
pathsep = strchr(protsep, '?');
if(pathsep)
- *pathsep=0;
+ *pathsep = 0;
/* we have a relative path to append to the last slash if there's one
available, or if the new URL is just a query string (starts with a
@@ -1515,14 +1616,14 @@ static char *concat_url(const char *base, const char *relurl)
if(useurl[0] != '?') {
pathsep = strrchr(protsep, '/');
if(pathsep)
- *pathsep=0;
+ *pathsep = 0;
}
/* Check if there's any slash after the host name, and if so, remember
that position instead */
pathsep = strchr(protsep, '/');
if(pathsep)
- protsep = pathsep+1;
+ protsep = pathsep + 1;
else
protsep = NULL;
@@ -1530,13 +1631,13 @@ static char *concat_url(const char *base, const char *relurl)
and act accordingly */
if((useurl[0] == '.') && (useurl[1] == '/'))
- useurl+=2; /* just skip the "./" */
+ useurl += 2; /* just skip the "./" */
while((useurl[0] == '.') &&
(useurl[1] == '.') &&
(useurl[2] == '/')) {
level++;
- useurl+=3; /* pass the "../" */
+ useurl += 3; /* pass the "../" */
}
if(protsep) {
@@ -1544,9 +1645,9 @@ static char *concat_url(const char *base, const char *relurl)
/* cut off one more level from the right of the original URL */
pathsep = strrchr(protsep, '/');
if(pathsep)
- *pathsep=0;
+ *pathsep = 0;
else {
- *protsep=0;
+ *protsep = 0;
break;
}
}
@@ -1558,9 +1659,10 @@ static char *concat_url(const char *base, const char *relurl)
if((relurl[0] == '/') && (relurl[1] == '/')) {
/* the new URL starts with //, just keep the protocol part from the
original one */
- *protsep=0;
+ *protsep = 0;
useurl = &relurl[2]; /* we keep the slashes from the original, so we
skip the new ones */
+ host_changed = TRUE;
}
else {
/* cut off the original URL from the first slash, or deal with URLs
@@ -1573,7 +1675,7 @@ static char *concat_url(const char *base, const char *relurl)
char *sep = strchr(protsep, '?');
if(sep && (sep < pathsep))
pathsep = sep;
- *pathsep=0;
+ *pathsep = 0;
}
else {
/* There was no slash. Now, since we might be operating on a badly
@@ -1582,7 +1684,7 @@ static char *concat_url(const char *base, const char *relurl)
?-letter as well! */
pathsep = strchr(protsep, '?');
if(pathsep)
- *pathsep=0;
+ *pathsep = 0;
}
}
}
@@ -1592,7 +1694,7 @@ static char *concat_url(const char *base, const char *relurl)
letter we replace each space with %20 while it is replaced with '+'
on the right side of the '?' letter.
*/
- newlen = strlen_url(useurl);
+ newlen = strlen_url(useurl, !host_changed);
urllen = strlen(url_clone);
@@ -1614,7 +1716,7 @@ static char *concat_url(const char *base, const char *relurl)
newest[urllen++]='/';
/* then append the new piece on the right side */
- strcpy_url(&newest[urllen], useurl);
+ strcpy_url(&newest[urllen], useurl, !host_changed);
free(url_clone);
@@ -1673,7 +1775,7 @@ CURLcode Curl_follow(struct Curl_easy *data,
}
}
- if(!is_absolute_url(newurl)) {
+ if(!is_absolute_url(newurl)) {
/***
*DANG* this is an RFC 2068 violation. The URL is supposed
to be absolute and this doesn't seem to be that!
@@ -1687,15 +1789,16 @@ CURLcode Curl_follow(struct Curl_easy *data,
/* The new URL MAY contain space or high byte values, that means a mighty
stupid redirect URL but we still make an effort to do "right". */
char *newest;
- size_t newlen = strlen_url(newurl);
+ size_t newlen = strlen_url(newurl, FALSE);
/* This is an absolute URL, don't allow the custom port number */
disallowport = TRUE;
- newest = malloc(newlen+1); /* get memory for this */
+ newest = malloc(newlen + 1); /* get memory for this */
if(!newest)
return CURLE_OUT_OF_MEMORY;
- strcpy_url(newest, newurl); /* create a space-free URL */
+
+ strcpy_url(newest, newurl, FALSE); /* create a space-free URL */
newurl = newest; /* use this instead now */
}
@@ -1763,7 +1866,8 @@ CURLcode Curl_follow(struct Curl_easy *data,
* can be overridden with CURLOPT_POSTREDIR.
*/
if((data->set.httpreq == HTTPREQ_POST
- || data->set.httpreq == HTTPREQ_POST_FORM)
+ || data->set.httpreq == HTTPREQ_POST_FORM
+ || data->set.httpreq == HTTPREQ_POST_MIME)
&& !(data->set.keep_post & CURL_REDIR_POST_301)) {
infof(data, "Switch from POST to GET\n");
data->set.httpreq = HTTPREQ_GET;
@@ -1787,7 +1891,8 @@ CURLcode Curl_follow(struct Curl_easy *data,
* can be overridden with CURLOPT_POSTREDIR.
*/
if((data->set.httpreq == HTTPREQ_POST
- || data->set.httpreq == HTTPREQ_POST_FORM)
+ || data->set.httpreq == HTTPREQ_POST_FORM
+ || data->set.httpreq == HTTPREQ_POST_MIME)
&& !(data->set.keep_post & CURL_REDIR_POST_302)) {
infof(data, "Switch from POST to GET\n");
data->set.httpreq = HTTPREQ_GET;
@@ -1820,7 +1925,7 @@ CURLcode Curl_follow(struct Curl_easy *data,
break;
}
Curl_pgrsTime(data, TIMER_REDIRECT);
- Curl_pgrsResetTimesSizes(data);
+ Curl_pgrsResetTransferSizes(data);
return CURLE_OK;
#endif /* CURL_DISABLE_HTTP */
diff --git a/Utilities/cmcurl/lib/transfer.h b/Utilities/cmcurl/lib/transfer.h
index 518967260..72526a834 100644
--- a/Utilities/cmcurl/lib/transfer.h
+++ b/Utilities/cmcurl/lib/transfer.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -22,6 +22,9 @@
*
***************************************************************************/
+char *Curl_checkheaders(const struct connectdata *conn,
+ const char *thisheader);
+
void Curl_init_CONNECT(struct Curl_easy *data);
CURLcode Curl_pretransfer(struct Curl_easy *data);
diff --git a/Utilities/cmcurl/lib/url.c b/Utilities/cmcurl/lib/url.c
index 87446dbca..584635bc3 100644
--- a/Utilities/cmcurl/lib/url.c
+++ b/Utilities/cmcurl/lib/url.c
@@ -71,6 +71,7 @@ bool curl_win32_idn_to_ascii(const char *in, char **out);
#include "netrc.h"
#include "formdata.h"
+#include "mime.h"
#include "vtls/vtls.h"
#include "hostip.h"
#include "transfer.h"
@@ -274,6 +275,7 @@ static const struct Curl_handler Curl_handler_dummy = {
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
+ ZERO_NULL, /* connection_check */
0, /* defport */
0, /* protocol */
PROTOPT_NONE /* flags */
@@ -283,7 +285,7 @@ void Curl_freeset(struct Curl_easy *data)
{
/* Free all dynamic strings stored in the data->set substructure. */
enum dupstring i;
- for(i=(enum dupstring)0; i < STRING_LAST; i++) {
+ for(i = (enum dupstring)0; i < STRING_LAST; i++) {
Curl_safefree(data->set.str[i]);
}
@@ -370,7 +372,7 @@ CURLcode Curl_dupset(struct Curl_easy *dst, struct Curl_easy *src)
memset(dst->set.str, 0, STRING_LAST * sizeof(char *));
/* duplicate all strings */
- for(i=(enum dupstring)0; i< STRING_LASTZEROTERMINATED; i++) {
+ for(i = (enum dupstring)0; i< STRING_LASTZEROTERMINATED; i++) {
result = setstropt(&dst->set.str[i], src->set.str[i]);
if(result)
return result;
@@ -478,6 +480,8 @@ CURLcode Curl_close(struct Curl_easy *data)
Curl_http2_cleanup_dependencies(data);
Curl_convert_close(data);
+ Curl_mime_cleanpart(&data->set.mimepost);
+
/* No longer a dirty share, if it exists */
if(data->share) {
Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
@@ -545,6 +549,9 @@ CURLcode Curl_init_userdefined(struct UserDefined *set)
set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
+ /* SOCKS5 proxy auth defaults to username/password + GSS-API */
+ set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI;
+
/* make libcurl quiet by default: */
set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
@@ -664,6 +671,8 @@ CURLcode Curl_open(struct Curl_easy **curl)
result = CURLE_OUT_OF_MEMORY;
}
+ Curl_mime_initpart(&data->set.mimepost, data);
+
data->state.headerbuff = malloc(HEADERSIZE);
if(!data->state.headerbuff) {
DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
@@ -672,7 +681,7 @@ CURLcode Curl_open(struct Curl_easy **curl)
else {
result = Curl_init_userdefined(&data->set);
- data->state.headersize=HEADERSIZE;
+ data->state.headersize = HEADERSIZE;
Curl_convert_init(data);
@@ -829,6 +838,10 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
then this can be changed to HEAD later on) */
data->set.httpreq = HTTPREQ_GET;
break;
+ case CURLOPT_REQUEST_TARGET:
+ result = setstropt(&data->set.str[STRING_TARGET],
+ va_arg(param, char *));
+ break;
case CURLOPT_FILETIME:
/*
* Try to get the file time of the remote document. The time will
@@ -1139,6 +1152,20 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
data->set.httpreq = HTTPREQ_POST_FORM;
data->set.opt_no_body = FALSE; /* this is implied */
break;
+#endif /* CURL_DISABLE_HTTP */
+
+ case CURLOPT_MIMEPOST:
+ /*
+ * Set to make us do MIME/form POST
+ */
+ result = curl_mime_subparts(&data->set.mimepost,
+ va_arg(param, curl_mime *));
+ if(!result) {
+ data->set.mimepost.freefunc = NULL; /* Avoid free upon easy cleanup. */
+ data->set.httpreq = HTTPREQ_POST_MIME;
+ data->set.opt_no_body = FALSE; /* this is implied */
+ }
+ break;
case CURLOPT_REFERER:
/*
@@ -1168,6 +1195,7 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
data->set.headers = va_arg(param, struct curl_slist *);
break;
+#ifndef CURL_DISABLE_HTTP
case CURLOPT_PROXYHEADER:
/*
* Set a list with proxy headers to use (or replace internals with)
@@ -1319,7 +1347,7 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
}
break;
-#endif /* CURL_DISABLE_COOKIES */
+#endif /* !CURL_DISABLE_COOKIES */
case CURLOPT_HTTPGET:
/*
@@ -1345,6 +1373,16 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
data->set.httpversion = arg;
break;
+ case CURLOPT_EXPECT_100_TIMEOUT_MS:
+ /*
+ * Time to wait for a response to a HTTP request containing an
+ * Expect: 100-continue header before sending the data anyway.
+ */
+ data->set.expect_100_timeout = va_arg(param, long);
+ break;
+
+#endif /* CURL_DISABLE_HTTP */
+
case CURLOPT_HTTPAUTH:
/*
* Set HTTP Authentication type BITMASK.
@@ -1396,16 +1434,6 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
}
break;
- case CURLOPT_EXPECT_100_TIMEOUT_MS:
- /*
- * Time to wait for a response to a HTTP request containing an
- * Expect: 100-continue header before sending the data anyway.
- */
- data->set.expect_100_timeout = va_arg(param, long);
- break;
-
-#endif /* CURL_DISABLE_HTTP */
-
case CURLOPT_CUSTOMREQUEST:
/*
* Set a custom string to use as request
@@ -1537,6 +1565,11 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
break;
#endif /* CURL_DISABLE_PROXY */
+ case CURLOPT_SOCKS5_AUTH:
+ data->set.socks5auth = va_arg(param, unsigned long);
+ if(data->set.socks5auth & ~(CURLAUTH_BASIC | CURLAUTH_GSSAPI))
+ result = CURLE_NOT_BUILT_IN;
+ break;
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
case CURLOPT_SOCKS5_GSSAPI_NEC:
/*
@@ -1646,28 +1679,28 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
* The low speed limit that if transfers are below this for
* CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
*/
- data->set.low_speed_limit=va_arg(param, long);
+ data->set.low_speed_limit = va_arg(param, long);
break;
case CURLOPT_MAX_SEND_SPEED_LARGE:
/*
* When transfer uploads are faster then CURLOPT_MAX_SEND_SPEED_LARGE
* bytes per second the transfer is throttled..
*/
- data->set.max_send_speed=va_arg(param, curl_off_t);
+ data->set.max_send_speed = va_arg(param, curl_off_t);
break;
case CURLOPT_MAX_RECV_SPEED_LARGE:
/*
* When receiving data faster than CURLOPT_MAX_RECV_SPEED_LARGE bytes per
* second the transfer is throttled..
*/
- data->set.max_recv_speed=va_arg(param, curl_off_t);
+ data->set.max_recv_speed = va_arg(param, curl_off_t);
break;
case CURLOPT_LOW_SPEED_TIME:
/*
* The low speed time that if transfers are below the set
* CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted.
*/
- data->set.low_speed_time=va_arg(param, long);
+ data->set.low_speed_time = va_arg(param, long);
break;
case CURLOPT_URL:
/*
@@ -1862,13 +1895,13 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
break;
case CURLOPT_RESUME_FROM:
/*
- * Resume transfer at the give file position
+ * Resume transfer at the given file position
*/
data->set.set_resume_from = va_arg(param, long);
break;
case CURLOPT_RESUME_FROM_LARGE:
/*
- * Resume transfer at the give file position
+ * Resume transfer at the given file position
*/
data->set.set_resume_from = va_arg(param, curl_off_t);
break;
@@ -2166,24 +2199,26 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
TRUE : FALSE;
break;
case CURLOPT_SSL_CTX_FUNCTION:
-#ifdef have_curlssl_ssl_ctx
/*
* Set a SSL_CTX callback
*/
- data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
-#else
- result = CURLE_NOT_BUILT_IN;
+#ifdef USE_SSL
+ if(Curl_ssl->have_ssl_ctx)
+ data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
+ else
#endif
+ result = CURLE_NOT_BUILT_IN;
break;
case CURLOPT_SSL_CTX_DATA:
-#ifdef have_curlssl_ssl_ctx
/*
* Set a SSL_CTX callback parameter pointer
*/
- data->set.ssl.fsslctxp = va_arg(param, void *);
-#else
- result = CURLE_NOT_BUILT_IN;
+#ifdef USE_SSL
+ if(Curl_ssl->have_ssl_ctx)
+ data->set.ssl.fsslctxp = va_arg(param, void *);
+ else
#endif
+ result = CURLE_NOT_BUILT_IN;
break;
case CURLOPT_SSL_FALSESTART:
/*
@@ -2197,35 +2232,38 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
data->set.ssl.falsestart = (0 != va_arg(param, long)) ? TRUE : FALSE;
break;
case CURLOPT_CERTINFO:
-#ifdef have_curlssl_certinfo
- data->set.ssl.certinfo = (0 != va_arg(param, long)) ? TRUE : FALSE;
-#else
- result = CURLE_NOT_BUILT_IN;
+#ifdef USE_SSL
+ if(Curl_ssl->have_certinfo)
+ data->set.ssl.certinfo = (0 != va_arg(param, long)) ? TRUE : FALSE;
+ else
#endif
+ result = CURLE_NOT_BUILT_IN;
break;
case CURLOPT_PINNEDPUBLICKEY:
-#ifdef have_curlssl_pinnedpubkey /* only by supported backends */
/*
* Set pinned public key for SSL connection.
* Specify file name of the public key in DER format.
*/
- result = setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG],
- va_arg(param, char *));
-#else
- result = CURLE_NOT_BUILT_IN;
+#ifdef USE_SSL
+ if(Curl_ssl->have_pinnedpubkey)
+ result = setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG],
+ va_arg(param, char *));
+ else
#endif
+ result = CURLE_NOT_BUILT_IN;
break;
case CURLOPT_PROXY_PINNEDPUBLICKEY:
-#ifdef have_curlssl_pinnedpubkey /* only by supported backends */
/*
* Set pinned public key for SSL connection.
* Specify file name of the public key in DER format.
*/
- result = setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY],
- va_arg(param, char *));
-#else
- result = CURLE_NOT_BUILT_IN;
+#ifdef USE_SSL
+ if(Curl_ssl->have_pinnedpubkey)
+ result = setstropt(&data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY],
+ va_arg(param, char *));
+ else
#endif
+ result = CURLE_NOT_BUILT_IN;
break;
case CURLOPT_CAINFO:
/*
@@ -2243,30 +2281,32 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
va_arg(param, char *));
break;
case CURLOPT_CAPATH:
-#ifdef have_curlssl_ca_path /* not supported by all backends */
/*
* Set CA path info for SSL connection. Specify directory name of the CA
* certificates which have been prepared using openssl c_rehash utility.
*/
- /* This does not work on windows. */
- result = setstropt(&data->set.str[STRING_SSL_CAPATH_ORIG],
- va_arg(param, char *));
-#else
- result = CURLE_NOT_BUILT_IN;
+#ifdef USE_SSL
+ if(Curl_ssl->have_ca_path)
+ /* This does not work on windows. */
+ result = setstropt(&data->set.str[STRING_SSL_CAPATH_ORIG],
+ va_arg(param, char *));
+ else
#endif
+ result = CURLE_NOT_BUILT_IN;
break;
case CURLOPT_PROXY_CAPATH:
-#ifdef have_curlssl_ca_path /* not supported by all backends */
/*
* Set CA path info for SSL connection proxy. Specify directory name of the
* CA certificates which have been prepared using openssl c_rehash utility.
*/
- /* This does not work on windows. */
- result = setstropt(&data->set.str[STRING_SSL_CAPATH_PROXY],
- va_arg(param, char *));
-#else
- result = CURLE_NOT_BUILT_IN;
+#ifdef USE_SSL
+ if(Curl_ssl->have_ca_path)
+ /* This does not work on windows. */
+ result = setstropt(&data->set.str[STRING_SSL_CAPATH_PROXY],
+ va_arg(param, char *));
+ else
#endif
+ result = CURLE_NOT_BUILT_IN;
break;
case CURLOPT_CRLFILE:
/*
@@ -2897,7 +2937,7 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
return CURLE_NOT_BUILT_IN;
#else
arg = va_arg(param, long);
- if((arg>=1) && (arg <= 256))
+ if((arg >= 1) && (arg <= 256))
data->set.stream_weight = (int)arg;
break;
#endif
@@ -2923,6 +2963,9 @@ CURLcode Curl_setopt(struct Curl_easy *data, CURLoption option,
case CURLOPT_SUPPRESS_CONNECT_HEADERS:
data->set.suppress_connect_headers = (0 != va_arg(param, long))?TRUE:FALSE;
break;
+ case CURLOPT_SSH_COMPRESSION:
+ data->set.ssh_compression = (0 != va_arg(param, long))?TRUE:FALSE;
+ break;
default:
/* unknown tag and its companion, just ignore: */
result = CURLE_UNKNOWN_OPTION;
@@ -3023,7 +3066,7 @@ static void conn_free(struct connectdata *conn)
Curl_safefree(conn->http_proxy.host.rawalloc); /* http proxy name buffer */
Curl_safefree(conn->socks_proxy.host.rawalloc); /* socks proxy name buffer */
Curl_safefree(conn->master_buffer);
- Curl_safefree(conn->connect_buffer);
+ Curl_safefree(conn->connect_state);
conn_reset_all_postponed_data(conn);
@@ -3260,9 +3303,9 @@ Curl_oldest_idle_connection(struct Curl_easy *data)
struct curl_hash_iterator iter;
struct curl_llist_element *curr;
struct curl_hash_element *he;
- time_t highscore=-1;
+ time_t highscore =- 1;
time_t score;
- struct timeval now;
+ struct curltime now;
struct connectdata *conn_candidate = NULL;
struct connectbundle *bundle;
@@ -3323,9 +3366,9 @@ find_oldest_idle_connection_in_bundle(struct Curl_easy *data,
struct connectbundle *bundle)
{
struct curl_llist_element *curr;
- time_t highscore=-1;
+ time_t highscore = -1;
time_t score;
- struct timeval now;
+ struct curltime now;
struct connectdata *conn_candidate = NULL;
struct connectdata *conn;
@@ -3367,11 +3410,19 @@ static bool disconnect_if_dead(struct connectdata *conn,
handles in pipeline and the connection isn't already marked in
use */
bool dead;
- if(conn->handler->protocol & CURLPROTO_RTSP)
- /* RTSP is a special case due to RTP interleaving */
- dead = Curl_rtsp_connisdead(conn);
- else
+
+ if(conn->handler->connection_check) {
+ /* The protocol has a special method for checking the state of the
+ connection. Use it to check if the connection is dead. */
+ unsigned int state;
+
+ state = conn->handler->connection_check(conn, CONNCHECK_ISDEAD);
+ dead = (state & CONNRESULT_DEAD);
+ }
+ else {
+ /* Use the general method for determining the death of a connection */
dead = SocketIsDead(conn->sock[FIRSTSOCKET]);
+ }
if(dead) {
conn->data = data;
@@ -3405,7 +3456,7 @@ static int call_disconnect_if_dead(struct connectdata *conn,
*/
static void prune_dead_connections(struct Curl_easy *data)
{
- struct timeval now = Curl_tvnow();
+ struct curltime now = Curl_tvnow();
time_t elapsed = Curl_tvdiff(now, data->state.conn_cache->last_cleanup);
if(elapsed >= 1000L) {
@@ -3946,7 +3997,7 @@ int Curl_doing_getsock(struct connectdata *conn,
CURLcode Curl_protocol_connecting(struct connectdata *conn,
bool *done)
{
- CURLcode result=CURLE_OK;
+ CURLcode result = CURLE_OK;
if(conn && conn->handler->connecting) {
*done = FALSE;
@@ -3965,7 +4016,7 @@ CURLcode Curl_protocol_connecting(struct connectdata *conn,
CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
{
- CURLcode result=CURLE_OK;
+ CURLcode result = CURLE_OK;
if(conn && conn->handler->doing) {
*done = FALSE;
@@ -3985,7 +4036,7 @@ CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
CURLcode Curl_protocol_connect(struct connectdata *conn,
bool *protocol_done)
{
- CURLcode result=CURLE_OK;
+ CURLcode result = CURLE_OK;
*protocol_done = FALSE;
@@ -4013,7 +4064,7 @@ CURLcode Curl_protocol_connect(struct connectdata *conn,
return CURLE_OK;
if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
- (conn->tunnel_state[FIRSTSOCKET] != TUNNEL_COMPLETE))
+ Curl_connect_ongoing(conn))
/* when using an HTTP tunnel proxy, await complete tunnel establishment
before proceeding further. Return CURLE_OK so we'll be called again */
return CURLE_OK;
@@ -4072,7 +4123,7 @@ static void fix_hostname(struct connectdata *conn, struct hostname *host)
if(len && (host->name[len-1] == '.'))
/* strip off a single trailing dot if present, primarily for SNI but
there's no use for it */
- host->name[len-1]=0;
+ host->name[len-1] = 0;
/* Check name for non-ASCII and convert hostname to ACE form if we can */
if(!is_ASCII_name(host->name)) {
@@ -4125,7 +4176,7 @@ static void free_fixed_hostname(struct hostname *host)
host->encalloc = NULL;
}
#elif defined(USE_WIN32_IDN)
- free(host->encalloc); /* must be freed withidn_free() since this was
+ free(host->encalloc); /* must be freed with free() since this was
allocated by curl_win32_idn_to_ascii */
host->encalloc = NULL;
#else
@@ -4145,7 +4196,12 @@ static void llist_dtor(void *user, void *element)
*/
static struct connectdata *allocate_conn(struct Curl_easy *data)
{
- struct connectdata *conn = calloc(1, sizeof(struct connectdata));
+#ifdef USE_SSL
+#define SSL_EXTRA + 4 * Curl_ssl->sizeof_ssl_backend_data - sizeof(long long)
+#else
+#define SSL_EXTRA 0
+#endif
+ struct connectdata *conn = calloc(1, sizeof(struct connectdata) + SSL_EXTRA);
if(!conn)
return NULL;
@@ -4228,6 +4284,23 @@ static struct connectdata *allocate_conn(struct Curl_easy *data)
conn->ip_version = data->set.ipver;
+#ifdef USE_SSL
+ /*
+ * To save on malloc()s, the SSL backend-specific data has been allocated
+ * at the end of the connectdata struct.
+ */
+ {
+ char *p = (char *)&conn->align_data__do_not_use;
+ conn->ssl[0].backend = (struct ssl_backend_data *)p;
+ conn->ssl[1].backend =
+ (struct ssl_backend_data *)(p + Curl_ssl->sizeof_ssl_backend_data);
+ conn->proxy_ssl[0].backend =
+ (struct ssl_backend_data *)(p + Curl_ssl->sizeof_ssl_backend_data * 2);
+ conn->proxy_ssl[1].backend =
+ (struct ssl_backend_data *)(p + Curl_ssl->sizeof_ssl_backend_data * 3);
+ }
+#endif
+
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
defined(NTLM_WB_ENABLED)
conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
@@ -4363,11 +4436,16 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
return CURLE_URL_MALFORMAT;
}
- /* Make sure we don't mistake a drive letter for a scheme, for example:
+ /* MSDOS/Windows style drive prefix, eg c: in c:foo */
+#define STARTS_WITH_DRIVE_PREFIX(str) \
+ ((('a' <= str[0] && str[0] <= 'z') || \
+ ('A' <= str[0] && str[0] <= 'Z')) && \
+ (str[1] == ':'))
+
+ /* Don't mistake a drive letter for a scheme if the default protocol is file.
curld --proto-default file c:/foo/bar.txt */
- if((('a' <= data->change.url[0] && data->change.url[0] <= 'z') ||
- ('A' <= data->change.url[0] && data->change.url[0] <= 'Z')) &&
- data->change.url[1] == ':' && data->set.str[STRING_DEFAULT_PROTOCOL] &&
+ if(STARTS_WITH_DRIVE_PREFIX(data->change.url) &&
+ data->set.str[STRING_DEFAULT_PROTOCOL] &&
strcasecompare(data->set.str[STRING_DEFAULT_PROTOCOL], "file")) {
; /* do nothing */
}
@@ -4386,8 +4464,6 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
if((url_has_scheme && strncasecompare(data->change.url, "file:", 5)) ||
(!url_has_scheme && data->set.str[STRING_DEFAULT_PROTOCOL] &&
strcasecompare(data->set.str[STRING_DEFAULT_PROTOCOL], "file"))) {
- bool path_has_drive = FALSE;
-
if(url_has_scheme)
rc = sscanf(data->change.url, "%*15[^\n/:]:%[^\n]", path);
else
@@ -4406,20 +4482,15 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
/* This cannot be done with strcpy() in a portable manner, since the
memory areas overlap! */
- memmove(path, path + 2, strlen(path + 2)+1);
+ memmove(path, path + 2, strlen(path + 2) + 1);
}
- /* the path may start with a drive letter. for backwards compatibility
- we skip some processing on those paths. */
- path_has_drive = (('a' <= path[0] && path[0] <= 'z') ||
- ('A' <= path[0] && path[0] <= 'Z')) && path[1] == ':';
-
/*
* we deal with file://<host>/<path> differently since it supports no
* hostname other than "localhost" and "127.0.0.1", which is unique among
* the URL protocols specified in RFC 1738
*/
- if(path[0] != '/' && !path_has_drive) {
+ if(path[0] != '/' && !STARTS_WITH_DRIVE_PREFIX(path)) {
/* the URL includes a host name, it must match "localhost" or
"127.0.0.1" to be valid */
char *ptr;
@@ -4452,14 +4523,11 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
ptr++;
/* This cannot be made with strcpy, as the memory chunks overlap! */
- memmove(path, ptr, strlen(ptr)+1);
-
- path_has_drive = (('a' <= path[0] && path[0] <= 'z') ||
- ('A' <= path[0] && path[0] <= 'Z')) && path[1] == ':';
+ memmove(path, ptr, strlen(ptr) + 1);
}
#if !defined(MSDOS) && !defined(WIN32) && !defined(__CYGWIN__)
- if(path_has_drive) {
+ if(STARTS_WITH_DRIVE_PREFIX(path)) {
failf(data, "File drive letters are only accepted in MSDOS/Windows.");
return CURLE_URL_MALFORMAT;
}
@@ -4471,7 +4539,7 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
else {
/* clear path */
char slashbuf[4];
- path[0]=0;
+ path[0] = 0;
rc = sscanf(data->change.url,
"%15[^\n/:]:%3[/]%[^\n/?#]%[^\n]",
@@ -4556,7 +4624,7 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
*/
at = strchr(conn->host.name, '@');
if(at)
- query = strchr(at+1, '?');
+ query = strchr(at + 1, '?');
else
query = strchr(conn->host.name, '?');
@@ -4574,15 +4642,15 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
/* move the existing path plus the zero byte forward, to make room for
the host-name part */
- memmove(path+hostlen+1, path, pathlen+1);
+ memmove(path + hostlen + 1, path, pathlen + 1);
/* now copy the trailing host part in front of the existing path */
- memcpy(path+1, query, hostlen);
+ memcpy(path + 1, query, hostlen);
path[0]='/'; /* prepend the missing slash */
rebuild_url = TRUE;
- *query=0; /* now cut off the hostname at the ? */
+ *query = 0; /* now cut off the hostname at the ? */
}
else if(!path[0]) {
/* if there's no path set, use a single slash */
@@ -4598,7 +4666,7 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
/* We need this function to deal with overlapping memory areas. We know
that the memory area 'path' points to is 'urllen' bytes big and that
is bigger than the path. Use +1 to move the zero byte too. */
- memmove(&path[1], path, strlen(path)+1);
+ memmove(&path[1], path, strlen(path) + 1);
path[0] = '/';
rebuild_url = TRUE;
}
@@ -4704,7 +4772,7 @@ static CURLcode parseurlandfillconn(struct Curl_easy *data,
if(*endp == ']') {
/* The address scope was well formed. Knock it out of the
hostname. */
- memmove(percent, endp, strlen(endp)+1);
+ memmove(percent, endp, strlen(endp) + 1);
conn->scope_id = (unsigned int)scope;
}
else {
@@ -4974,7 +5042,7 @@ static char *detect_proxy(struct connectdata *conn)
strcpy(envp, "_proxy");
/* read the protocol proxy: */
- prox=curl_getenv(proxy_env);
+ prox = curl_getenv(proxy_env);
/*
* We don't try the uppercase version of HTTP_PROXY because of
@@ -4991,7 +5059,7 @@ static char *detect_proxy(struct connectdata *conn)
if(!prox && !strcasecompare("http_proxy", proxy_env)) {
/* There was no lowercase variable, try the uppercase version: */
Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
- prox=curl_getenv(proxy_env);
+ prox = curl_getenv(proxy_env);
}
if(prox)
@@ -4999,7 +5067,7 @@ static char *detect_proxy(struct connectdata *conn)
else {
proxy = curl_getenv("all_proxy"); /* default proxy to use */
if(!proxy)
- proxy=curl_getenv("ALL_PROXY");
+ proxy = curl_getenv("ALL_PROXY");
}
return proxy;
@@ -5034,7 +5102,7 @@ static CURLcode parse_proxy(struct Curl_easy *data,
/* Parse the protocol part if present */
endofprot = strstr(proxy, "://");
if(endofprot) {
- proxyptr = endofprot+3;
+ proxyptr = endofprot + 3;
if(checkprefix("https", proxy))
proxytype = CURLPROXY_HTTPS;
else if(checkprefix("socks5h", proxy))
@@ -5056,13 +5124,14 @@ static CURLcode parse_proxy(struct Curl_easy *data,
else
proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
-#ifndef HTTPS_PROXY_SUPPORT
- if(proxytype == CURLPROXY_HTTPS) {
- failf(data, "Unsupported proxy \'%s\'"
- ", libcurl is built without the HTTPS-proxy support.", proxy);
- return CURLE_NOT_BUILT_IN;
- }
+#ifdef USE_SSL
+ if(!Curl_ssl->support_https_proxy)
#endif
+ if(proxytype == CURLPROXY_HTTPS) {
+ failf(data, "Unsupported proxy \'%s\', libcurl is built without the "
+ "HTTPS-proxy support.", proxy);
+ return CURLE_NOT_BUILT_IN;
+ }
sockstype = proxytype == CURLPROXY_SOCKS5_HOSTNAME ||
proxytype == CURLPROXY_SOCKS5 ||
@@ -5133,11 +5202,14 @@ static CURLcode parse_proxy(struct Curl_easy *data,
conn->port = port;
}
else {
- if(proxyptr[0]=='/')
+ if(proxyptr[0]=='/') {
/* If the first character in the proxy string is a slash, fail
immediately. The following code will otherwise clear the string which
will lead to code running as if no proxy was set! */
+ Curl_safefree(proxyuser);
+ Curl_safefree(proxypasswd);
return CURLE_COULDNT_RESOLVE_PROXY;
+ }
/* without a port number after the host name, some people seem to use
a slash so we strip everything from the first slash */
@@ -5280,22 +5352,21 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
}
}
- no_proxy = curl_getenv("no_proxy");
- if(!no_proxy)
- no_proxy = curl_getenv("NO_PROXY");
+ if(!data->set.str[STRING_NOPROXY]) {
+ no_proxy = curl_getenv("no_proxy");
+ if(!no_proxy)
+ no_proxy = curl_getenv("NO_PROXY");
+ }
- if(check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY]) ||
- (!data->set.str[STRING_NOPROXY] &&
- check_noproxy(conn->host.name, no_proxy))) {
+ if(check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY] ?
+ data->set.str[STRING_NOPROXY] : no_proxy)) {
Curl_safefree(proxy);
Curl_safefree(socksproxy);
}
- else if(!proxy && !socksproxy)
#ifndef CURL_DISABLE_HTTP
+ else if(!proxy && !socksproxy)
/* if the host is not in the noproxy list, detect proxy. */
proxy = detect_proxy(conn);
-#else /* !CURL_DISABLE_HTTP */
- proxy = NULL;
#endif /* CURL_DISABLE_HTTP */
Curl_safefree(no_proxy);
@@ -5348,12 +5419,15 @@ static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
result = CURLE_UNSUPPORTED_PROTOCOL;
goto out;
#else
- /* force this connection's protocol to become HTTP if not already
- compatible - if it isn't tunneling through */
- if(!(conn->handler->protocol & PROTO_FAMILY_HTTP) &&
- !conn->bits.tunnel_proxy)
- conn->handler = &Curl_handler_http;
-
+ /* force this connection's protocol to become HTTP if compatible */
+ if(!(conn->handler->protocol & PROTO_FAMILY_HTTP)) {
+ if((conn->handler->flags & PROTOPT_PROXY_AS_HTTP) &&
+ !conn->bits.tunnel_proxy)
+ conn->handler = &Curl_handler_http;
+ else
+ /* if not converting to HTTP over the proxy, enforce tunneling */
+ conn->bits.tunnel_proxy = TRUE;
+ }
conn->bits.httpproxy = TRUE;
#endif
}
@@ -5740,7 +5814,7 @@ static CURLcode parse_remote_port(struct Curl_easy *data,
char *rest;
long port;
- port=strtol(portptr+1, &rest, 10); /* Port number must be decimal */
+ port = strtol(portptr + 1, &rest, 10); /* Port number must be decimal */
if((port < 0) || (port > 0xffff)) {
/* Single unix standard says port numbers are 16 bits long */
@@ -6096,7 +6170,7 @@ static CURLcode resolve_server(struct Curl_easy *data,
struct connectdata *conn,
bool *async)
{
- CURLcode result=CURLE_OK;
+ CURLcode result = CURLE_OK;
time_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
/*************************************************************
@@ -6259,11 +6333,10 @@ static void reuse_conn(struct connectdata *old_conn,
free_fixed_hostname(&conn->conn_to_host);
Curl_safefree(conn->host.rawalloc);
Curl_safefree(conn->conn_to_host.rawalloc);
- conn->host=old_conn->host;
- conn->bits.conn_to_host = old_conn->bits.conn_to_host;
+ conn->host = old_conn->host;
conn->conn_to_host = old_conn->conn_to_host;
- conn->bits.conn_to_port = old_conn->bits.conn_to_port;
conn->conn_to_port = old_conn->conn_to_port;
+ conn->remote_port = old_conn->remote_port;
/* persist connection info in session handle */
Curl_persistconninfo(conn);
@@ -6362,9 +6435,9 @@ static CURLcode create_conn(struct Curl_easy *data,
* other parts of the code will rely on this fact
***********************************************************/
#define LEAST_PATH_ALLOC 256
- urllen=strlen(data->change.url);
+ urllen = strlen(data->change.url);
if(urllen < LEAST_PATH_ALLOC)
- urllen=LEAST_PATH_ALLOC;
+ urllen = LEAST_PATH_ALLOC;
/*
* We malloc() the buffers below urllen+2 to make room for 2 possibilities:
@@ -6375,14 +6448,14 @@ static CURLcode create_conn(struct Curl_easy *data,
Curl_safefree(data->state.pathbuffer);
data->state.path = NULL;
- data->state.pathbuffer = malloc(urllen+2);
+ data->state.pathbuffer = malloc(urllen + 2);
if(NULL == data->state.pathbuffer) {
result = CURLE_OUT_OF_MEMORY; /* really bad error */
goto out;
}
data->state.path = data->state.pathbuffer;
- conn->host.rawalloc = malloc(urllen+2);
+ conn->host.rawalloc = malloc(urllen + 2);
if(NULL == conn->host.rawalloc) {
Curl_safefree(data->state.pathbuffer);
data->state.path = NULL;
@@ -7015,7 +7088,7 @@ CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn)
k->buf = data->state.buffer;
k->hbufp = data->state.headerbuff;
- k->ignorebody=FALSE;
+ k->ignorebody = FALSE;
Curl_speedinit(data);
diff --git a/Utilities/cmcurl/lib/urldata.h b/Utilities/cmcurl/lib/urldata.h
index d4a4a98dc..66e4596fd 100644
--- a/Utilities/cmcurl/lib/urldata.h
+++ b/Utilities/cmcurl/lib/urldata.h
@@ -82,75 +82,6 @@
#include "cookie.h"
#include "formdata.h"
-#ifdef USE_OPENSSL
-#include <openssl/ssl.h>
-#ifdef HAVE_OPENSSL_ENGINE_H
-#include <openssl/engine.h>
-#endif
-#endif /* USE_OPENSSL */
-
-#ifdef USE_GNUTLS
-#include <gnutls/gnutls.h>
-#endif
-
-#ifdef USE_MBEDTLS
-
-#include <mbedtls/ssl.h>
-#include <mbedtls/version.h>
-#include <mbedtls/entropy.h>
-#include <mbedtls/ctr_drbg.h>
-
-#elif defined USE_POLARSSL
-
-#include <polarssl/ssl.h>
-#include <polarssl/version.h>
-#if POLARSSL_VERSION_NUMBER<0x01010000
-#include <polarssl/havege.h>
-#else
-#include <polarssl/entropy.h>
-#include <polarssl/ctr_drbg.h>
-#endif /* POLARSSL_VERSION_NUMBER<0x01010000 */
-
-#endif /* USE_POLARSSL */
-
-#ifdef USE_CYASSL
-#undef OCSP_REQUEST /* avoid cyassl/openssl/ssl.h clash with wincrypt.h */
-#undef OCSP_RESPONSE /* avoid cyassl/openssl/ssl.h clash with wincrypt.h */
-#include <cyassl/openssl/ssl.h>
-#endif
-
-#ifdef USE_NSS
-#include <nspr.h>
-#include <pk11pub.h>
-#endif
-
-#ifdef USE_GSKIT
-#include <gskssl.h>
-#endif
-
-#ifdef USE_AXTLS
-#include <axTLS/config.h>
-#include <axTLS/ssl.h>
-#undef malloc
-#undef calloc
-#undef realloc
-#endif /* USE_AXTLS */
-
-#if defined(USE_SCHANNEL) || defined(USE_WINDOWS_SSPI)
-#include "curl_sspi.h"
-#endif
-#ifdef USE_SCHANNEL
-#include <schnlsp.h>
-#include <schannel.h>
-#endif
-
-#ifdef USE_DARWINSSL
-#include <Security/Security.h>
-/* For some reason, when building for iOS, the omnibus header above does
- * not include SecureTransport.h as of iOS SDK 5.1. */
-#include <Security/SecureTransport.h>
-#endif
-
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
@@ -172,6 +103,7 @@
#include "hash.h"
#include "splay.h"
+#include "mime.h"
#include "imap.h"
#include "pop3.h"
#include "smtp.h"
@@ -240,20 +172,6 @@ enum protection_level {
};
#endif
-#ifdef USE_SCHANNEL
-/* Structs to store Schannel handles */
-struct curl_schannel_cred {
- CredHandle cred_handle;
- TimeStamp time_stamp;
- int refcount;
-};
-
-struct curl_schannel_ctxt {
- CtxtHandle ctxt_handle;
- TimeStamp time_stamp;
-};
-#endif
-
/* enum for the nonblocking SSL connection state machine */
typedef enum {
ssl_connect_1,
@@ -270,6 +188,9 @@ typedef enum {
ssl_connection_complete
} ssl_connection_state;
+/* SSL backend-specific data; declared differently by each SSL backend */
+struct ssl_backend_data;
+
/* struct for data related to each SSL connection */
struct ssl_connect_data {
/* Use ssl encrypted communications TRUE/FALSE, not necessarily using it atm
@@ -278,78 +199,8 @@ struct ssl_connect_data {
bool use;
ssl_connection_state state;
ssl_connect_state connecting_state;
-#if defined(USE_OPENSSL)
- /* these ones requires specific SSL-types */
- SSL_CTX* ctx;
- SSL* handle;
- X509* server_cert;
-#elif defined(USE_GNUTLS)
- gnutls_session_t session;
- gnutls_certificate_credentials_t cred;
-#ifdef USE_TLS_SRP
- gnutls_srp_client_credentials_t srp_client_cred;
-#endif
-#elif defined(USE_MBEDTLS)
- mbedtls_ctr_drbg_context ctr_drbg;
- mbedtls_entropy_context entropy;
- mbedtls_ssl_context ssl;
- int server_fd;
- mbedtls_x509_crt cacert;
- mbedtls_x509_crt clicert;
- mbedtls_x509_crl crl;
- mbedtls_pk_context pk;
- mbedtls_ssl_config config;
- const char *protocols[3];
-#elif defined(USE_POLARSSL)
- ctr_drbg_context ctr_drbg;
- entropy_context entropy;
- ssl_context ssl;
- int server_fd;
- x509_crt cacert;
- x509_crt clicert;
- x509_crl crl;
- rsa_context rsa;
-#elif defined(USE_CYASSL)
- SSL_CTX* ctx;
- SSL* handle;
-#elif defined(USE_NSS)
- PRFileDesc *handle;
- char *client_nickname;
- struct Curl_easy *data;
- struct curl_llist obj_list;
- PK11GenericObject *obj_clicert;
-#elif defined(USE_GSKIT)
- gsk_handle handle;
- int iocport;
- int localfd;
- int remotefd;
-#elif defined(USE_AXTLS)
- SSL_CTX* ssl_ctx;
- SSL* ssl;
-#elif defined(USE_SCHANNEL)
- struct curl_schannel_cred *cred;
- struct curl_schannel_ctxt *ctxt;
- SecPkgContext_StreamSizes stream_sizes;
- size_t encdata_length, decdata_length;
- size_t encdata_offset, decdata_offset;
- unsigned char *encdata_buffer, *decdata_buffer;
- /* encdata_is_incomplete: if encdata contains only a partial record that
- can't be decrypted without another Curl_read_plain (that is, status is
- SEC_E_INCOMPLETE_MESSAGE) then set this true. after Curl_read_plain writes
- more bytes into encdata then set this back to false. */
- bool encdata_is_incomplete;
- unsigned long req_flags, ret_flags;
- CURLcode recv_unrecoverable_err; /* schannel_recv had an unrecoverable err */
- bool recv_sspi_close_notify; /* true if connection closed by close_notify */
- bool recv_connection_closed; /* true if connection closed, regardless how */
- bool use_alpn; /* true if ALPN is used for this connection */
-#elif defined(USE_DARWINSSL)
- SSLContextRef ssl_ctx;
- curl_socket_t ssl_sockfd;
- bool ssl_direction; /* true if writing, false if reading */
- size_t ssl_write_buffered_length;
-#elif defined(USE_SSL)
-#error "SSL backend specific information missing from ssl_connect_data"
+#if defined(USE_SSL)
+ struct ssl_backend_data *backend;
#endif
};
@@ -359,13 +210,13 @@ struct ssl_primary_config {
bool verifypeer; /* set TRUE if this is desired */
bool verifyhost; /* set TRUE if CN/SAN must match hostname */
bool verifystatus; /* set TRUE if certificate status must be checked */
+ bool sessionid; /* cache session IDs or not */
char *CApath; /* certificate dir (doesn't work on windows) */
char *CAfile; /* certificate to verify peer against */
char *clientcert;
char *random_file; /* path to file containing "random" data */
char *egdsocket; /* path to file containing the EGD daemon socket */
char *cipher_list; /* list of ciphers to use */
- bool sessionid; /* cache session IDs or not */
};
struct ssl_config_data {
@@ -411,12 +262,20 @@ struct curl_ssl_session {
struct ssl_primary_config ssl_config; /* setup for this session */
};
+#ifdef USE_WINDOWS_SSPI
+#include "curl_sspi.h"
+#endif
+
/* Struct used for Digest challenge-response authentication */
struct digestdata {
#if defined(USE_WINDOWS_SSPI)
BYTE *input_token;
size_t input_token_len;
CtxtHandle *http_context;
+ /* copy of user/passwd used to make the identity for http_context.
+ either may be NULL. */
+ char *user;
+ char *passwd;
#else
char *nonce;
char *cnonce;
@@ -438,10 +297,6 @@ typedef enum {
NTLMSTATE_LAST
} curlntlm;
-#ifdef USE_WINDOWS_SSPI
-#include "curl_sspi.h"
-#endif
-
#if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
#include <iconv.h>
#endif
@@ -678,8 +533,8 @@ struct SingleRequest {
100 reply (without a following second response
code) result in a CURLE_GOT_NOTHING error code */
- struct timeval start; /* transfer started at this time */
- struct timeval now; /* current time */
+ struct curltime start; /* transfer started at this time */
+ struct curltime now; /* current time */
bool header; /* incoming data has HTTP header */
enum {
HEADER_NORMAL, /* no bad header at all */
@@ -701,7 +556,7 @@ struct SingleRequest {
Content-Range: header */
int httpcode; /* error code from the 'HTTP/1.? XXX' or
'RTSP/1.? XXX' line */
- struct timeval start100; /* time stamp to wait for the 100 code from */
+ struct curltime start100; /* time stamp to wait for the 100 code from */
enum expect100 exp100; /* expect 100 continue state */
enum upgrade101 upgr101; /* 101 upgrade state */
@@ -829,6 +684,12 @@ struct Curl_handler {
CURLcode (*readwrite)(struct Curl_easy *data, struct connectdata *conn,
ssize_t *nread, bool *readmore);
+ /* This function can perform various checks on the connection. See
+ CONNCHECK_* for more information about the checks that can be performed,
+ and CONNRESULT_* for the results that can be returned. */
+ unsigned int (*connection_check)(struct connectdata *conn,
+ unsigned int checks_to_perform);
+
long defport; /* Default port. */
unsigned int protocol; /* See CURLPROTO_* - this needs to be the single
specific protocol bit */
@@ -855,6 +716,15 @@ struct Curl_handler {
#define PROTOPT_STREAM (1<<9) /* a protocol with individual logical streams */
#define PROTOPT_URLOPTIONS (1<<10) /* allow options part in the userinfo field
of the URL */
+#define PROTOPT_PROXY_AS_HTTP (1<<11) /* allow this non-HTTP scheme over a
+ HTTP proxy as HTTP proxies may know
+ this protocol and act as a gateway */
+
+#define CONNCHECK_NONE 0 /* No checks */
+#define CONNCHECK_ISDEAD (1<<0) /* Check if the connection is dead. */
+
+#define CONNRESULT_NONE 0 /* No extra information. */
+#define CONNRESULT_DEAD (1<<0) /* The connection is dead. */
/* return the count of bytes sent, or -1 on error */
typedef ssize_t (Curl_send)(struct connectdata *conn, /* connection data */
@@ -892,6 +762,24 @@ struct proxy_info {
char *passwd; /* proxy password string, allocated */
};
+#define CONNECT_BUFFER_SIZE 16384
+
+/* struct for HTTP CONNECT state data */
+struct http_connect_state {
+ char connect_buffer[CONNECT_BUFFER_SIZE];
+ int perline; /* count bytes per line */
+ int keepon;
+ char *line_start;
+ char *ptr; /* where to store more data */
+ curl_off_t cl; /* size of content to read and ignore */
+ bool chunked_encoding;
+ enum {
+ TUNNEL_INIT, /* init/default/no tunnel state */
+ TUNNEL_CONNECT, /* CONNECT has been sent off */
+ TUNNEL_COMPLETE /* CONNECT response received completely */
+ } tunnel_state;
+};
+
/*
* The connectdata struct contains all fields and variables that should be
* unique for an entire connection.
@@ -983,8 +871,8 @@ struct connectdata {
int httpversion; /* the HTTP version*10 reported by the server */
int rtspversion; /* the RTSP version*10 reported by the server */
- struct timeval now; /* "current" time */
- struct timeval created; /* creation time */
+ struct curltime now; /* "current" time */
+ struct curltime created; /* creation time */
curl_socket_t sock[2]; /* two sockets, the second is used for the data
transfer when doing FTP */
curl_socket_t tempsock[2]; /* temporary sockets for happy eyeballs */
@@ -1007,7 +895,7 @@ struct connectdata {
/* connecttime: when connect() is called on the current IP address. Used to
be able to track when to move on to try next IP - but only when the multi
interface is used. */
- struct timeval connecttime;
+ struct curltime connecttime;
/* The two fields below get set in Curl_connecthost */
int num_addr; /* number of addresses to try to connect to */
time_t timeoutms_per_addr; /* how long time in milliseconds to spend on
@@ -1134,22 +1022,24 @@ struct connectdata {
char *localdev;
unsigned short localport;
int localportrange;
-
- /* tunnel as in tunnel through a HTTP proxy with CONNECT */
- enum {
- TUNNEL_INIT, /* init/default/no tunnel state */
- TUNNEL_CONNECT, /* CONNECT has been sent off */
- TUNNEL_COMPLETE /* CONNECT response received completely */
- } tunnel_state[2]; /* two separate ones to allow FTP */
+ struct http_connect_state *connect_state; /* for HTTP CONNECT */
struct connectbundle *bundle; /* The bundle we are member of */
-
int negnpn; /* APLN or NPN TLS negotiated protocol, CURL_HTTP_VERSION* */
- char *connect_buffer; /* for CONNECT business */
#ifdef USE_UNIX_SOCKETS
char *unix_domain_socket;
bool abstract_unix_socket;
#endif
+
+#ifdef USE_SSL
+ /*
+ * To avoid multiple malloc() calls, the ssl_connect_data structures
+ * associated with a connectdata struct are allocated in the same block
+ * as the latter. This field forces alignment to an 8-byte boundary so
+ * that this all works.
+ */
+ long long *align_data__do_not_use;
+#endif
};
/* The end of connectdata. */
@@ -1213,34 +1103,36 @@ struct Progress {
int width; /* screen width at download start */
int flags; /* see progress.h */
- double timespent;
+ time_t timespent;
curl_off_t dlspeed;
curl_off_t ulspeed;
- double t_nslookup;
- double t_connect;
- double t_appconnect;
- double t_pretransfer;
- double t_starttransfer;
- double t_redirect;
+ time_t t_nslookup;
+ time_t t_connect;
+ time_t t_appconnect;
+ time_t t_pretransfer;
+ time_t t_starttransfer;
+ time_t t_redirect;
- struct timeval start;
- struct timeval t_startsingle;
- struct timeval t_startop;
- struct timeval t_acceptdata;
+ struct curltime start;
+ struct curltime t_startsingle;
+ struct curltime t_startop;
+ struct curltime t_acceptdata;
+
+ bool is_t_startransfer_set;
/* upload speed limit */
- struct timeval ul_limit_start;
+ struct curltime ul_limit_start;
curl_off_t ul_limit_size;
/* download speed limit */
- struct timeval dl_limit_start;
+ struct curltime dl_limit_start;
curl_off_t dl_limit_size;
-#define CURR_TIME (5+1) /* 6 entries for 5 seconds */
+#define CURR_TIME (5 + 1) /* 6 entries for 5 seconds */
curl_off_t speeder[ CURR_TIME ];
- struct timeval speeder_time[ CURR_TIME ];
+ struct curltime speeder_time[ CURR_TIME ];
int speeder_c;
};
@@ -1249,8 +1141,10 @@ typedef enum {
HTTPREQ_GET,
HTTPREQ_POST,
HTTPREQ_POST_FORM, /* we make a difference internally */
+ HTTPREQ_POST_MIME, /* we make a difference internally */
HTTPREQ_PUT,
HTTPREQ_HEAD,
+ HTTPREQ_OPTIONS,
HTTPREQ_CUSTOM,
HTTPREQ_LAST /* last in list */
} Curl_HttpReq;
@@ -1334,7 +1228,7 @@ typedef enum {
*/
struct time_node {
struct curl_llist_element list;
- struct timeval time;
+ struct curltime time;
expire_id eid;
};
@@ -1349,7 +1243,7 @@ struct UrlState {
bool multi_owned_by_easy;
/* buffers to store authentication data in, as parsed from input options */
- struct timeval keeps_speed; /* for the progress meter really */
+ struct curltime keeps_speed; /* for the progress meter really */
struct connectdata *lastconnect; /* The last connection, NULL if undefined */
@@ -1357,7 +1251,7 @@ struct UrlState {
size_t headersize; /* size of the allocation */
char *buffer; /* download buffer */
- char uploadbuffer[UPLOAD_BUFSIZE+1]; /* upload buffer */
+ char uploadbuffer[UPLOAD_BUFSIZE + 1]; /* upload buffer */
curl_off_t current_speed; /* the ProgressShow() function sets this,
bytes / second */
bool this_is_a_follow; /* this is a followed Location: request */
@@ -1401,9 +1295,10 @@ struct UrlState {
ares_channel f.e. */
#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
- ENGINE *engine;
+ /* void instead of ENGINE to avoid bleeding OpenSSL into this header */
+ void *engine;
#endif /* USE_OPENSSL */
- struct timeval expiretime; /* set this with Curl_expire() only */
+ struct curltime expiretime; /* set this with Curl_expire() only */
struct Curl_tree timenode; /* for the splay stuff */
struct curl_llist timeoutlist; /* list of pending timeouts */
struct time_node expires[EXPIRE_LAST]; /* nodes for each expire type */
@@ -1574,7 +1469,7 @@ enum dupstring {
#ifdef USE_UNIX_SOCKETS
STRING_UNIX_SOCKET_PATH, /* path to Unix socket, if used */
#endif
-
+ STRING_TARGET, /* CURLOPT_REQUEST_TARGET */
/* -- end of zero-terminated strings -- */
STRING_LASTZEROTERMINATED,
@@ -1601,6 +1496,7 @@ struct UserDefined {
long use_port; /* which port to use (when not using default) */
unsigned long httpauth; /* kind of HTTP authentication to use (bitmask) */
unsigned long proxyauth; /* kind of proxy authentication to use (bitmask) */
+ unsigned long socks5auth;/* kind of SOCKS5 authentication to use (bitmask) */
long followlocation; /* as in HTTP Location: */
long maxredirs; /* maximum no. of http(s) redirects to follow, set to -1
for infinity */
@@ -1663,7 +1559,8 @@ struct UserDefined {
curl_off_t set_resume_from; /* continue [ftp] transfer from here */
struct curl_slist *headers; /* linked list of extra headers */
struct curl_slist *proxyheaders; /* linked list of extra CONNECT headers */
- struct curl_httppost *httppost; /* linked list of POST data */
+ struct curl_httppost *httppost; /* linked list of old POST data */
+ curl_mimepart mimepost; /* MIME/POST data. */
bool sep_headers; /* handle host and proxy headers separately */
bool cookiesession; /* new cookie session? */
bool crlf; /* convert crlf on ftp upload(?) */
@@ -1685,6 +1582,7 @@ struct UserDefined {
Curl_HttpReq httpreq; /* what kind of HTTP request (if any) is this */
long httpversion; /* when non-zero, a specific HTTP version requested to
be used in the library's request(s) */
+ bool strip_path_slash; /* strip off initial slash from path */
struct ssl_config_data ssl; /* user defined SSL stuff */
struct ssl_config_data proxy_ssl; /* user defined SSL stuff for proxy */
struct ssl_general_config general_ssl; /* general user defined SSL stuff */
@@ -1708,6 +1606,7 @@ struct UserDefined {
curl_sshkeycallback ssh_keyfunc; /* key matching callback */
void *ssh_keyfunc_userp; /* custom pointer to callback */
+ bool ssh_compression; /* enable SSH compression */
/* Here follows boolean settings that define how to behave during
this session. They are STATIC, set by libcurl users or at least initially
diff --git a/Utilities/cmcurl/lib/vauth/digest_sspi.c b/Utilities/cmcurl/lib/vauth/digest_sspi.c
index 0bd94442d..a3f96ed24 100644
--- a/Utilities/cmcurl/lib/vauth/digest_sspi.c
+++ b/Utilities/cmcurl/lib/vauth/digest_sspi.c
@@ -352,8 +352,8 @@ CURLcode Curl_auth_decode_digest_http_message(const char *chlg,
if(!Curl_auth_digest_get_pair(p, value, content, &p))
break;
- if(Curl_strcasecompare(value, "stale")
- && Curl_strcasecompare(content, "true")) {
+ if(strcasecompare(value, "stale") &&
+ strcasecompare(content, "true")) {
stale = true;
break;
}
@@ -438,6 +438,20 @@ CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data,
return CURLE_OUT_OF_MEMORY;
}
+ /* If the user/passwd that was used to make the identity for http_context
+ has changed then delete that context. */
+ if((userp && !digest->user) || (!userp && digest->user) ||
+ (passwdp && !digest->passwd) || (!passwdp && digest->passwd) ||
+ (userp && digest->user && strcmp(userp, digest->user)) ||
+ (passwdp && digest->passwd && strcmp(passwdp, digest->passwd))) {
+ if(digest->http_context) {
+ s_pSecFn->DeleteSecurityContext(digest->http_context);
+ Curl_safefree(digest->http_context);
+ }
+ Curl_safefree(digest->user);
+ Curl_safefree(digest->passwd);
+ }
+
if(digest->http_context) {
chlg_desc.ulVersion = SECBUFFER_VERSION;
chlg_desc.cBuffers = 5;
@@ -479,6 +493,10 @@ CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data,
TimeStamp expiry; /* For Windows 9x compatibility of SSPI calls */
TCHAR *spn;
+ /* free the copy of user/passwd used to make the previous identity */
+ Curl_safefree(digest->user);
+ Curl_safefree(digest->passwd);
+
if(userp && *userp) {
/* Populate our identity structure */
if(Curl_create_sspi_identity(userp, passwdp, &identity)) {
@@ -500,6 +518,25 @@ CURLcode Curl_auth_create_digest_http_message(struct Curl_easy *data,
/* Use the current Windows user */
p_identity = NULL;
+ if(userp) {
+ digest->user = strdup(userp);
+
+ if(!digest->user) {
+ free(output_token);
+ return CURLE_OUT_OF_MEMORY;
+ }
+ }
+
+ if(passwdp) {
+ digest->passwd = strdup(passwdp);
+
+ if(!digest->passwd) {
+ free(output_token);
+ Curl_safefree(digest->user);
+ return CURLE_OUT_OF_MEMORY;
+ }
+ }
+
/* Acquire our credentials handle */
status = s_pSecFn->AcquireCredentialsHandle(NULL,
(TCHAR *) TEXT(SP_NAME_DIGEST),
@@ -623,6 +660,10 @@ void Curl_auth_digest_cleanup(struct digestdata *digest)
s_pSecFn->DeleteSecurityContext(digest->http_context);
Curl_safefree(digest->http_context);
}
+
+ /* Free the copy of user/passwd used to make the identity for http_context */
+ Curl_safefree(digest->user);
+ Curl_safefree(digest->passwd);
}
#endif /* USE_WINDOWS_SSPI && !CURL_DISABLE_CRYPTO_AUTH */
diff --git a/Utilities/cmcurl/lib/vauth/ntlm.c b/Utilities/cmcurl/lib/vauth/ntlm.c
index 42196455f..50d922208 100644
--- a/Utilities/cmcurl/lib/vauth/ntlm.c
+++ b/Utilities/cmcurl/lib/vauth/ntlm.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -44,7 +44,9 @@
#include "rand.h"
#include "vtls/vtls.h"
-#ifdef USE_NSS
+/* SSL backend-specific #if branches in this file must be kept in the order
+ documented in curl_ntlm_core. */
+#if defined(NTLM_NEEDS_NSS_INIT)
#include "vtls/nssg.h" /* for Curl_nss_force_init() */
#endif
@@ -272,7 +274,7 @@ CURLcode Curl_auth_decode_ntlm_type2_message(struct Curl_easy *data,
unsigned char *type2 = NULL;
size_t type2_len = 0;
-#if defined(USE_NSS)
+#if defined(NTLM_NEEDS_NSS_INIT)
/* Make sure the crypto backend is initialized */
result = Curl_nss_force_init(data);
if(result)
@@ -350,6 +352,7 @@ static void unicodecpy(unsigned char *dest, const char *src, size_t length)
*
* Parameters:
*
+ * data [in] - The session handle.
* userp [in] - The user name in the format User or Domain\User.
* passdwp [in] - The user's password.
* ntlm [in/out] - The NTLM data struct being used and modified.
@@ -359,7 +362,8 @@ static void unicodecpy(unsigned char *dest, const char *src, size_t length)
*
* Returns CURLE_OK on success.
*/
-CURLcode Curl_auth_create_ntlm_type1_message(const char *userp,
+CURLcode Curl_auth_create_ntlm_type1_message(struct Curl_easy *data,
+ const char *userp,
const char *passwdp,
struct ntlmdata *ntlm,
char **outptr, size_t *outlen)
@@ -458,7 +462,7 @@ CURLcode Curl_auth_create_ntlm_type1_message(const char *userp,
});
/* Return with binary blob encoded into base64 */
- return Curl_base64_encode(NULL, (char *)ntlmbuf, size, outptr, outlen);
+ return Curl_base64_encode(data, (char *)ntlmbuf, size, outptr, outlen);
}
/*
@@ -827,7 +831,7 @@ CURLcode Curl_auth_create_ntlm_type3_message(struct Curl_easy *data,
return CURLE_CONV_FAILED;
/* Return with binary blob encoded into base64 */
- result = Curl_base64_encode(NULL, (char *)ntlmbuf, size, outptr, outlen);
+ result = Curl_base64_encode(data, (char *)ntlmbuf, size, outptr, outlen);
Curl_auth_ntlm_cleanup(ntlm);
diff --git a/Utilities/cmcurl/lib/vauth/ntlm_sspi.c b/Utilities/cmcurl/lib/vauth/ntlm_sspi.c
index c3305176d..e748ce3b6 100644
--- a/Utilities/cmcurl/lib/vauth/ntlm_sspi.c
+++ b/Utilities/cmcurl/lib/vauth/ntlm_sspi.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -29,6 +29,7 @@
#include "vauth/vauth.h"
#include "urldata.h"
#include "curl_base64.h"
+#include "curl_ntlm_core.h"
#include "warnless.h"
#include "curl_multibyte.h"
#include "sendf.h"
@@ -66,6 +67,7 @@ bool Curl_auth_is_ntlm_supported(void)
*
* Parameters:
*
+ * data [in] - The session handle.
* userp [in] - The user name in the format User or Domain\User.
* passdwp [in] - The user's password.
* ntlm [in/out] - The NTLM data struct being used and modified.
@@ -75,7 +77,8 @@ bool Curl_auth_is_ntlm_supported(void)
*
* Returns CURLE_OK on success.
*/
-CURLcode Curl_auth_create_ntlm_type1_message(const char *userp,
+CURLcode Curl_auth_create_ntlm_type1_message(struct Curl_easy *data,
+ const char *userp,
const char *passwdp,
struct ntlmdata *ntlm,
char **outptr, size_t *outlen)
@@ -166,7 +169,7 @@ CURLcode Curl_auth_create_ntlm_type1_message(const char *userp,
return CURLE_RECV_ERROR;
/* Base64 encode the response */
- return Curl_base64_encode(NULL, (char *) ntlm->output_token,
+ return Curl_base64_encode(data, (char *) ntlm->output_token,
type_1_buf.cbBuffer, outptr, outlen);
}
diff --git a/Utilities/cmcurl/lib/vauth/spnego_gssapi.c b/Utilities/cmcurl/lib/vauth/spnego_gssapi.c
index 8840db8fd..5196c2704 100644
--- a/Utilities/cmcurl/lib/vauth/spnego_gssapi.c
+++ b/Utilities/cmcurl/lib/vauth/spnego_gssapi.c
@@ -180,6 +180,10 @@ CURLcode Curl_auth_decode_spnego_message(struct Curl_easy *data,
return CURLE_OUT_OF_MEMORY;
}
+ /* Free previous token */
+ if(nego->output_token.length && nego->output_token.value)
+ gss_release_buffer(&unused_status, &nego->output_token);
+
nego->output_token = output_token;
return CURLE_OK;
diff --git a/Utilities/cmcurl/lib/vauth/vauth.h b/Utilities/cmcurl/lib/vauth/vauth.h
index 9d61228c3..dfaf985c6 100644
--- a/Utilities/cmcurl/lib/vauth/vauth.h
+++ b/Utilities/cmcurl/lib/vauth/vauth.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 2014 - 2016, Steve Holme, <steve_holme@hotmail.com>.
+ * Copyright (C) 2014 - 2017, Steve Holme, <steve_holme@hotmail.com>.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -119,7 +119,8 @@ void Curl_auth_digest_cleanup(struct digestdata *digest);
bool Curl_auth_is_ntlm_supported(void);
/* This is used to generate a base64 encoded NTLM type-1 message */
-CURLcode Curl_auth_create_ntlm_type1_message(const char *userp,
+CURLcode Curl_auth_create_ntlm_type1_message(struct Curl_easy *data,
+ const char *userp,
const char *passwdp,
struct ntlmdata *ntlm,
char **outptr,
diff --git a/Utilities/cmcurl/lib/version.c b/Utilities/cmcurl/lib/version.c
index 3d1776813..ebd600635 100644
--- a/Utilities/cmcurl/lib/version.c
+++ b/Utilities/cmcurl/lib/version.c
@@ -324,8 +324,8 @@ static curl_version_info_data version_info = {
#if defined(USE_LIBPSL)
| CURL_VERSION_PSL
#endif
-#if defined(HTTPS_PROXY_SUPPORT)
- | CURL_VERSION_HTTPS_PROXY
+#if defined(CURL_WITH_MULTI_SSL)
+ | CURL_VERSION_MULTI_SSL
#endif
,
NULL, /* ssl_version */
@@ -355,6 +355,10 @@ curl_version_info_data *curl_version_info(CURLversion stamp)
#ifdef USE_SSL
Curl_ssl_version(ssl_buffer, sizeof(ssl_buffer));
version_info.ssl_version = ssl_buffer;
+ if(Curl_ssl->support_https_proxy)
+ version_info.features |= CURL_VERSION_HTTPS_PROXY;
+ else
+ version_info.features &= ~CURL_VERSION_HTTPS_PROXY;
#endif
#ifdef HAVE_LIBZ
diff --git a/Utilities/cmcurl/lib/vtls/axtls.c b/Utilities/cmcurl/lib/vtls/axtls.c
index f0e376640..6b42708d8 100644
--- a/Utilities/cmcurl/lib/vtls/axtls.c
+++ b/Utilities/cmcurl/lib/vtls/axtls.c
@@ -47,21 +47,12 @@
#include "curl_memory.h"
#include "memdebug.h"
+struct ssl_backend_data {
+ SSL_CTX* ssl_ctx;
+ SSL* ssl;
+};
-/* Global axTLS init, called from Curl_ssl_init() */
-int Curl_axtls_init(void)
-{
-/* axTLS has no global init. Everything is done through SSL and SSL_CTX
- * structs stored in connectdata structure. Perhaps can move to axtls.h.
- */
- return 1;
-}
-
-int Curl_axtls_cleanup(void)
-{
- /* axTLS has no global cleanup. Perhaps can move this to axtls.h. */
- return 1;
-}
+#define BACKEND connssl->backend
static CURLcode map_error_to_curl(int axtls_err)
{
@@ -120,13 +111,13 @@ static Curl_send axtls_send;
static void free_ssl_structs(struct ssl_connect_data *connssl)
{
- if(connssl->ssl) {
- ssl_free(connssl->ssl);
- connssl->ssl = NULL;
+ if(BACKEND->ssl) {
+ ssl_free(BACKEND->ssl);
+ BACKEND->ssl = NULL;
}
- if(connssl->ssl_ctx) {
- ssl_ctx_free(connssl->ssl_ctx);
- connssl->ssl_ctx = NULL;
+ if(BACKEND->ssl_ctx) {
+ ssl_ctx_free(BACKEND->ssl_ctx);
+ BACKEND->ssl_ctx = NULL;
}
}
@@ -137,6 +128,7 @@ static void free_ssl_structs(struct ssl_connect_data *connssl)
*/
static CURLcode connect_prep(struct connectdata *conn, int sockindex)
{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
struct Curl_easy *data = conn->data;
SSL_CTX *ssl_ctx;
SSL *ssl = NULL;
@@ -151,7 +143,7 @@ static CURLcode connect_prep(struct connectdata *conn, int sockindex)
SSL_SERVER_VERIFY_LATER |
SSL_CONNECT_IN_PARTS;
- if(conn->ssl[sockindex].state == ssl_connection_complete)
+ if(connssl->state == ssl_connection_complete)
/* to make us tolerant against being called more than once for the
same connection */
return CURLE_OK;
@@ -185,8 +177,8 @@ static CURLcode connect_prep(struct connectdata *conn, int sockindex)
return CURLE_SSL_CONNECT_ERROR;
}
- conn->ssl[sockindex].ssl_ctx = ssl_ctx;
- conn->ssl[sockindex].ssl = NULL;
+ BACKEND->ssl_ctx = ssl_ctx;
+ BACKEND->ssl = NULL;
/* Load the trusted CA cert bundle file */
if(SSL_CONN_CONFIG(CAfile)) {
@@ -212,7 +204,7 @@ static CURLcode connect_prep(struct connectdata *conn, int sockindex)
/* Load client certificate */
if(SSL_SET_OPTION(cert)) {
- i=0;
+ i = 0;
/* Instead of trying to analyze cert type here, let axTLS try them all. */
while(cert_types[i] != 0) {
ssl_fcn_return = ssl_obj_load(ssl_ctx, cert_types[i],
@@ -236,7 +228,7 @@ static CURLcode connect_prep(struct connectdata *conn, int sockindex)
If a pkcs12 file successfully loaded a cert, then there's nothing to do
because the key has already been loaded. */
if(SSL_SET_OPTION(key) && cert_types[i] != SSL_OBJ_PKCS12) {
- i=0;
+ i = 0;
/* Instead of trying to analyze key type here, let axTLS try them all. */
while(key_types[i] != 0) {
ssl_fcn_return = ssl_obj_load(ssl_ctx, key_types[i],
@@ -281,10 +273,26 @@ static CURLcode connect_prep(struct connectdata *conn, int sockindex)
if(!ssl)
ssl = ssl_client_new(ssl_ctx, conn->sock[sockindex], NULL, 0, NULL);
- conn->ssl[sockindex].ssl = ssl;
+ BACKEND->ssl = ssl;
return CURLE_OK;
}
+static void Curl_axtls_close(struct connectdata *conn, int sockindex)
+{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+
+ infof(conn->data, " Curl_axtls_close\n");
+
+ /* line from openssl.c: (void)SSL_shutdown(BACKEND->ssl);
+ axTLS compat layer does nothing for SSL_shutdown */
+
+ /* The following line is from openssl.c. There seems to be no axTLS
+ equivalent. ssl_free and ssl_ctx_free close things.
+ SSL_set_connect_state(connssl->handle); */
+
+ free_ssl_structs(connssl);
+}
+
/*
* For both blocking and non-blocking connects, this function finalizes the
* SSL connection.
@@ -292,7 +300,8 @@ static CURLcode connect_prep(struct connectdata *conn, int sockindex)
static CURLcode connect_finish(struct connectdata *conn, int sockindex)
{
struct Curl_easy *data = conn->data;
- SSL *ssl = conn->ssl[sockindex].ssl;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ SSL *ssl = BACKEND->ssl;
const char *peer_CN;
uint32_t dns_altname_index;
const char *dns_altname;
@@ -387,7 +396,7 @@ static CURLcode connect_finish(struct connectdata *conn, int sockindex)
}
/* General housekeeping */
- conn->ssl[sockindex].state = ssl_connection_complete;
+ connssl->state = ssl_connection_complete;
conn->recv[sockindex] = axtls_recv;
conn->send[sockindex] = axtls_send;
@@ -409,11 +418,10 @@ static CURLcode connect_finish(struct connectdata *conn, int sockindex)
* Use axTLS's non-blocking connection feature to open an SSL connection.
* This is called after a TCP connection is already established.
*/
-CURLcode Curl_axtls_connect_nonblocking(
- struct connectdata *conn,
- int sockindex,
- bool *done)
+static CURLcode Curl_axtls_connect_nonblocking(struct connectdata *conn,
+ int sockindex, bool *done)
{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
CURLcode conn_step;
int ssl_fcn_return;
int i;
@@ -421,23 +429,23 @@ CURLcode Curl_axtls_connect_nonblocking(
*done = FALSE;
/* connectdata is calloc'd and connecting_state is only changed in this
function, so this is safe, as the state is effectively initialized. */
- if(conn->ssl[sockindex].connecting_state == ssl_connect_1) {
+ if(connssl->connecting_state == ssl_connect_1) {
conn_step = connect_prep(conn, sockindex);
if(conn_step != CURLE_OK) {
Curl_axtls_close(conn, sockindex);
return conn_step;
}
- conn->ssl[sockindex].connecting_state = ssl_connect_2;
+ connssl->connecting_state = ssl_connect_2;
}
- if(conn->ssl[sockindex].connecting_state == ssl_connect_2) {
+ if(connssl->connecting_state == ssl_connect_2) {
/* Check to make sure handshake was ok. */
- if(ssl_handshake_status(conn->ssl[sockindex].ssl) != SSL_OK) {
+ if(ssl_handshake_status(BACKEND->ssl) != SSL_OK) {
/* Loop to perform more work in between sleeps. This is work around the
fact that axtls does not expose any knowledge about when work needs
to be performed. This can save ~25% of time on SSL handshakes. */
- for(i=0; i<5; i++) {
- ssl_fcn_return = ssl_read(conn->ssl[sockindex].ssl, NULL);
+ for(i = 0; i<5; i++) {
+ ssl_fcn_return = ssl_read(BACKEND->ssl, NULL);
if(ssl_fcn_return < 0) {
Curl_axtls_close(conn, sockindex);
ssl_display_error(ssl_fcn_return); /* goes to stdout. */
@@ -447,10 +455,10 @@ CURLcode Curl_axtls_connect_nonblocking(
}
}
infof(conn->data, "handshake completed successfully\n");
- conn->ssl[sockindex].connecting_state = ssl_connect_3;
+ connssl->connecting_state = ssl_connect_3;
}
- if(conn->ssl[sockindex].connecting_state == ssl_connect_3) {
+ if(connssl->connecting_state == ssl_connect_3) {
conn_step = connect_finish(conn, sockindex);
if(conn_step != CURLE_OK) {
Curl_axtls_close(conn, sockindex);
@@ -458,15 +466,15 @@ CURLcode Curl_axtls_connect_nonblocking(
}
/* Reset connect state */
- conn->ssl[sockindex].connecting_state = ssl_connect_1;
+ connssl->connecting_state = ssl_connect_1;
*done = TRUE;
return CURLE_OK;
}
/* Unrecognized state. Things are very bad. */
- conn->ssl[sockindex].state = ssl_connection_none;
- conn->ssl[sockindex].connecting_state = ssl_connect_1;
+ connssl->state = ssl_connection_none;
+ connssl->connecting_state = ssl_connect_1;
/* Return value perhaps not strictly correct, but distinguishes the issue.*/
return CURLE_BAD_FUNCTION_ARGUMENT;
}
@@ -476,15 +484,13 @@ CURLcode Curl_axtls_connect_nonblocking(
* This function is called after the TCP connect has completed. Setup the TLS
* layer and do all necessary magic for a blocking connect.
*/
-CURLcode
-Curl_axtls_connect(struct connectdata *conn,
- int sockindex)
-
+static CURLcode Curl_axtls_connect(struct connectdata *conn, int sockindex)
{
struct Curl_easy *data = conn->data;
CURLcode conn_step = connect_prep(conn, sockindex);
int ssl_fcn_return;
- SSL *ssl = conn->ssl[sockindex].ssl;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ SSL *ssl = BACKEND->ssl;
long timeout_ms;
if(conn_step != CURLE_OK) {
@@ -530,8 +536,9 @@ static ssize_t axtls_send(struct connectdata *conn,
size_t len,
CURLcode *err)
{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
/* ssl_write() returns 'int' while write() and send() returns 'size_t' */
- int rc = ssl_write(conn->ssl[sockindex].ssl, mem, (int)len);
+ int rc = ssl_write(BACKEND->ssl, mem, (int)len);
infof(conn->data, " axtls_send\n");
@@ -544,27 +551,11 @@ static ssize_t axtls_send(struct connectdata *conn,
return rc;
}
-void Curl_axtls_close(struct connectdata *conn, int sockindex)
-{
- struct ssl_connect_data *connssl = &conn->ssl[sockindex];
-
- infof(conn->data, " Curl_axtls_close\n");
-
- /* line from openssl.c: (void)SSL_shutdown(connssl->ssl);
- axTLS compat layer does nothing for SSL_shutdown */
-
- /* The following line is from openssl.c. There seems to be no axTLS
- equivalent. ssl_free and ssl_ctx_free close things.
- SSL_set_connect_state(connssl->handle); */
-
- free_ssl_structs(connssl);
-}
-
/*
* This function is called to shut down the SSL layer but keep the
* socket open (CCC - Clear Command Channel)
*/
-int Curl_axtls_shutdown(struct connectdata *conn, int sockindex)
+static int Curl_axtls_shutdown(struct connectdata *conn, int sockindex)
{
/* Outline taken from openssl.c since functions are in axTLS compat layer.
axTLS's error set is much smaller, so a lot of error-handling was removed.
@@ -584,17 +575,17 @@ int Curl_axtls_shutdown(struct connectdata *conn, int sockindex)
/* axTLS compat layer does nothing for SSL_shutdown, so we do nothing too
if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
- (void)SSL_shutdown(connssl->ssl);
+ (void)SSL_shutdown(BACKEND->ssl);
*/
- if(connssl->ssl) {
+ if(BACKEND->ssl) {
int what = SOCKET_READABLE(conn->sock[sockindex], SSL_SHUTDOWN_TIMEOUT);
if(what > 0) {
/* Something to read, let's do it and hope that it is the close
notify alert from the server. buf is managed internally by
axTLS and will be released upon calling ssl_free via
free_ssl_structs. */
- nread = (ssize_t)ssl_read(connssl->ssl, &buf);
+ nread = (ssize_t)ssl_read(BACKEND->ssl, &buf);
if(nread < SSL_OK) {
failf(data, "close notify alert not received during shutdown");
@@ -630,7 +621,7 @@ static ssize_t axtls_recv(struct connectdata *conn, /* connection data */
*err = CURLE_OK;
if(connssl) {
- ret = ssl_read(connssl->ssl, &read_buf);
+ ret = ssl_read(BACKEND->ssl, &read_buf);
if(ret > SSL_OK) {
/* ssl_read returns SSL_OK if there is more data to read, so if it is
larger, then all data has been read already. */
@@ -663,9 +654,10 @@ static ssize_t axtls_recv(struct connectdata *conn, /* connection data */
* 0 means the connection has been closed
* -1 means the connection status is unknown
*/
-int Curl_axtls_check_cxn(struct connectdata *conn)
+static int Curl_axtls_check_cxn(struct connectdata *conn)
{
- /* openssl.c line: rc = SSL_peek(conn->ssl[FIRSTSOCKET].ssl, (void*)&buf, 1);
+ /* openssl.c line:
+ rc = SSL_peek(conn->ssl[FIRSTSOCKET].backend->ssl, (void*)&buf, 1);
axTLS compat layer always returns the last argument, so connection is
always alive? */
@@ -673,7 +665,7 @@ int Curl_axtls_check_cxn(struct connectdata *conn)
return 1; /* connection still in place */
}
-void Curl_axtls_session_free(void *ptr)
+static void Curl_axtls_session_free(void *ptr)
{
(void)ptr;
/* free the ID */
@@ -681,14 +673,13 @@ void Curl_axtls_session_free(void *ptr)
compatibility layer does nothing, so we do nothing too. */
}
-size_t Curl_axtls_version(char *buffer, size_t size)
+static size_t Curl_axtls_version(char *buffer, size_t size)
{
return snprintf(buffer, size, "axTLS/%s", ssl_version());
}
-CURLcode Curl_axtls_random(struct Curl_easy *data,
- unsigned char *entropy,
- size_t length)
+static CURLcode Curl_axtls_random(struct Curl_easy *data,
+ unsigned char *entropy, size_t length)
{
static bool ssl_seeded = FALSE;
(void)data;
@@ -703,4 +694,49 @@ CURLcode Curl_axtls_random(struct Curl_easy *data,
return CURLE_OK;
}
+static void *Curl_axtls_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info UNUSED_PARAM)
+{
+ (void)info;
+ return BACKEND->ssl;
+}
+
+const struct Curl_ssl Curl_ssl_axtls = {
+ { CURLSSLBACKEND_AXTLS, "axtls" }, /* info */
+
+ 0, /* have_ca_path */
+ 0, /* have_certinfo */
+ 0, /* have_pinnedpubkey */
+ 0, /* have_ssl_ctx */
+ 0, /* support_https_proxy */
+
+ sizeof(struct ssl_backend_data),
+
+ /*
+ * axTLS has no global init. Everything is done through SSL and SSL_CTX
+ * structs stored in connectdata structure.
+ */
+ Curl_none_init, /* init */
+ /* axTLS has no global cleanup. */
+ Curl_none_cleanup, /* cleanup */
+ Curl_axtls_version, /* version */
+ Curl_axtls_check_cxn, /* check_cxn */
+ Curl_axtls_shutdown, /* shutdown */
+ Curl_none_data_pending, /* data_pending */
+ Curl_axtls_random, /* random */
+ Curl_none_cert_status_request, /* cert_status_request */
+ Curl_axtls_connect, /* connect */
+ Curl_axtls_connect_nonblocking, /* connect_nonblocking */
+ Curl_axtls_get_internals, /* get_internals */
+ Curl_axtls_close, /* close */
+ Curl_none_close_all, /* close_all */
+ Curl_axtls_session_free, /* session_free */
+ Curl_none_set_engine, /* set_engine */
+ Curl_none_set_engine_default, /* set_engine_default */
+ Curl_none_engines_list, /* engines_list */
+ Curl_none_false_start, /* false_start */
+ Curl_none_md5sum, /* md5sum */
+ NULL /* sha256sum */
+};
+
#endif /* USE_AXTLS */
diff --git a/Utilities/cmcurl/lib/vtls/axtls.h b/Utilities/cmcurl/lib/vtls/axtls.h
index 53797eadb..3f1e129c2 100644
--- a/Utilities/cmcurl/lib/vtls/axtls.h
+++ b/Utilities/cmcurl/lib/vtls/axtls.h
@@ -27,44 +27,7 @@
#include "curl/curl.h"
#include "urldata.h"
-int Curl_axtls_init(void);
-int Curl_axtls_cleanup(void);
-CURLcode Curl_axtls_connect(struct connectdata *conn, int sockindex);
-CURLcode Curl_axtls_connect_nonblocking(
- struct connectdata *conn,
- int sockindex,
- bool *done);
-
- /* close a SSL connection */
-void Curl_axtls_close(struct connectdata *conn, int sockindex);
-
-void Curl_axtls_session_free(void *ptr);
-size_t Curl_axtls_version(char *buffer, size_t size);
-int Curl_axtls_shutdown(struct connectdata *conn, int sockindex);
-int Curl_axtls_check_cxn(struct connectdata *conn);
-CURLcode Curl_axtls_random(struct Curl_easy *data,
- unsigned char *entropy,
- size_t length);
-
-/* Set the API backend definition to axTLS */
-#define CURL_SSL_BACKEND CURLSSLBACKEND_AXTLS
-
-/* API setup for axTLS */
-#define curlssl_init Curl_axtls_init
-#define curlssl_cleanup Curl_axtls_cleanup
-#define curlssl_connect Curl_axtls_connect
-#define curlssl_connect_nonblocking Curl_axtls_connect_nonblocking
-#define curlssl_session_free(x) Curl_axtls_session_free(x)
-#define curlssl_close_all(x) ((void)x)
-#define curlssl_close Curl_axtls_close
-#define curlssl_shutdown(x,y) Curl_axtls_shutdown(x,y)
-#define curlssl_set_engine(x,y) ((void)x, (void)y, CURLE_NOT_BUILT_IN)
-#define curlssl_set_engine_default(x) ((void)x, CURLE_NOT_BUILT_IN)
-#define curlssl_engines_list(x) ((void)x, (struct curl_slist *)NULL)
-#define curlssl_version Curl_axtls_version
-#define curlssl_check_cxn(x) Curl_axtls_check_cxn(x)
-#define curlssl_data_pending(x,y) ((void)x, (void)y, 0)
-#define curlssl_random(x,y,z) Curl_axtls_random(x,y,z)
+extern const struct Curl_ssl Curl_ssl_axtls;
#endif /* USE_AXTLS */
#endif /* HEADER_CURL_AXTLS_H */
diff --git a/Utilities/cmcurl/lib/vtls/cyassl.c b/Utilities/cmcurl/lib/vtls/cyassl.c
index 01bfdabd1..ba5ee1548 100644
--- a/Utilities/cmcurl/lib/vtls/cyassl.c
+++ b/Utilities/cmcurl/lib/vtls/cyassl.c
@@ -91,6 +91,7 @@ and that's a problem since options.h hasn't been included yet. */
#include "x509asn1.h"
#include "curl_printf.h"
+#include <cyassl/openssl/ssl.h>
#include <cyassl/ssl.h>
#ifdef HAVE_CYASSL_ERROR_SSL_H
#include <cyassl/error-ssl.h>
@@ -110,6 +111,25 @@ and that's a problem since options.h hasn't been included yet. */
#define CYASSL_MAX_ERROR_SZ 80
#endif
+/* KEEP_PEER_CERT is a product of the presence of build time symbol
+ OPENSSL_EXTRA without NO_CERTS, depending on the version. KEEP_PEER_CERT is
+ in wolfSSL's settings.h, and the latter two are build time symbols in
+ options.h. */
+#ifndef KEEP_PEER_CERT
+#if defined(HAVE_CYASSL_GET_PEER_CERTIFICATE) || \
+ defined(HAVE_WOLFSSL_GET_PEER_CERTIFICATE) || \
+ (defined(OPENSSL_EXTRA) && !defined(NO_CERTS))
+#define KEEP_PEER_CERT
+#endif
+#endif
+
+struct ssl_backend_data {
+ SSL_CTX* ctx;
+ SSL* handle;
+};
+
+#define BACKEND connssl->backend
+
static Curl_recv cyassl_recv;
static Curl_send cyassl_send;
@@ -136,7 +156,7 @@ cyassl_connect_step1(struct connectdata *conn,
char error_buffer[CYASSL_MAX_ERROR_SZ];
char *ciphers;
struct Curl_easy *data = conn->data;
- struct ssl_connect_data* conssl = &conn->ssl[sockindex];
+ struct ssl_connect_data* connssl = &conn->ssl[sockindex];
SSL_METHOD* req_method = NULL;
curl_socket_t sockfd = conn->sock[sockindex];
#ifdef HAVE_SNI
@@ -146,7 +166,7 @@ cyassl_connect_step1(struct connectdata *conn,
#define use_sni(x) Curl_nop_stmt
#endif
- if(conssl->state == ssl_connection_complete)
+ if(connssl->state == ssl_connection_complete)
return CURLE_OK;
if(SSL_CONN_CONFIG(version_max) != CURL_SSLVERSION_MAX_NONE) {
@@ -205,11 +225,11 @@ cyassl_connect_step1(struct connectdata *conn,
return CURLE_OUT_OF_MEMORY;
}
- if(conssl->ctx)
- SSL_CTX_free(conssl->ctx);
- conssl->ctx = SSL_CTX_new(req_method);
+ if(BACKEND->ctx)
+ SSL_CTX_free(BACKEND->ctx);
+ BACKEND->ctx = SSL_CTX_new(req_method);
- if(!conssl->ctx) {
+ if(!BACKEND->ctx) {
failf(data, "SSL: couldn't create a context!");
return CURLE_OUT_OF_MEMORY;
}
@@ -225,9 +245,9 @@ cyassl_connect_step1(struct connectdata *conn,
version. We use wolfSSL_CTX_SetMinVersion and not CyaSSL_SetMinVersion
because only the former will work before the user's CTX callback is called.
*/
- if((wolfSSL_CTX_SetMinVersion(conssl->ctx, WOLFSSL_TLSV1) != 1) &&
- (wolfSSL_CTX_SetMinVersion(conssl->ctx, WOLFSSL_TLSV1_1) != 1) &&
- (wolfSSL_CTX_SetMinVersion(conssl->ctx, WOLFSSL_TLSV1_2) != 1)) {
+ if((wolfSSL_CTX_SetMinVersion(BACKEND->ctx, WOLFSSL_TLSV1) != 1) &&
+ (wolfSSL_CTX_SetMinVersion(BACKEND->ctx, WOLFSSL_TLSV1_1) != 1) &&
+ (wolfSSL_CTX_SetMinVersion(BACKEND->ctx, WOLFSSL_TLSV1_2) != 1)) {
failf(data, "SSL: couldn't set the minimum protocol version");
return CURLE_SSL_CONNECT_ERROR;
}
@@ -237,7 +257,7 @@ cyassl_connect_step1(struct connectdata *conn,
ciphers = SSL_CONN_CONFIG(cipher_list);
if(ciphers) {
- if(!SSL_CTX_set_cipher_list(conssl->ctx, ciphers)) {
+ if(!SSL_CTX_set_cipher_list(BACKEND->ctx, ciphers)) {
failf(data, "failed setting cipher list: %s", ciphers);
return CURLE_SSL_CIPHER;
}
@@ -247,7 +267,7 @@ cyassl_connect_step1(struct connectdata *conn,
#ifndef NO_FILESYSTEM
/* load trusted cacert */
if(SSL_CONN_CONFIG(CAfile)) {
- if(1 != SSL_CTX_load_verify_locations(conssl->ctx,
+ if(1 != SSL_CTX_load_verify_locations(BACKEND->ctx,
SSL_CONN_CONFIG(CAfile),
SSL_CONN_CONFIG(CApath))) {
if(SSL_CONN_CONFIG(verifypeer)) {
@@ -284,7 +304,7 @@ cyassl_connect_step1(struct connectdata *conn,
if(SSL_SET_OPTION(cert) && SSL_SET_OPTION(key)) {
int file_type = do_file_type(SSL_SET_OPTION(cert_type));
- if(SSL_CTX_use_certificate_file(conssl->ctx, SSL_SET_OPTION(cert),
+ if(SSL_CTX_use_certificate_file(BACKEND->ctx, SSL_SET_OPTION(cert),
file_type) != 1) {
failf(data, "unable to use client certificate (no key or wrong pass"
" phrase?)");
@@ -292,7 +312,7 @@ cyassl_connect_step1(struct connectdata *conn,
}
file_type = do_file_type(SSL_SET_OPTION(key_type));
- if(SSL_CTX_use_PrivateKey_file(conssl->ctx, SSL_SET_OPTION(key),
+ if(SSL_CTX_use_PrivateKey_file(BACKEND->ctx, SSL_SET_OPTION(key),
file_type) != 1) {
failf(data, "unable to set private key");
return CURLE_SSL_CONNECT_ERROR;
@@ -304,7 +324,7 @@ cyassl_connect_step1(struct connectdata *conn,
* fail to connect if the verification fails, or if it should continue
* anyway. In the latter case the result of the verification is checked with
* SSL_get_verify_result() below. */
- SSL_CTX_set_verify(conssl->ctx,
+ SSL_CTX_set_verify(BACKEND->ctx,
SSL_CONN_CONFIG(verifypeer)?SSL_VERIFY_PEER:
SSL_VERIFY_NONE,
NULL);
@@ -323,7 +343,7 @@ cyassl_connect_step1(struct connectdata *conn,
#ifdef ENABLE_IPV6
(0 == Curl_inet_pton(AF_INET6, hostname, &addr6)) &&
#endif
- (CyaSSL_CTX_UseSNI(conssl->ctx, CYASSL_SNI_HOST_NAME, hostname,
+ (CyaSSL_CTX_UseSNI(BACKEND->ctx, CYASSL_SNI_HOST_NAME, hostname,
(unsigned short)hostname_len) != 1)) {
infof(data, "WARNING: failed to configure server name indication (SNI) "
"TLS extension\n");
@@ -336,15 +356,15 @@ cyassl_connect_step1(struct connectdata *conn,
https://github.com/wolfSSL/wolfssl/issues/366
The supported curves below are those also supported by OpenSSL 1.0.2 and
in the same order. */
- CyaSSL_CTX_UseSupportedCurve(conssl->ctx, 0x17); /* secp256r1 */
- CyaSSL_CTX_UseSupportedCurve(conssl->ctx, 0x19); /* secp521r1 */
- CyaSSL_CTX_UseSupportedCurve(conssl->ctx, 0x18); /* secp384r1 */
+ CyaSSL_CTX_UseSupportedCurve(BACKEND->ctx, 0x17); /* secp256r1 */
+ CyaSSL_CTX_UseSupportedCurve(BACKEND->ctx, 0x19); /* secp521r1 */
+ CyaSSL_CTX_UseSupportedCurve(BACKEND->ctx, 0x18); /* secp384r1 */
#endif
/* give application a chance to interfere with SSL set up. */
if(data->set.ssl.fsslctx) {
CURLcode result = CURLE_OK;
- result = (*data->set.ssl.fsslctx)(data, conssl->ctx,
+ result = (*data->set.ssl.fsslctx)(data, BACKEND->ctx,
data->set.ssl.fsslctxp);
if(result) {
failf(data, "error signaled by ssl ctx callback");
@@ -362,10 +382,10 @@ cyassl_connect_step1(struct connectdata *conn,
#endif
/* Let's make an SSL structure */
- if(conssl->handle)
- SSL_free(conssl->handle);
- conssl->handle = SSL_new(conssl->ctx);
- if(!conssl->handle) {
+ if(BACKEND->handle)
+ SSL_free(BACKEND->handle);
+ BACKEND->handle = SSL_new(BACKEND->ctx);
+ if(!BACKEND->handle) {
failf(data, "SSL: couldn't create a context (handle)!");
return CURLE_OUT_OF_MEMORY;
}
@@ -388,7 +408,7 @@ cyassl_connect_step1(struct connectdata *conn,
strcpy(protocols + strlen(protocols), ALPN_HTTP_1_1);
infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
- if(wolfSSL_UseALPN(conssl->handle, protocols,
+ if(wolfSSL_UseALPN(BACKEND->handle, protocols,
(unsigned)strlen(protocols),
WOLFSSL_ALPN_CONTINUE_ON_MISMATCH) != SSL_SUCCESS) {
failf(data, "SSL: failed setting ALPN protocols");
@@ -404,10 +424,10 @@ cyassl_connect_step1(struct connectdata *conn,
Curl_ssl_sessionid_lock(conn);
if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) {
/* we got a session id, use it! */
- if(!SSL_set_session(conssl->handle, ssl_sessionid)) {
+ if(!SSL_set_session(BACKEND->handle, ssl_sessionid)) {
Curl_ssl_sessionid_unlock(conn);
failf(data, "SSL: SSL_set_session failed: %s",
- ERR_error_string(SSL_get_error(conssl->handle, 0),
+ ERR_error_string(SSL_get_error(BACKEND->handle, 0),
error_buffer));
return CURLE_SSL_CONNECT_ERROR;
}
@@ -418,12 +438,12 @@ cyassl_connect_step1(struct connectdata *conn,
}
/* pass the raw socket into the SSL layer */
- if(!SSL_set_fd(conssl->handle, (int)sockfd)) {
+ if(!SSL_set_fd(BACKEND->handle, (int)sockfd)) {
failf(data, "SSL: SSL_set_fd failed");
return CURLE_SSL_CONNECT_ERROR;
}
- conssl->connecting_state = ssl_connect_2;
+ connssl->connecting_state = ssl_connect_2;
return CURLE_OK;
}
@@ -434,7 +454,7 @@ cyassl_connect_step2(struct connectdata *conn,
{
int ret = -1;
struct Curl_easy *data = conn->data;
- struct ssl_connect_data* conssl = &conn->ssl[sockindex];
+ struct ssl_connect_data* connssl = &conn->ssl[sockindex];
const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
conn->host.name;
const char * const dispname = SSL_IS_PROXY() ?
@@ -448,22 +468,22 @@ cyassl_connect_step2(struct connectdata *conn,
/* Enable RFC2818 checks */
if(SSL_CONN_CONFIG(verifyhost)) {
- ret = CyaSSL_check_domain_name(conssl->handle, hostname);
+ ret = CyaSSL_check_domain_name(BACKEND->handle, hostname);
if(ret == SSL_FAILURE)
return CURLE_OUT_OF_MEMORY;
}
- ret = SSL_connect(conssl->handle);
+ ret = SSL_connect(BACKEND->handle);
if(ret != 1) {
char error_buffer[CYASSL_MAX_ERROR_SZ];
- int detail = SSL_get_error(conssl->handle, ret);
+ int detail = SSL_get_error(BACKEND->handle, ret);
if(SSL_ERROR_WANT_READ == detail) {
- conssl->connecting_state = ssl_connect_2_reading;
+ connssl->connecting_state = ssl_connect_2_reading;
return CURLE_OK;
}
else if(SSL_ERROR_WANT_WRITE == detail) {
- conssl->connecting_state = ssl_connect_2_writing;
+ connssl->connecting_state = ssl_connect_2_writing;
return CURLE_OK;
}
/* There is no easy way to override only the CN matching.
@@ -524,7 +544,7 @@ cyassl_connect_step2(struct connectdata *conn,
curl_asn1Element *pubkey;
CURLcode result;
- x509 = SSL_get_peer_certificate(conssl->handle);
+ x509 = SSL_get_peer_certificate(BACKEND->handle);
if(!x509) {
failf(data, "SSL: failed retrieving server certificate");
return CURLE_SSL_PINNEDPUBKEYNOTMATCH;
@@ -566,7 +586,7 @@ cyassl_connect_step2(struct connectdata *conn,
char *protocol = NULL;
unsigned short protocol_len = 0;
- rc = wolfSSL_ALPN_GetProtocol(conssl->handle, &protocol, &protocol_len);
+ rc = wolfSSL_ALPN_GetProtocol(BACKEND->handle, &protocol, &protocol_len);
if(rc == SSL_SUCCESS) {
infof(data, "ALPN, server accepted to use %.*s\n", protocol_len,
@@ -595,11 +615,11 @@ cyassl_connect_step2(struct connectdata *conn,
}
#endif /* HAVE_ALPN */
- conssl->connecting_state = ssl_connect_3;
+ connssl->connecting_state = ssl_connect_3;
#if (LIBCYASSL_VERSION_HEX >= 0x03009010)
infof(data, "SSL connection using %s / %s\n",
- wolfSSL_get_version(conssl->handle),
- wolfSSL_get_cipher_name(conssl->handle));
+ wolfSSL_get_version(BACKEND->handle),
+ wolfSSL_get_cipher_name(BACKEND->handle));
#else
infof(data, "SSL connected\n");
#endif
@@ -623,7 +643,7 @@ cyassl_connect_step3(struct connectdata *conn,
SSL_SESSION *our_ssl_sessionid;
void *old_ssl_sessionid = NULL;
- our_ssl_sessionid = SSL_get_session(connssl->handle);
+ our_ssl_sessionid = SSL_get_session(BACKEND->handle);
Curl_ssl_sessionid_lock(conn);
incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL,
@@ -660,12 +680,13 @@ static ssize_t cyassl_send(struct connectdata *conn,
size_t len,
CURLcode *curlcode)
{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
char error_buffer[CYASSL_MAX_ERROR_SZ];
int memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
- int rc = SSL_write(conn->ssl[sockindex].handle, mem, memlen);
+ int rc = SSL_write(BACKEND->handle, mem, memlen);
if(rc < 0) {
- int err = SSL_get_error(conn->ssl[sockindex].handle, rc);
+ int err = SSL_get_error(BACKEND->handle, rc);
switch(err) {
case SSL_ERROR_WANT_READ:
@@ -684,18 +705,18 @@ static ssize_t cyassl_send(struct connectdata *conn,
return rc;
}
-void Curl_cyassl_close(struct connectdata *conn, int sockindex)
+static void Curl_cyassl_close(struct connectdata *conn, int sockindex)
{
- struct ssl_connect_data *conssl = &conn->ssl[sockindex];
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
- if(conssl->handle) {
- (void)SSL_shutdown(conssl->handle);
- SSL_free(conssl->handle);
- conssl->handle = NULL;
+ if(BACKEND->handle) {
+ (void)SSL_shutdown(BACKEND->handle);
+ SSL_free(BACKEND->handle);
+ BACKEND->handle = NULL;
}
- if(conssl->ctx) {
- SSL_CTX_free(conssl->ctx);
- conssl->ctx = NULL;
+ if(BACKEND->ctx) {
+ SSL_CTX_free(BACKEND->ctx);
+ BACKEND->ctx = NULL;
}
}
@@ -705,12 +726,13 @@ static ssize_t cyassl_recv(struct connectdata *conn,
size_t buffersize,
CURLcode *curlcode)
{
+ struct ssl_connect_data *connssl = &conn->ssl[num];
char error_buffer[CYASSL_MAX_ERROR_SZ];
int buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
- int nread = SSL_read(conn->ssl[num].handle, buf, buffsize);
+ int nread = SSL_read(BACKEND->handle, buf, buffsize);
if(nread < 0) {
- int err = SSL_get_error(conn->ssl[num].handle, nread);
+ int err = SSL_get_error(BACKEND->handle, nread);
switch(err) {
case SSL_ERROR_ZERO_RETURN: /* no more data */
@@ -732,14 +754,14 @@ static ssize_t cyassl_recv(struct connectdata *conn,
}
-void Curl_cyassl_session_free(void *ptr)
+static void Curl_cyassl_session_free(void *ptr)
{
(void)ptr;
/* CyaSSL reuses sessions on own, no free */
}
-size_t Curl_cyassl_version(char *buffer, size_t size)
+static size_t Curl_cyassl_version(char *buffer, size_t size)
{
#if LIBCYASSL_VERSION_HEX >= 0x03006000
return snprintf(buffer, size, "wolfSSL/%s", wolfSSL_lib_version());
@@ -753,16 +775,18 @@ size_t Curl_cyassl_version(char *buffer, size_t size)
}
-int Curl_cyassl_init(void)
+static int Curl_cyassl_init(void)
{
return (CyaSSL_Init() == SSL_SUCCESS);
}
-bool Curl_cyassl_data_pending(const struct connectdata* conn, int connindex)
+static bool Curl_cyassl_data_pending(const struct connectdata* conn,
+ int connindex)
{
- if(conn->ssl[connindex].handle) /* SSL is in use */
- return (0 != SSL_pending(conn->ssl[connindex].handle)) ? TRUE : FALSE;
+ const struct ssl_connect_data *connssl = &conn->ssl[connindex];
+ if(BACKEND->handle) /* SSL is in use */
+ return (0 != SSL_pending(BACKEND->handle)) ? TRUE : FALSE;
else
return FALSE;
}
@@ -772,14 +796,14 @@ bool Curl_cyassl_data_pending(const struct connectdata* conn, int connindex)
* This function is called to shut down the SSL layer but keep the
* socket open (CCC - Clear Command Channel)
*/
-int Curl_cyassl_shutdown(struct connectdata *conn, int sockindex)
+static int Curl_cyassl_shutdown(struct connectdata *conn, int sockindex)
{
int retval = 0;
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
- if(connssl->handle) {
- SSL_free(connssl->handle);
- connssl->handle = NULL;
+ if(BACKEND->handle) {
+ SSL_free(BACKEND->handle);
+ BACKEND->handle = NULL;
}
return retval;
}
@@ -804,7 +828,7 @@ cyassl_connect_common(struct connectdata *conn,
return CURLE_OK;
}
- if(ssl_connect_1==connssl->connecting_state) {
+ if(ssl_connect_1 == connssl->connecting_state) {
/* Find out how much more time we're allowed */
timeout_ms = Curl_timeleft(data, NULL, TRUE);
@@ -836,9 +860,9 @@ cyassl_connect_common(struct connectdata *conn,
if(connssl->connecting_state == ssl_connect_2_reading
|| connssl->connecting_state == ssl_connect_2_writing) {
- curl_socket_t writefd = ssl_connect_2_writing==
+ curl_socket_t writefd = ssl_connect_2_writing ==
connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
- curl_socket_t readfd = ssl_connect_2_reading==
+ curl_socket_t readfd = ssl_connect_2_reading ==
connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
@@ -899,18 +923,14 @@ cyassl_connect_common(struct connectdata *conn,
}
-CURLcode
-Curl_cyassl_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done)
+static CURLcode Curl_cyassl_connect_nonblocking(struct connectdata *conn,
+ int sockindex, bool *done)
{
return cyassl_connect_common(conn, sockindex, TRUE, done);
}
-CURLcode
-Curl_cyassl_connect(struct connectdata *conn,
- int sockindex)
+static CURLcode Curl_cyassl_connect(struct connectdata *conn, int sockindex)
{
CURLcode result;
bool done = FALSE;
@@ -924,9 +944,8 @@ Curl_cyassl_connect(struct connectdata *conn,
return CURLE_OK;
}
-CURLcode Curl_cyassl_random(struct Curl_easy *data,
- unsigned char *entropy,
- size_t length)
+static CURLcode Curl_cyassl_random(struct Curl_easy *data,
+ unsigned char *entropy, size_t length)
{
RNG rng;
(void)data;
@@ -939,10 +958,10 @@ CURLcode Curl_cyassl_random(struct Curl_easy *data,
return CURLE_OK;
}
-void Curl_cyassl_sha256sum(const unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *sha256sum /* output */,
- size_t unused)
+static void Curl_cyassl_sha256sum(const unsigned char *tmp, /* input */
+ size_t tmplen,
+ unsigned char *sha256sum /* output */,
+ size_t unused)
{
Sha256 SHA256pw;
(void)unused;
@@ -951,4 +970,48 @@ void Curl_cyassl_sha256sum(const unsigned char *tmp, /* input */
Sha256Final(&SHA256pw, sha256sum);
}
+static void *Curl_cyassl_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info UNUSED_PARAM)
+{
+ (void)info;
+ return BACKEND->handle;
+}
+
+const struct Curl_ssl Curl_ssl_cyassl = {
+ { CURLSSLBACKEND_WOLFSSL, "WolfSSL" }, /* info */
+
+ 0, /* have_ca_path */
+ 0, /* have_certinfo */
+#ifdef KEEP_PEER_CERT
+ 1, /* have_pinnedpubkey */
+#else
+ 0, /* have_pinnedpubkey */
+#endif
+ 1, /* have_ssl_ctx */
+ 0, /* support_https_proxy */
+
+ sizeof(struct ssl_backend_data),
+
+ Curl_cyassl_init, /* init */
+ Curl_none_cleanup, /* cleanup */
+ Curl_cyassl_version, /* version */
+ Curl_none_check_cxn, /* check_cxn */
+ Curl_cyassl_shutdown, /* shutdown */
+ Curl_cyassl_data_pending, /* data_pending */
+ Curl_cyassl_random, /* random */
+ Curl_none_cert_status_request, /* cert_status_request */
+ Curl_cyassl_connect, /* connect */
+ Curl_cyassl_connect_nonblocking, /* connect_nonblocking */
+ Curl_cyassl_get_internals, /* get_internals */
+ Curl_cyassl_close, /* close */
+ Curl_none_close_all, /* close_all */
+ Curl_cyassl_session_free, /* session_free */
+ Curl_none_set_engine, /* set_engine */
+ Curl_none_set_engine_default, /* set_engine_default */
+ Curl_none_engines_list, /* engines_list */
+ Curl_none_false_start, /* false_start */
+ Curl_none_md5sum, /* md5sum */
+ Curl_cyassl_sha256sum /* sha256sum */
+};
+
#endif
diff --git a/Utilities/cmcurl/lib/vtls/cyassl.h b/Utilities/cmcurl/lib/vtls/cyassl.h
index f47719e4e..01e11cc23 100644
--- a/Utilities/cmcurl/lib/vtls/cyassl.h
+++ b/Utilities/cmcurl/lib/vtls/cyassl.h
@@ -25,68 +25,7 @@
#ifdef USE_CYASSL
-/* KEEP_PEER_CERT is a product of the presence of build time symbol
- OPENSSL_EXTRA without NO_CERTS, depending on the version. KEEP_PEER_CERT is
- in wolfSSL's settings.h, and the latter two are build time symbols in
- options.h. */
-#ifndef KEEP_PEER_CERT
-#if defined(HAVE_CYASSL_GET_PEER_CERTIFICATE) || \
- defined(HAVE_WOLFSSL_GET_PEER_CERTIFICATE) || \
- (defined(OPENSSL_EXTRA) && !defined(NO_CERTS))
-#define KEEP_PEER_CERT
-#endif
-#endif
-
-CURLcode Curl_cyassl_connect(struct connectdata *conn, int sockindex);
-bool Curl_cyassl_data_pending(const struct connectdata* conn, int connindex);
-int Curl_cyassl_shutdown(struct connectdata* conn, int sockindex);
-
- /* close a SSL connection */
-void Curl_cyassl_close(struct connectdata *conn, int sockindex);
-
-void Curl_cyassl_session_free(void *ptr);
-size_t Curl_cyassl_version(char *buffer, size_t size);
-int Curl_cyassl_shutdown(struct connectdata *conn, int sockindex);
-int Curl_cyassl_init(void);
-CURLcode Curl_cyassl_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done);
-CURLcode Curl_cyassl_random(struct Curl_easy *data,
- unsigned char *entropy,
- size_t length);
-void Curl_cyassl_sha256sum(const unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *sha256sum, /* output */
- size_t unused);
-
-/* Set the API backend definition to CyaSSL */
-#define CURL_SSL_BACKEND CURLSSLBACKEND_CYASSL
-
-/* this backend supports CURLOPT_SSL_CTX_* */
-#define have_curlssl_ssl_ctx 1
-
-#ifdef KEEP_PEER_CERT
-/* this backend supports CURLOPT_PINNEDPUBLICKEY */
-#define have_curlssl_pinnedpubkey 1
-#endif
-
-/* API setup for CyaSSL */
-#define curlssl_init Curl_cyassl_init
-#define curlssl_cleanup() Curl_nop_stmt
-#define curlssl_connect Curl_cyassl_connect
-#define curlssl_connect_nonblocking Curl_cyassl_connect_nonblocking
-#define curlssl_session_free(x) Curl_cyassl_session_free(x)
-#define curlssl_close_all(x) ((void)x)
-#define curlssl_close Curl_cyassl_close
-#define curlssl_shutdown(x,y) Curl_cyassl_shutdown(x,y)
-#define curlssl_set_engine(x,y) ((void)x, (void)y, CURLE_NOT_BUILT_IN)
-#define curlssl_set_engine_default(x) ((void)x, CURLE_NOT_BUILT_IN)
-#define curlssl_engines_list(x) ((void)x, (struct curl_slist *)NULL)
-#define curlssl_version Curl_cyassl_version
-#define curlssl_check_cxn(x) ((void)x, -1)
-#define curlssl_data_pending(x,y) Curl_cyassl_data_pending(x,y)
-#define curlssl_random(x,y,z) Curl_cyassl_random(x,y,z)
-#define curlssl_sha256sum(a,b,c,d) Curl_cyassl_sha256sum(a,b,c,d)
+extern const struct Curl_ssl Curl_ssl_cyassl;
#endif /* USE_CYASSL */
#endif /* HEADER_CURL_CYASSL_H */
diff --git a/Utilities/cmcurl/lib/vtls/darwinssl.c b/Utilities/cmcurl/lib/vtls/darwinssl.c
index 041766541..a98f43307 100644
--- a/Utilities/cmcurl/lib/vtls/darwinssl.c
+++ b/Utilities/cmcurl/lib/vtls/darwinssl.c
@@ -34,11 +34,18 @@
#ifdef USE_DARWINSSL
+#ifdef __clang__
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wtautological-pointer-compare"
+#endif /* __clang__ */
+
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#include <Security/Security.h>
+/* For some reason, when building for iOS, the omnibus header above does
+ * not include SecureTransport.h as of iOS SDK 5.1. */
#include <Security/SecureTransport.h>
#include <CoreFoundation/CoreFoundation.h>
#include <CommonCrypto/CommonDigest.h>
@@ -113,6 +120,33 @@
#define ioErr -36
#define paramErr -50
+struct ssl_backend_data {
+ SSLContextRef ssl_ctx;
+ curl_socket_t ssl_sockfd;
+ bool ssl_direction; /* true if writing, false if reading */
+ size_t ssl_write_buffered_length;
+};
+
+#define BACKEND connssl->backend
+
+/* pinned public key support tests */
+
+/* version 1 supports macOS 10.12+ and iOS 10+ */
+#if ((TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000) || \
+ (!TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200))
+#define DARWIN_SSL_PINNEDPUBKEY_V1 1
+#endif
+
+/* version 2 supports MacOSX 10.7+ */
+#if (!TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070)
+#define DARWIN_SSL_PINNEDPUBKEY_V2 1
+#endif
+
+#if defined(DARWIN_SSL_PINNEDPUBKEY_V1) || defined(DARWIN_SSL_PINNEDPUBKEY_V2)
+/* this backend supports CURLOPT_PINNEDPUBLICKEY */
+#define DARWIN_SSL_PINNEDPUBKEY 1
+#endif /* DARWIN_SSL_PINNEDPUBKEY */
+
#ifdef DARWIN_SSL_PINNEDPUBKEY
/* both new and old APIs return rsa keys missing the spki header (not DER) */
static const unsigned char rsa4096SpkiHeader[] = {
@@ -156,7 +190,7 @@ static OSStatus SocketRead(SSLConnectionRef connection,
UInt8 *currData = (UInt8 *)data;
/*int sock = *(int *)connection;*/
struct ssl_connect_data *connssl = (struct ssl_connect_data *)connection;
- int sock = connssl->ssl_sockfd;
+ int sock = BACKEND->ssl_sockfd;
OSStatus rtn = noErr;
size_t bytesRead;
ssize_t rrtn;
@@ -185,7 +219,7 @@ static OSStatus SocketRead(SSLConnectionRef connection,
break;
case EAGAIN:
rtn = errSSLWouldBlock;
- connssl->ssl_direction = false;
+ BACKEND->ssl_direction = false;
break;
default:
rtn = ioErr;
@@ -216,7 +250,7 @@ static OSStatus SocketWrite(SSLConnectionRef connection,
size_t bytesSent = 0;
/*int sock = *(int *)connection;*/
struct ssl_connect_data *connssl = (struct ssl_connect_data *)connection;
- int sock = connssl->ssl_sockfd;
+ int sock = BACKEND->ssl_sockfd;
ssize_t length;
size_t dataLen = *dataLength;
const UInt8 *dataPtr = (UInt8 *)data;
@@ -236,7 +270,7 @@ static OSStatus SocketWrite(SSLConnectionRef connection,
theErr = errno;
if(theErr == EAGAIN) {
ortn = errSSLWouldBlock;
- connssl->ssl_direction = true;
+ BACKEND->ssl_direction = true;
}
else {
ortn = ioErr;
@@ -844,7 +878,7 @@ CF_INLINE void GetDarwinVersionNumber(int *major, int *minor)
into a string. Some aren't available under iOS or newer cats. So here's
a unified function for getting a string describing the certificate that
ought to work in all cats starting with Leopard. */
-CF_INLINE CFStringRef CopyCertSubject(SecCertificateRef cert)
+CF_INLINE CFStringRef getsubject(SecCertificateRef cert)
{
CFStringRef server_cert_summary = CFSTR("(null)");
@@ -871,6 +905,54 @@ CF_INLINE CFStringRef CopyCertSubject(SecCertificateRef cert)
return server_cert_summary;
}
+static CURLcode CopyCertSubject(struct Curl_easy *data,
+ SecCertificateRef cert, char **certp)
+{
+ CFStringRef c = getsubject(cert);
+ CURLcode result = CURLE_OK;
+ const char *direct;
+ char *cbuf = NULL;
+ *certp = NULL;
+
+ if(!c) {
+ failf(data, "SSL: invalid CA certificate subject");
+ return CURLE_OUT_OF_MEMORY;
+ }
+
+ /* If the subject is already available as UTF-8 encoded (ie 'direct') then
+ use that, else convert it. */
+ direct = CFStringGetCStringPtr(c, kCFStringEncodingUTF8);
+ if(direct) {
+ *certp = strdup(direct);
+ if(!*certp) {
+ failf(data, "SSL: out of memory");
+ result = CURLE_OUT_OF_MEMORY;
+ }
+ }
+ else {
+ size_t cbuf_size = ((size_t)CFStringGetLength(c) * 4) + 1;
+ cbuf = calloc(cbuf_size, 1);
+ if(cbuf) {
+ if(!CFStringGetCString(c, cbuf, cbuf_size,
+ kCFStringEncodingUTF8)) {
+ failf(data, "SSL: invalid CA certificate subject");
+ result = CURLE_SSL_CACERT;
+ }
+ else
+ /* pass back the buffer */
+ *certp = cbuf;
+ }
+ else {
+ failf(data, "SSL: couldn't allocate %zu bytes of memory", cbuf_size);
+ result = CURLE_OUT_OF_MEMORY;
+ }
+ }
+ if(result)
+ free(cbuf);
+ CFRelease(c);
+ return result;
+}
+
#if CURL_SUPPORT_MAC_10_6
/* The SecKeychainSearch API was deprecated in Lion, and using it will raise
deprecation warnings, so let's not compile this unless it's necessary: */
@@ -963,7 +1045,7 @@ static OSStatus CopyIdentityWithLabel(char *label,
keys_list_count = CFArrayGetCount(keys_list);
*out_cert_and_key = NULL;
status = 1;
- for(i=0; i<keys_list_count; i++) {
+ for(i = 0; i<keys_list_count; i++) {
OSStatus err = noErr;
SecCertificateRef cert = NULL;
SecIdentityRef identity =
@@ -1075,7 +1157,8 @@ CF_INLINE bool is_file(const char *filename)
}
#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
-static CURLcode darwinssl_version_from_curl(long *darwinver, long ssl_version)
+static CURLcode darwinssl_version_from_curl(SSLProtocol *darwinver,
+ long ssl_version)
{
switch(ssl_version) {
case CURL_SSLVERSION_TLSv1_0:
@@ -1136,30 +1219,30 @@ set_ssl_version_min_max(struct connectdata *conn, int sockindex)
return result;
}
- (void)SSLSetProtocolVersionMin(connssl->ssl_ctx, darwin_ver_min);
- (void)SSLSetProtocolVersionMax(connssl->ssl_ctx, darwin_ver_max);
+ (void)SSLSetProtocolVersionMin(BACKEND->ssl_ctx, darwin_ver_min);
+ (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, darwin_ver_max);
return result;
}
else {
#if CURL_SUPPORT_MAC_10_8
long i = ssl_version;
- (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kSSLProtocolAll,
false);
for(; i <= (ssl_version_max >> 16); i++) {
switch(i) {
case CURL_SSLVERSION_TLSv1_0:
- (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kTLSProtocol1,
true);
break;
case CURL_SSLVERSION_TLSv1_1:
- (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kTLSProtocol11,
true);
break;
case CURL_SSLVERSION_TLSv1_2:
- (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kTLSProtocol12,
true);
break;
@@ -1205,10 +1288,10 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
if(SSLCreateContext != NULL) { /* use the newer API if avaialble */
- if(connssl->ssl_ctx)
- CFRelease(connssl->ssl_ctx);
- connssl->ssl_ctx = SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType);
- if(!connssl->ssl_ctx) {
+ if(BACKEND->ssl_ctx)
+ CFRelease(BACKEND->ssl_ctx);
+ BACKEND->ssl_ctx = SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType);
+ if(!BACKEND->ssl_ctx) {
failf(data, "SSL: couldn't create a context!");
return CURLE_OUT_OF_MEMORY;
}
@@ -1216,9 +1299,9 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
else {
/* The old ST API does not exist under iOS, so don't compile it: */
#if CURL_SUPPORT_MAC_10_8
- if(connssl->ssl_ctx)
- (void)SSLDisposeContext(connssl->ssl_ctx);
- err = SSLNewContext(false, &(connssl->ssl_ctx));
+ if(BACKEND->ssl_ctx)
+ (void)SSLDisposeContext(BACKEND->ssl_ctx);
+ err = SSLNewContext(false, &(BACKEND->ssl_ctx));
if(err != noErr) {
failf(data, "SSL: couldn't create a context: OSStatus %d", err);
return CURLE_OUT_OF_MEMORY;
@@ -1226,15 +1309,15 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
#endif /* CURL_SUPPORT_MAC_10_8 */
}
#else
- if(connssl->ssl_ctx)
- (void)SSLDisposeContext(connssl->ssl_ctx);
- err = SSLNewContext(false, &(connssl->ssl_ctx));
+ if(BACKEND->ssl_ctx)
+ (void)SSLDisposeContext(BACKEND->ssl_ctx);
+ err = SSLNewContext(false, &(BACKEND->ssl_ctx));
if(err != noErr) {
failf(data, "SSL: couldn't create a context: OSStatus %d", err);
return CURLE_OUT_OF_MEMORY;
}
#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */
- connssl->ssl_write_buffered_length = 0UL; /* reset buffered write length */
+ BACKEND->ssl_write_buffered_length = 0UL; /* reset buffered write length */
/* check to see if we've been told to use an explicit SSL/TLS version */
#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
@@ -1242,8 +1325,8 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
switch(conn->ssl_config.version) {
case CURL_SSLVERSION_DEFAULT:
case CURL_SSLVERSION_TLSv1:
- (void)SSLSetProtocolVersionMin(connssl->ssl_ctx, kTLSProtocol1);
- (void)SSLSetProtocolVersionMax(connssl->ssl_ctx, kTLSProtocol12);
+ (void)SSLSetProtocolVersionMin(BACKEND->ssl_ctx, kTLSProtocol1);
+ (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, kTLSProtocol12);
break;
case CURL_SSLVERSION_TLSv1_0:
case CURL_SSLVERSION_TLSv1_1:
@@ -1256,20 +1339,20 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
break;
}
case CURL_SSLVERSION_SSLv3:
- err = SSLSetProtocolVersionMin(connssl->ssl_ctx, kSSLProtocol3);
+ err = SSLSetProtocolVersionMin(BACKEND->ssl_ctx, kSSLProtocol3);
if(err != noErr) {
failf(data, "Your version of the OS does not support SSLv3");
return CURLE_SSL_CONNECT_ERROR;
}
- (void)SSLSetProtocolVersionMax(connssl->ssl_ctx, kSSLProtocol3);
+ (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, kSSLProtocol3);
break;
case CURL_SSLVERSION_SSLv2:
- err = SSLSetProtocolVersionMin(connssl->ssl_ctx, kSSLProtocol2);
+ err = SSLSetProtocolVersionMin(BACKEND->ssl_ctx, kSSLProtocol2);
if(err != noErr) {
failf(data, "Your version of the OS does not support SSLv2");
return CURLE_SSL_CONNECT_ERROR;
}
- (void)SSLSetProtocolVersionMax(connssl->ssl_ctx, kSSLProtocol2);
+ (void)SSLSetProtocolVersionMax(BACKEND->ssl_ctx, kSSLProtocol2);
break;
default:
failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
@@ -1278,19 +1361,19 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
}
else {
#if CURL_SUPPORT_MAC_10_8
- (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kSSLProtocolAll,
false);
switch(conn->ssl_config.version) {
case CURL_SSLVERSION_DEFAULT:
case CURL_SSLVERSION_TLSv1:
- (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kTLSProtocol1,
true);
- (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kTLSProtocol11,
true);
- (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kTLSProtocol12,
true);
break;
@@ -1305,7 +1388,7 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
break;
}
case CURL_SSLVERSION_SSLv3:
- err = SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ err = SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kSSLProtocol3,
true);
if(err != noErr) {
@@ -1314,7 +1397,7 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
}
break;
case CURL_SSLVERSION_SSLv2:
- err = SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ err = SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kSSLProtocol2,
true);
if(err != noErr) {
@@ -1334,12 +1417,12 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
" SSL/TLS version");
return CURLE_SSL_CONNECT_ERROR;
}
- (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx, kSSLProtocolAll, false);
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx, kSSLProtocolAll, false);
switch(conn->ssl_config.version) {
case CURL_SSLVERSION_DEFAULT:
case CURL_SSLVERSION_TLSv1:
case CURL_SSLVERSION_TLSv1_0:
- (void)SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ (void)SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kTLSProtocol1,
true);
break;
@@ -1353,7 +1436,7 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
failf(data, "Your version of the OS does not support TLSv1.3");
return CURLE_SSL_CONNECT_ERROR;
case CURL_SSLVERSION_SSLv2:
- err = SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ err = SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kSSLProtocol2,
true);
if(err != noErr) {
@@ -1362,7 +1445,7 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
}
break;
case CURL_SSLVERSION_SSLv3:
- err = SSLSetProtocolVersionEnabled(connssl->ssl_ctx,
+ err = SSLSetProtocolVersionEnabled(BACKEND->ssl_ctx,
kSSLProtocol3,
true);
if(err != noErr) {
@@ -1412,25 +1495,21 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
/* If we found one, print it out: */
err = SecIdentityCopyCertificate(cert_and_key, &cert);
if(err == noErr) {
- CFStringRef cert_summary = CopyCertSubject(cert);
- char cert_summary_c[128];
-
- if(cert_summary) {
- memset(cert_summary_c, 0, 128);
- if(CFStringGetCString(cert_summary,
- cert_summary_c,
- 128,
- kCFStringEncodingUTF8)) {
- infof(data, "Client certificate: %s\n", cert_summary_c);
- }
- CFRelease(cert_summary);
- CFRelease(cert);
+ char *certp;
+ CURLcode result = CopyCertSubject(data, cert, &certp);
+ if(!result) {
+ infof(data, "Client certificate: %s\n", certp);
+ free(certp);
}
+
+ CFRelease(cert);
+ if(result)
+ return result;
}
certs_c[0] = cert_and_key;
certs = CFArrayCreate(NULL, (const void **)certs_c, 1L,
&kCFTypeArrayCallBacks);
- err = SSLSetCertificate(connssl->ssl_ctx, certs);
+ err = SSLSetCertificate(BACKEND->ssl_ctx, certs);
if(certs)
CFRelease(certs);
if(err != noErr) {
@@ -1493,7 +1572,7 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
if(SSLSetSessionOption != NULL) {
#endif /* CURL_BUILD_MAC */
bool break_on_auth = !conn->ssl_config.verifypeer || ssl_cafile;
- err = SSLSetSessionOption(connssl->ssl_ctx,
+ err = SSLSetSessionOption(BACKEND->ssl_ctx,
kSSLSessionOptionBreakOnServerAuth,
break_on_auth);
if(err != noErr) {
@@ -1503,7 +1582,7 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
}
else {
#if CURL_SUPPORT_MAC_10_8
- err = SSLSetEnableCertVerify(connssl->ssl_ctx,
+ err = SSLSetEnableCertVerify(BACKEND->ssl_ctx,
conn->ssl_config.verifypeer?true:false);
if(err != noErr) {
failf(data, "SSL: SSLSetEnableCertVerify() failed: OSStatus %d", err);
@@ -1512,7 +1591,7 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
#endif /* CURL_SUPPORT_MAC_10_8 */
}
#else
- err = SSLSetEnableCertVerify(connssl->ssl_ctx,
+ err = SSLSetEnableCertVerify(BACKEND->ssl_ctx,
conn->ssl_config.verifypeer?true:false);
if(err != noErr) {
failf(data, "SSL: SSLSetEnableCertVerify() failed: OSStatus %d", err);
@@ -1533,7 +1612,7 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
* Both hostname check and SNI require SSLSetPeerDomainName().
* Also: the verifyhost setting influences SNI usage */
if(conn->ssl_config.verifyhost) {
- err = SSLSetPeerDomainName(connssl->ssl_ctx, hostname,
+ err = SSLSetPeerDomainName(BACKEND->ssl_ctx, hostname,
strlen(hostname));
if(err != noErr) {
@@ -1559,11 +1638,11 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
higher priority, but it's probably better that we not connect at all than
to give the user a false sense of security if the server only supports
insecure ciphers. (Note: We don't care about SSLv2-only ciphers.) */
- (void)SSLGetNumberSupportedCiphers(connssl->ssl_ctx, &all_ciphers_count);
+ (void)SSLGetNumberSupportedCiphers(BACKEND->ssl_ctx, &all_ciphers_count);
all_ciphers = malloc(all_ciphers_count*sizeof(SSLCipherSuite));
allowed_ciphers = malloc(all_ciphers_count*sizeof(SSLCipherSuite));
if(all_ciphers && allowed_ciphers &&
- SSLGetSupportedCiphers(connssl->ssl_ctx, all_ciphers,
+ SSLGetSupportedCiphers(BACKEND->ssl_ctx, all_ciphers,
&all_ciphers_count) == noErr) {
for(i = 0UL ; i < all_ciphers_count ; i++) {
#if CURL_BUILD_MAC
@@ -1645,7 +1724,7 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
break;
}
}
- err = SSLSetEnabledCiphers(connssl->ssl_ctx, allowed_ciphers,
+ err = SSLSetEnabledCiphers(BACKEND->ssl_ctx, allowed_ciphers,
allowed_ciphers_count);
if(err != noErr) {
failf(data, "SSL: SSLSetEnabledCiphers() failed: OSStatus %d", err);
@@ -1666,9 +1745,9 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
specifically doesn't want us doing that: */
if(SSLSetSessionOption != NULL) {
/* TODO s/data->set.ssl.enable_beast/SSL_SET_OPTION(enable_beast)/g */
- SSLSetSessionOption(connssl->ssl_ctx, kSSLSessionOptionSendOneByteRecord,
+ SSLSetSessionOption(BACKEND->ssl_ctx, kSSLSessionOptionSendOneByteRecord,
!data->set.ssl.enable_beast);
- SSLSetSessionOption(connssl->ssl_ctx, kSSLSessionOptionFalseStart,
+ SSLSetSessionOption(BACKEND->ssl_ctx, kSSLSessionOptionFalseStart,
data->set.ssl.falsestart); /* false start support */
}
#endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */
@@ -1682,7 +1761,7 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
if(!Curl_ssl_getsessionid(conn, (void **)&ssl_sessionid,
&ssl_sessionid_len, sockindex)) {
/* we got a session id, use it! */
- err = SSLSetPeerID(connssl->ssl_ctx, ssl_sessionid, ssl_sessionid_len);
+ err = SSLSetPeerID(BACKEND->ssl_ctx, ssl_sessionid, ssl_sessionid_len);
Curl_ssl_sessionid_unlock(conn);
if(err != noErr) {
failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err);
@@ -1700,7 +1779,7 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
verifypeer, SSL_CONN_CONFIG(verifyhost), hostname, port);
ssl_sessionid_len = strlen(ssl_sessionid);
- err = SSLSetPeerID(connssl->ssl_ctx, ssl_sessionid, ssl_sessionid_len);
+ err = SSLSetPeerID(BACKEND->ssl_ctx, ssl_sessionid, ssl_sessionid_len);
if(err != noErr) {
Curl_ssl_sessionid_unlock(conn);
failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err);
@@ -1717,7 +1796,7 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
}
}
- err = SSLSetIOFuncs(connssl->ssl_ctx, SocketRead, SocketWrite);
+ err = SSLSetIOFuncs(BACKEND->ssl_ctx, SocketRead, SocketWrite);
if(err != noErr) {
failf(data, "SSL: SSLSetIOFuncs() failed: OSStatus %d", err);
return CURLE_SSL_CONNECT_ERROR;
@@ -1727,8 +1806,8 @@ static CURLcode darwinssl_connect_step1(struct connectdata *conn,
/* We need to store the FD in a constant memory address, because
* SSLSetConnection() will not copy that address. I've found that
* conn->sock[sockindex] may change on its own. */
- connssl->ssl_sockfd = sockfd;
- err = SSLSetConnection(connssl->ssl_ctx, connssl);
+ BACKEND->ssl_sockfd = sockfd;
+ err = SSLSetConnection(BACKEND->ssl_ctx, connssl);
if(err != noErr) {
failf(data, "SSL: SSLSetConnection() failed: %d", err);
return CURLE_SSL_CONNECT_ERROR;
@@ -1791,7 +1870,7 @@ static int read_cert(const char *file, unsigned char **out, size_t *outlen)
{
int fd;
ssize_t n, len = 0, cap = 512;
- unsigned char buf[cap], *data;
+ unsigned char buf[512], *data;
fd = open(file, 0);
if(fd < 0)
@@ -1869,6 +1948,8 @@ static int append_cert_to_array(struct Curl_easy *data,
CFMutableArrayRef array)
{
CFDataRef certdata = CFDataCreate(kCFAllocatorDefault, buf, buflen);
+ char *certp;
+ CURLcode result;
if(!certdata) {
failf(data, "SSL: failed to allocate array for CA certificate");
return CURLE_OUT_OF_MEMORY;
@@ -1883,25 +1964,10 @@ static int append_cert_to_array(struct Curl_easy *data,
}
/* Check if cacert is valid. */
- CFStringRef subject = CopyCertSubject(cacert);
- if(subject) {
- char subject_cbuf[128];
- memset(subject_cbuf, 0, 128);
- if(!CFStringGetCString(subject,
- subject_cbuf,
- 128,
- kCFStringEncodingUTF8)) {
- CFRelease(cacert);
- failf(data, "SSL: invalid CA certificate subject");
- return CURLE_SSL_CACERT;
- }
- CFRelease(subject);
- }
- else {
- CFRelease(cacert);
- failf(data, "SSL: invalid CA certificate");
- return CURLE_SSL_CACERT;
- }
+ result = CopyCertSubject(data, cacert, &certp);
+ if(result)
+ return result;
+ free(certp);
CFArrayAppendValue(array, cacert);
CFRelease(cacert);
@@ -2027,12 +2093,13 @@ static int verify_cert(const char *cafile, struct Curl_easy *data,
}
#ifdef DARWIN_SSL_PINNEDPUBKEY
-static CURLcode pkp_pin_peer_pubkey(struct SessionHandle *data,
+static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data,
SSLContextRef ctx,
const char *pinnedpubkey)
{ /* Scratch */
size_t pubkeylen, realpubkeylen, spkiHeaderLength = 24;
- unsigned char *pubkey = NULL, *realpubkey = NULL, *spkiHeader = NULL;
+ unsigned char *pubkey = NULL, *realpubkey = NULL;
+ const unsigned char *spkiHeader = NULL;
CFDataRef publicKeyBits = NULL;
/* Result is returned to caller */
@@ -2075,7 +2142,7 @@ static CURLcode pkp_pin_peer_pubkey(struct SessionHandle *data,
#endif /* DARWIN_SSL_PINNEDPUBKEY_V2 */
pubkeylen = CFDataGetLength(publicKeyBits);
- pubkey = CFDataGetBytePtr(publicKeyBits);
+ pubkey = (unsigned char *)CFDataGetBytePtr(publicKeyBits);
switch(pubkeylen) {
case 526:
@@ -2148,12 +2215,12 @@ darwinssl_connect_step2(struct connectdata *conn, int sockindex)
|| ssl_connect_2_writing == connssl->connecting_state);
/* Here goes nothing: */
- err = SSLHandshake(connssl->ssl_ctx);
+ err = SSLHandshake(BACKEND->ssl_ctx);
if(err != noErr) {
switch(err) {
case errSSLWouldBlock: /* they're not done with us yet */
- connssl->connecting_state = connssl->ssl_direction ?
+ connssl->connecting_state = BACKEND->ssl_direction ?
ssl_connect_2_writing : ssl_connect_2_reading;
return CURLE_OK;
@@ -2162,7 +2229,7 @@ darwinssl_connect_step2(struct connectdata *conn, int sockindex)
case -9841:
if(SSL_CONN_CONFIG(CAfile) && SSL_CONN_CONFIG(verifypeer)) {
int res = verify_cert(SSL_CONN_CONFIG(CAfile), data,
- connssl->ssl_ctx);
+ BACKEND->ssl_ctx);
if(res != CURLE_OK)
return res;
}
@@ -2240,7 +2307,7 @@ darwinssl_connect_step2(struct connectdata *conn, int sockindex)
#ifdef DARWIN_SSL_PINNEDPUBKEY
if(data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]) {
- CURLcode result = pkp_pin_peer_pubkey(data, connssl->ssl_ctx,
+ CURLcode result = pkp_pin_peer_pubkey(data, BACKEND->ssl_ctx,
data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG]);
if(result) {
failf(data, "SSL: public key does not match pinned public key!");
@@ -2250,8 +2317,8 @@ darwinssl_connect_step2(struct connectdata *conn, int sockindex)
#endif /* DARWIN_SSL_PINNEDPUBKEY */
/* Informational message */
- (void)SSLGetNegotiatedCipher(connssl->ssl_ctx, &cipher);
- (void)SSLGetNegotiatedProtocolVersion(connssl->ssl_ctx, &protocol);
+ (void)SSLGetNegotiatedCipher(BACKEND->ssl_ctx, &cipher);
+ (void)SSLGetNegotiatedProtocolVersion(BACKEND->ssl_ctx, &protocol);
switch(protocol) {
case kSSLProtocol2:
infof(data, "SSL 2.0 connection using %s\n",
@@ -2292,36 +2359,32 @@ show_verbose_server_cert(struct connectdata *conn,
{
struct Curl_easy *data = conn->data;
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
- CFStringRef server_cert_summary;
- char server_cert_summary_c[128];
CFArrayRef server_certs = NULL;
SecCertificateRef server_cert;
OSStatus err;
CFIndex i, count;
SecTrustRef trust = NULL;
- if(!connssl->ssl_ctx)
+ if(!BACKEND->ssl_ctx)
return;
#if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS
#if CURL_BUILD_IOS
#pragma unused(server_certs)
- err = SSLCopyPeerTrust(connssl->ssl_ctx, &trust);
+ err = SSLCopyPeerTrust(BACKEND->ssl_ctx, &trust);
/* For some reason, SSLCopyPeerTrust() can return noErr and yet return
a null trust, so be on guard for that: */
if(err == noErr && trust) {
count = SecTrustGetCertificateCount(trust);
for(i = 0L ; i < count ; i++) {
+ CURLcode result;
+ char *certp;
server_cert = SecTrustGetCertificateAtIndex(trust, i);
- server_cert_summary = CopyCertSubject(server_cert);
- memset(server_cert_summary_c, 0, 128);
- if(CFStringGetCString(server_cert_summary,
- server_cert_summary_c,
- 128,
- kCFStringEncodingUTF8)) {
- infof(data, "Server certificate: %s\n", server_cert_summary_c);
+ result = CopyCertSubject(data, server_cert, &certp);
+ if(!result) {
+ infof(data, "Server certificate: %s\n", certp);
+ free(certp);
}
- CFRelease(server_cert_summary);
}
CFRelease(trust);
}
@@ -2334,45 +2397,40 @@ show_verbose_server_cert(struct connectdata *conn,
Lion or later. */
if(SecTrustEvaluateAsync != NULL) {
#pragma unused(server_certs)
- err = SSLCopyPeerTrust(connssl->ssl_ctx, &trust);
+ err = SSLCopyPeerTrust(BACKEND->ssl_ctx, &trust);
/* For some reason, SSLCopyPeerTrust() can return noErr and yet return
a null trust, so be on guard for that: */
if(err == noErr && trust) {
count = SecTrustGetCertificateCount(trust);
for(i = 0L ; i < count ; i++) {
+ char *certp;
+ CURLcode result;
server_cert = SecTrustGetCertificateAtIndex(trust, i);
- server_cert_summary = CopyCertSubject(server_cert);
- memset(server_cert_summary_c, 0, 128);
- if(CFStringGetCString(server_cert_summary,
- server_cert_summary_c,
- 128,
- kCFStringEncodingUTF8)) {
- infof(data, "Server certificate: %s\n", server_cert_summary_c);
+ result = CopyCertSubject(data, server_cert, &certp);
+ if(!result) {
+ infof(data, "Server certificate: %s\n", certp);
+ free(certp);
}
- CFRelease(server_cert_summary);
}
CFRelease(trust);
}
}
else {
#if CURL_SUPPORT_MAC_10_8
- err = SSLCopyPeerCertificates(connssl->ssl_ctx, &server_certs);
+ err = SSLCopyPeerCertificates(BACKEND->ssl_ctx, &server_certs);
/* Just in case SSLCopyPeerCertificates() returns null too... */
if(err == noErr && server_certs) {
count = CFArrayGetCount(server_certs);
for(i = 0L ; i < count ; i++) {
+ char *certp;
+ CURLcode result;
server_cert = (SecCertificateRef)CFArrayGetValueAtIndex(server_certs,
i);
-
- server_cert_summary = CopyCertSubject(server_cert);
- memset(server_cert_summary_c, 0, 128);
- if(CFStringGetCString(server_cert_summary,
- server_cert_summary_c,
- 128,
- kCFStringEncodingUTF8)) {
- infof(data, "Server certificate: %s\n", server_cert_summary_c);
+ result = CopyCertSubject(data, server_cert, &certp);
+ if(!result) {
+ infof(data, "Server certificate: %s\n", certp);
+ free(certp);
}
- CFRelease(server_cert_summary);
}
CFRelease(server_certs);
}
@@ -2381,20 +2439,18 @@ show_verbose_server_cert(struct connectdata *conn,
#endif /* CURL_BUILD_IOS */
#else
#pragma unused(trust)
- err = SSLCopyPeerCertificates(connssl->ssl_ctx, &server_certs);
+ err = SSLCopyPeerCertificates(BACKEND->ssl_ctx, &server_certs);
if(err == noErr) {
count = CFArrayGetCount(server_certs);
for(i = 0L ; i < count ; i++) {
+ CURLcode result;
+ char *certp;
server_cert = (SecCertificateRef)CFArrayGetValueAtIndex(server_certs, i);
- server_cert_summary = CopyCertSubject(server_cert);
- memset(server_cert_summary_c, 0, 128);
- if(CFStringGetCString(server_cert_summary,
- server_cert_summary_c,
- 128,
- kCFStringEncodingUTF8)) {
- infof(data, "Server certificate: %s\n", server_cert_summary_c);
+ result = CopyCertSubject(data, server_cert, &certp);
+ if(!result) {
+ infof(data, "Server certificate: %s\n", certp);
+ free(certp);
}
- CFRelease(server_cert_summary);
}
CFRelease(server_certs);
}
@@ -2443,7 +2499,7 @@ darwinssl_connect_common(struct connectdata *conn,
return CURLE_OK;
}
- if(ssl_connect_1==connssl->connecting_state) {
+ if(ssl_connect_1 == connssl->connecting_state) {
/* Find out how much more time we're allowed */
timeout_ms = Curl_timeleft(data, NULL, TRUE);
@@ -2538,17 +2594,13 @@ darwinssl_connect_common(struct connectdata *conn,
return CURLE_OK;
}
-CURLcode
-Curl_darwinssl_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done)
+static CURLcode Curl_darwinssl_connect_nonblocking(struct connectdata *conn,
+ int sockindex, bool *done)
{
return darwinssl_connect_common(conn, sockindex, TRUE, done);
}
-CURLcode
-Curl_darwinssl_connect(struct connectdata *conn,
- int sockindex)
+static CURLcode Curl_darwinssl_connect(struct connectdata *conn, int sockindex)
{
CURLcode result;
bool done = FALSE;
@@ -2563,28 +2615,28 @@ Curl_darwinssl_connect(struct connectdata *conn,
return CURLE_OK;
}
-void Curl_darwinssl_close(struct connectdata *conn, int sockindex)
+static void Curl_darwinssl_close(struct connectdata *conn, int sockindex)
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
- if(connssl->ssl_ctx) {
- (void)SSLClose(connssl->ssl_ctx);
+ if(BACKEND->ssl_ctx) {
+ (void)SSLClose(BACKEND->ssl_ctx);
#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
if(SSLCreateContext != NULL)
- CFRelease(connssl->ssl_ctx);
+ CFRelease(BACKEND->ssl_ctx);
#if CURL_SUPPORT_MAC_10_8
else
- (void)SSLDisposeContext(connssl->ssl_ctx);
+ (void)SSLDisposeContext(BACKEND->ssl_ctx);
#endif /* CURL_SUPPORT_MAC_10_8 */
#else
- (void)SSLDisposeContext(connssl->ssl_ctx);
+ (void)SSLDisposeContext(BACKEND->ssl_ctx);
#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */
- connssl->ssl_ctx = NULL;
+ BACKEND->ssl_ctx = NULL;
}
- connssl->ssl_sockfd = 0;
+ BACKEND->ssl_sockfd = 0;
}
-int Curl_darwinssl_shutdown(struct connectdata *conn, int sockindex)
+static int Curl_darwinssl_shutdown(struct connectdata *conn, int sockindex)
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
struct Curl_easy *data = conn->data;
@@ -2593,7 +2645,7 @@ int Curl_darwinssl_shutdown(struct connectdata *conn, int sockindex)
int rc;
char buf[120];
- if(!connssl->ssl_ctx)
+ if(!BACKEND->ssl_ctx)
return 0;
if(data->set.ftp_ccc != CURLFTPSSL_CCC_ACTIVE)
@@ -2637,7 +2689,7 @@ int Curl_darwinssl_shutdown(struct connectdata *conn, int sockindex)
return rc;
}
-void Curl_darwinssl_session_free(void *ptr)
+static void Curl_darwinssl_session_free(void *ptr)
{
/* ST, as of iOS 5 and Mountain Lion, has no public method of deleting a
cached session ID inside the Security framework. There is a private
@@ -2648,7 +2700,7 @@ void Curl_darwinssl_session_free(void *ptr)
Curl_safefree(ptr);
}
-size_t Curl_darwinssl_version(char *buffer, size_t size)
+static size_t Curl_darwinssl_version(char *buffer, size_t size)
{
return snprintf(buffer, size, "SecureTransport");
}
@@ -2661,14 +2713,14 @@ size_t Curl_darwinssl_version(char *buffer, size_t size)
* 0 means the connection has been closed
* -1 means the connection status is unknown
*/
-int Curl_darwinssl_check_cxn(struct connectdata *conn)
+static int Curl_darwinssl_check_cxn(struct connectdata *conn)
{
struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET];
OSStatus err;
SSLSessionState state;
- if(connssl->ssl_ctx) {
- err = SSLGetSessionState(connssl->ssl_ctx, &state);
+ if(BACKEND->ssl_ctx) {
+ err = SSLGetSessionState(BACKEND->ssl_ctx, &state);
if(err == noErr)
return state == kSSLConnected || state == kSSLHandshake;
return -1;
@@ -2676,15 +2728,15 @@ int Curl_darwinssl_check_cxn(struct connectdata *conn)
return 0;
}
-bool Curl_darwinssl_data_pending(const struct connectdata *conn,
- int connindex)
+static bool Curl_darwinssl_data_pending(const struct connectdata *conn,
+ int connindex)
{
const struct ssl_connect_data *connssl = &conn->ssl[connindex];
OSStatus err;
size_t buffer;
- if(connssl->ssl_ctx) { /* SSL is in use */
- err = SSLGetBufferedReadSize(connssl->ssl_ctx, &buffer);
+ if(BACKEND->ssl_ctx) { /* SSL is in use */
+ err = SSLGetBufferedReadSize(BACKEND->ssl_ctx, &buffer);
if(err == noErr)
return buffer > 0UL;
return false;
@@ -2693,14 +2745,16 @@ bool Curl_darwinssl_data_pending(const struct connectdata *conn,
return false;
}
-CURLcode Curl_darwinssl_random(unsigned char *entropy,
- size_t length)
+static CURLcode Curl_darwinssl_random(struct Curl_easy *data UNUSED_PARAM,
+ unsigned char *entropy, size_t length)
{
/* arc4random_buf() isn't available on cats older than Lion, so let's
do this manually for the benefit of the older cats. */
size_t i;
u_int32_t random_number = 0;
+ (void)data;
+
for(i = 0 ; i < length ; i++) {
if(i % sizeof(u_int32_t) == 0)
random_number = arc4random();
@@ -2711,25 +2765,26 @@ CURLcode Curl_darwinssl_random(unsigned char *entropy,
return CURLE_OK;
}
-void Curl_darwinssl_md5sum(unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *md5sum, /* output */
- size_t md5len)
+static CURLcode Curl_darwinssl_md5sum(unsigned char *tmp, /* input */
+ size_t tmplen,
+ unsigned char *md5sum, /* output */
+ size_t md5len)
{
(void)md5len;
(void)CC_MD5(tmp, (CC_LONG)tmplen, md5sum);
+ return CURLE_OK;
}
-void Curl_darwinssl_sha256sum(unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *sha256sum, /* output */
- size_t sha256len)
+static void Curl_darwinssl_sha256sum(const unsigned char *tmp, /* input */
+ size_t tmplen,
+ unsigned char *sha256sum, /* output */
+ size_t sha256len)
{
- assert(sha256len >= SHA256_DIGEST_LENGTH);
+ assert(sha256len >= CURL_SHA256_DIGEST_LENGTH);
(void)CC_SHA256(tmp, (CC_LONG)tmplen, sha256sum);
}
-bool Curl_darwinssl_false_start(void)
+static bool Curl_darwinssl_false_start(void)
{
#if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7
if(SSLSetSessionOption != NULL)
@@ -2764,15 +2819,15 @@ static ssize_t darwinssl_send(struct connectdata *conn,
over again with no new data until it quits returning errSSLWouldBlock. */
/* Do we have buffered data to write from the last time we were called? */
- if(connssl->ssl_write_buffered_length) {
+ if(BACKEND->ssl_write_buffered_length) {
/* Write the buffered data: */
- err = SSLWrite(connssl->ssl_ctx, NULL, 0UL, &processed);
+ err = SSLWrite(BACKEND->ssl_ctx, NULL, 0UL, &processed);
switch(err) {
case noErr:
/* processed is always going to be 0 because we didn't write to
the buffer, so return how much was written to the socket */
- processed = connssl->ssl_write_buffered_length;
- connssl->ssl_write_buffered_length = 0UL;
+ processed = BACKEND->ssl_write_buffered_length;
+ BACKEND->ssl_write_buffered_length = 0UL;
break;
case errSSLWouldBlock: /* argh, try again */
*curlcode = CURLE_AGAIN;
@@ -2785,13 +2840,13 @@ static ssize_t darwinssl_send(struct connectdata *conn,
}
else {
/* We've got new data to write: */
- err = SSLWrite(connssl->ssl_ctx, mem, len, &processed);
+ err = SSLWrite(BACKEND->ssl_ctx, mem, len, &processed);
if(err != noErr) {
switch(err) {
case errSSLWouldBlock:
/* Data was buffered but not sent, we have to tell the caller
to try sending again, and remember how much was buffered */
- connssl->ssl_write_buffered_length = len;
+ BACKEND->ssl_write_buffered_length = len;
*curlcode = CURLE_AGAIN;
return -1L;
default:
@@ -2813,7 +2868,7 @@ static ssize_t darwinssl_recv(struct connectdata *conn,
/*struct Curl_easy *data = conn->data;*/
struct ssl_connect_data *connssl = &conn->ssl[num];
size_t processed = 0UL;
- OSStatus err = SSLRead(connssl->ssl_ctx, buf, buffersize, &processed);
+ OSStatus err = SSLRead(BACKEND->ssl_ctx, buf, buffersize, &processed);
if(err != noErr) {
switch(err) {
@@ -2844,4 +2899,52 @@ static ssize_t darwinssl_recv(struct connectdata *conn,
return (ssize_t)processed;
}
+static void *Curl_darwinssl_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info UNUSED_PARAM)
+{
+ (void)info;
+ return BACKEND->ssl_ctx;
+}
+
+const struct Curl_ssl Curl_ssl_darwinssl = {
+ { CURLSSLBACKEND_DARWINSSL, "darwinssl" }, /* info */
+
+ 0, /* have_ca_path */
+ 0, /* have_certinfo */
+#ifdef DARWIN_SSL_PINNEDPUBKEY
+ 1, /* have_pinnedpubkey */
+#else
+ 0, /* have_pinnedpubkey */
+#endif /* DARWIN_SSL_PINNEDPUBKEY */
+ 0, /* have_ssl_ctx */
+ 0, /* support_https_proxy */
+
+ sizeof(struct ssl_backend_data),
+
+ Curl_none_init, /* init */
+ Curl_none_cleanup, /* cleanup */
+ Curl_darwinssl_version, /* version */
+ Curl_darwinssl_check_cxn, /* check_cxn */
+ Curl_darwinssl_shutdown, /* shutdown */
+ Curl_darwinssl_data_pending, /* data_pending */
+ Curl_darwinssl_random, /* random */
+ Curl_none_cert_status_request, /* cert_status_request */
+ Curl_darwinssl_connect, /* connect */
+ Curl_darwinssl_connect_nonblocking, /* connect_nonblocking */
+ Curl_darwinssl_get_internals, /* get_internals */
+ Curl_darwinssl_close, /* close */
+ Curl_none_close_all, /* close_all */
+ Curl_darwinssl_session_free, /* session_free */
+ Curl_none_set_engine, /* set_engine */
+ Curl_none_set_engine_default, /* set_engine_default */
+ Curl_none_engines_list, /* engines_list */
+ Curl_darwinssl_false_start, /* false_start */
+ Curl_darwinssl_md5sum, /* md5sum */
+ Curl_darwinssl_sha256sum /* sha256sum */
+};
+
+#ifdef __clang__
+#pragma clang diagnostic pop
+#endif
+
#endif /* USE_DARWINSSL */
diff --git a/Utilities/cmcurl/lib/vtls/darwinssl.h b/Utilities/cmcurl/lib/vtls/darwinssl.h
index fd372ffa0..23c7f705c 100644
--- a/Utilities/cmcurl/lib/vtls/darwinssl.h
+++ b/Utilities/cmcurl/lib/vtls/darwinssl.h
@@ -26,75 +26,7 @@
#ifdef USE_DARWINSSL
-CURLcode Curl_darwinssl_connect(struct connectdata *conn, int sockindex);
-
-CURLcode Curl_darwinssl_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done);
-
-/* close a SSL connection */
-void Curl_darwinssl_close(struct connectdata *conn, int sockindex);
-
-void Curl_darwinssl_session_free(void *ptr);
-size_t Curl_darwinssl_version(char *buffer, size_t size);
-int Curl_darwinssl_shutdown(struct connectdata *conn, int sockindex);
-int Curl_darwinssl_check_cxn(struct connectdata *conn);
-bool Curl_darwinssl_data_pending(const struct connectdata *conn,
- int connindex);
-
-CURLcode Curl_darwinssl_random(unsigned char *entropy,
- size_t length);
-void Curl_darwinssl_md5sum(unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *md5sum, /* output */
- size_t md5len);
-void Curl_darwinssl_sha256sum(unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *sha256sum, /* output */
- size_t sha256len);
-bool Curl_darwinssl_false_start(void);
-
-/* Set the API backend definition to SecureTransport */
-#define CURL_SSL_BACKEND CURLSSLBACKEND_DARWINSSL
-
-/* pinned public key support tests */
-
-/* version 1 supports macOS 10.12+ and iOS 10+ */
-#if ((TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000) || \
- (!TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200))
-#define DARWIN_SSL_PINNEDPUBKEY_V1 1
-#endif
-
-/* version 2 supports MacOSX 10.7+ */
-#if (!TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070)
-#define DARWIN_SSL_PINNEDPUBKEY_V2 1
-#endif
-
-#if defined(DARWIN_SSL_PINNEDPUBKEY_V1) || defined(DARWIN_SSL_PINNEDPUBKEY_V2)
-/* this backend supports CURLOPT_PINNEDPUBLICKEY */
-#define DARWIN_SSL_PINNEDPUBKEY 1
-#define have_curlssl_pinnedpubkey 1
-#endif /* DARWIN_SSL_PINNEDPUBKEY */
-
-/* API setup for SecureTransport */
-#define curlssl_init() (1)
-#define curlssl_cleanup() Curl_nop_stmt
-#define curlssl_connect Curl_darwinssl_connect
-#define curlssl_connect_nonblocking Curl_darwinssl_connect_nonblocking
-#define curlssl_session_free(x) Curl_darwinssl_session_free(x)
-#define curlssl_close_all(x) ((void)x)
-#define curlssl_close Curl_darwinssl_close
-#define curlssl_shutdown(x,y) 0
-#define curlssl_set_engine(x,y) ((void)x, (void)y, CURLE_NOT_BUILT_IN)
-#define curlssl_set_engine_default(x) ((void)x, CURLE_NOT_BUILT_IN)
-#define curlssl_engines_list(x) ((void)x, (struct curl_slist *)NULL)
-#define curlssl_version Curl_darwinssl_version
-#define curlssl_check_cxn Curl_darwinssl_check_cxn
-#define curlssl_data_pending(x,y) Curl_darwinssl_data_pending(x, y)
-#define curlssl_random(x,y,z) ((void)x, Curl_darwinssl_random(y,z))
-#define curlssl_md5sum(a,b,c,d) Curl_darwinssl_md5sum(a,b,c,d)
-#define curlssl_sha256sum(a,b,c,d) Curl_darwinssl_sha256sum(a,b,c,d)
-#define curlssl_false_start() Curl_darwinssl_false_start()
+extern const struct Curl_ssl Curl_ssl_darwinssl;
#endif /* USE_DARWINSSL */
#endif /* HEADER_CURL_DARWINSSL_H */
diff --git a/Utilities/cmcurl/lib/vtls/gskit.c b/Utilities/cmcurl/lib/vtls/gskit.c
index bf75bddc2..ba5faeff8 100644
--- a/Utilities/cmcurl/lib/vtls/gskit.c
+++ b/Utilities/cmcurl/lib/vtls/gskit.c
@@ -98,6 +98,14 @@
#define CURL_GSKPROTO_TLSV12_MASK (1 << CURL_GSKPROTO_TLSV12)
#define CURL_GSKPROTO_LAST 5
+struct ssl_backend_data {
+ gsk_handle handle;
+ int iocport;
+ int localfd;
+ int remotefd;
+};
+
+#define BACKEND connssl->backend
/* Supported ciphers. */
typedef struct {
@@ -427,7 +435,7 @@ static CURLcode set_ciphers(struct connectdata *conn,
}
-int Curl_gskit_init(void)
+static int Curl_gskit_init(void)
{
/* No initialisation needed. */
@@ -435,7 +443,7 @@ int Curl_gskit_init(void)
}
-void Curl_gskit_cleanup(void)
+static void Curl_gskit_cleanup(void)
{
/* Nothing to do. */
}
@@ -495,14 +503,14 @@ static void cancel_async_handshake(struct connectdata *conn, int sockindex)
Qso_OverlappedIO_t cstat;
if(QsoCancelOperation(conn->sock[sockindex], 0) > 0)
- QsoWaitForIOCompletion(connssl->iocport, &cstat, (struct timeval *) NULL);
+ QsoWaitForIOCompletion(BACKEND->iocport, &cstat, (struct timeval *) NULL);
}
static void close_async_handshake(struct ssl_connect_data *connssl)
{
- QsoDestroyIOCompletionPort(connssl->iocport);
- connssl->iocport = -1;
+ QsoDestroyIOCompletionPort(BACKEND->iocport);
+ BACKEND->iocport = -1;
}
/* SSL over SSL
@@ -620,12 +628,12 @@ static int pipe_ssloverssl(struct connectdata *conn, int sockindex,
FD_ZERO(&fds_write);
n = -1;
if(directions & SOS_READ) {
- FD_SET(connssl->remotefd, &fds_write);
- n = connssl->remotefd;
+ FD_SET(BACKEND->remotefd, &fds_write);
+ n = BACKEND->remotefd;
}
if(directions & SOS_WRITE) {
- FD_SET(connssl->remotefd, &fds_read);
- n = connssl->remotefd;
+ FD_SET(BACKEND->remotefd, &fds_read);
+ n = BACKEND->remotefd;
FD_SET(conn->sock[sockindex], &fds_write);
if(n < conn->sock[sockindex])
n = conn->sock[sockindex];
@@ -634,14 +642,15 @@ static int pipe_ssloverssl(struct connectdata *conn, int sockindex,
if(i < 0)
return -1; /* Select error. */
- if(FD_ISSET(connssl->remotefd, &fds_write)) {
+ if(FD_ISSET(BACKEND->remotefd, &fds_write)) {
/* Try getting data from HTTPS proxy and pipe it upstream. */
n = 0;
- i = gsk_secure_soc_read(connproxyssl->handle, buf, sizeof buf, &n);
+ i = gsk_secure_soc_read(connproxyssl->backend->handle,
+ buf, sizeof buf, &n);
switch(i) {
case GSK_OK:
if(n) {
- i = write(connssl->remotefd, buf, n);
+ i = write(BACKEND->remotefd, buf, n);
if(i < 0)
return -1;
ret = 1;
@@ -655,14 +664,14 @@ static int pipe_ssloverssl(struct connectdata *conn, int sockindex,
}
}
- if(FD_ISSET(connssl->remotefd, &fds_read) &&
+ if(FD_ISSET(BACKEND->remotefd, &fds_read) &&
FD_ISSET(conn->sock[sockindex], &fds_write)) {
/* Pipe data to HTTPS proxy. */
- n = read(connssl->remotefd, buf, sizeof buf);
+ n = read(BACKEND->remotefd, buf, sizeof buf);
if(n < 0)
return -1;
if(n) {
- i = gsk_secure_soc_write(connproxyssl->handle, buf, n, &m);
+ i = gsk_secure_soc_write(connproxyssl->backend->handle, buf, n, &m);
if(i != GSK_OK || n != m)
return -1;
ret = 1;
@@ -676,23 +685,23 @@ static int pipe_ssloverssl(struct connectdata *conn, int sockindex,
static void close_one(struct ssl_connect_data *connssl,
struct connectdata *conn, int sockindex)
{
- if(connssl->handle) {
- gskit_status(conn->data, gsk_secure_soc_close(&connssl->handle),
+ if(BACKEND->handle) {
+ gskit_status(conn->data, gsk_secure_soc_close(&BACKEND->handle),
"gsk_secure_soc_close()", 0);
/* Last chance to drain output. */
while(pipe_ssloverssl(conn, sockindex, SOS_WRITE) > 0)
;
- connssl->handle = (gsk_handle) NULL;
- if(connssl->localfd >= 0) {
- close(connssl->localfd);
- connssl->localfd = -1;
+ BACKEND->handle = (gsk_handle) NULL;
+ if(BACKEND->localfd >= 0) {
+ close(BACKEND->localfd);
+ BACKEND->localfd = -1;
}
- if(connssl->remotefd >= 0) {
- close(connssl->remotefd);
- connssl->remotefd = -1;
+ if(BACKEND->remotefd >= 0) {
+ close(BACKEND->remotefd);
+ BACKEND->remotefd = -1;
}
}
- if(connssl->iocport >= 0)
+ if(BACKEND->iocport >= 0)
close_async_handshake(connssl);
}
@@ -700,13 +709,14 @@ static void close_one(struct ssl_connect_data *connssl,
static ssize_t gskit_send(struct connectdata *conn, int sockindex,
const void *mem, size_t len, CURLcode *curlcode)
{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
struct Curl_easy *data = conn->data;
CURLcode cc = CURLE_SEND_ERROR;
int written;
if(pipe_ssloverssl(conn, sockindex, SOS_WRITE) >= 0) {
cc = gskit_status(data,
- gsk_secure_soc_write(conn->ssl[sockindex].handle,
+ gsk_secure_soc_write(BACKEND->handle,
(char *) mem, (int) len, &written),
"gsk_secure_soc_write()", CURLE_SEND_ERROR);
if(cc == CURLE_OK)
@@ -724,6 +734,7 @@ static ssize_t gskit_send(struct connectdata *conn, int sockindex,
static ssize_t gskit_recv(struct connectdata *conn, int num, char *buf,
size_t buffersize, CURLcode *curlcode)
{
+ struct ssl_connect_data *connssl = &conn->ssl[num];
struct Curl_easy *data = conn->data;
int buffsize;
int nread;
@@ -731,7 +742,7 @@ static ssize_t gskit_recv(struct connectdata *conn, int num, char *buf,
if(pipe_ssloverssl(conn, num, SOS_READ) >= 0) {
buffsize = buffersize > (size_t) INT_MAX? INT_MAX: (int) buffersize;
- cc = gskit_status(data, gsk_secure_soc_read(conn->ssl[num].handle,
+ cc = gskit_status(data, gsk_secure_soc_read(BACKEND->handle,
buf, buffsize, &nread),
"gsk_secure_soc_read()", CURLE_RECV_ERROR);
}
@@ -806,10 +817,10 @@ static CURLcode gskit_connect_step1(struct connectdata *conn, int sockindex)
/* Create SSL environment, start (preferably asynchronous) handshake. */
- connssl->handle = (gsk_handle) NULL;
- connssl->iocport = -1;
- connssl->localfd = -1;
- connssl->remotefd = -1;
+ BACKEND->handle = (gsk_handle) NULL;
+ BACKEND->iocport = -1;
+ BACKEND->localfd = -1;
+ BACKEND->remotefd = -1;
/* GSKit supports two ways of specifying an SSL context: either by
* application identifier (that should have been defined at the system
@@ -842,7 +853,7 @@ static CURLcode gskit_connect_step1(struct connectdata *conn, int sockindex)
}
/* Create secure session. */
- result = gskit_status(data, gsk_secure_soc_open(envir, &connssl->handle),
+ result = gskit_status(data, gsk_secure_soc_open(envir, &BACKEND->handle),
"gsk_secure_soc_open()", CURLE_SSL_CONNECT_ERROR);
gsk_environment_close(&envir);
if(result)
@@ -852,18 +863,18 @@ static CURLcode gskit_connect_step1(struct connectdata *conn, int sockindex)
if(conn->proxy_ssl[sockindex].use) {
if(inetsocketpair(sockpair))
return CURLE_SSL_CONNECT_ERROR;
- connssl->localfd = sockpair[0];
- connssl->remotefd = sockpair[1];
- setsockopt(connssl->localfd, SOL_SOCKET, SO_RCVBUF,
+ BACKEND->localfd = sockpair[0];
+ BACKEND->remotefd = sockpair[1];
+ setsockopt(BACKEND->localfd, SOL_SOCKET, SO_RCVBUF,
(void *) sobufsize, sizeof sobufsize);
- setsockopt(connssl->remotefd, SOL_SOCKET, SO_RCVBUF,
+ setsockopt(BACKEND->remotefd, SOL_SOCKET, SO_RCVBUF,
(void *) sobufsize, sizeof sobufsize);
- setsockopt(connssl->localfd, SOL_SOCKET, SO_SNDBUF,
+ setsockopt(BACKEND->localfd, SOL_SOCKET, SO_SNDBUF,
(void *) sobufsize, sizeof sobufsize);
- setsockopt(connssl->remotefd, SOL_SOCKET, SO_SNDBUF,
+ setsockopt(BACKEND->remotefd, SOL_SOCKET, SO_SNDBUF,
(void *) sobufsize, sizeof sobufsize);
- curlx_nonblock(connssl->localfd, TRUE);
- curlx_nonblock(connssl->remotefd, TRUE);
+ curlx_nonblock(BACKEND->localfd, TRUE);
+ curlx_nonblock(BACKEND->remotefd, TRUE);
}
/* Determine which SSL/TLS version should be enabled. */
@@ -897,7 +908,7 @@ static CURLcode gskit_connect_step1(struct connectdata *conn, int sockindex)
/* Process SNI. Ignore if not supported (on OS400 < V7R1). */
if(sni) {
- result = set_buffer(data, connssl->handle,
+ result = set_buffer(data, BACKEND->handle,
GSK_SSL_EXTN_SERVERNAME_REQUEST, sni, TRUE);
if(result == CURLE_UNSUPPORTED_PROTOCOL)
result = CURLE_OK;
@@ -911,34 +922,34 @@ static CURLcode gskit_connect_step1(struct connectdata *conn, int sockindex)
if(timeout < 0)
result = CURLE_OPERATION_TIMEDOUT;
else
- result = set_numeric(data, connssl->handle, GSK_HANDSHAKE_TIMEOUT,
+ result = set_numeric(data, BACKEND->handle, GSK_HANDSHAKE_TIMEOUT,
(timeout + 999) / 1000);
}
if(!result)
- result = set_numeric(data, connssl->handle, GSK_OS400_READ_TIMEOUT, 1);
+ result = set_numeric(data, BACKEND->handle, GSK_OS400_READ_TIMEOUT, 1);
if(!result)
- result = set_numeric(data, connssl->handle, GSK_FD, connssl->localfd >= 0?
- connssl->localfd: conn->sock[sockindex]);
+ result = set_numeric(data, BACKEND->handle, GSK_FD, BACKEND->localfd >= 0?
+ BACKEND->localfd: conn->sock[sockindex]);
if(!result)
- result = set_ciphers(conn, connssl->handle, &protoflags);
+ result = set_ciphers(conn, BACKEND->handle, &protoflags);
if(!protoflags) {
failf(data, "No SSL protocol/cipher combination enabled");
result = CURLE_SSL_CIPHER;
}
if(!result)
- result = set_enum(data, connssl->handle, GSK_PROTOCOL_SSLV2,
+ result = set_enum(data, BACKEND->handle, GSK_PROTOCOL_SSLV2,
(protoflags & CURL_GSKPROTO_SSLV2_MASK)?
GSK_PROTOCOL_SSLV2_ON: GSK_PROTOCOL_SSLV2_OFF, FALSE);
if(!result)
- result = set_enum(data, connssl->handle, GSK_PROTOCOL_SSLV3,
+ result = set_enum(data, BACKEND->handle, GSK_PROTOCOL_SSLV3,
(protoflags & CURL_GSKPROTO_SSLV3_MASK)?
GSK_PROTOCOL_SSLV3_ON: GSK_PROTOCOL_SSLV3_OFF, FALSE);
if(!result)
- result = set_enum(data, connssl->handle, GSK_PROTOCOL_TLSV1,
+ result = set_enum(data, BACKEND->handle, GSK_PROTOCOL_TLSV1,
(protoflags & CURL_GSKPROTO_TLSV10_MASK)?
GSK_PROTOCOL_TLSV1_ON: GSK_PROTOCOL_TLSV1_OFF, FALSE);
if(!result) {
- result = set_enum(data, connssl->handle, GSK_PROTOCOL_TLSV11,
+ result = set_enum(data, BACKEND->handle, GSK_PROTOCOL_TLSV11,
(protoflags & CURL_GSKPROTO_TLSV11_MASK)?
GSK_TRUE: GSK_FALSE, TRUE);
if(result == CURLE_UNSUPPORTED_PROTOCOL) {
@@ -950,7 +961,7 @@ static CURLcode gskit_connect_step1(struct connectdata *conn, int sockindex)
}
}
if(!result) {
- result = set_enum(data, connssl->handle, GSK_PROTOCOL_TLSV12,
+ result = set_enum(data, BACKEND->handle, GSK_PROTOCOL_TLSV12,
(protoflags & CURL_GSKPROTO_TLSV12_MASK)?
GSK_TRUE: GSK_FALSE, TRUE);
if(result == CURLE_UNSUPPORTED_PROTOCOL) {
@@ -962,18 +973,18 @@ static CURLcode gskit_connect_step1(struct connectdata *conn, int sockindex)
}
}
if(!result)
- result = set_enum(data, connssl->handle, GSK_SERVER_AUTH_TYPE,
+ result = set_enum(data, BACKEND->handle, GSK_SERVER_AUTH_TYPE,
verifypeer? GSK_SERVER_AUTH_FULL:
GSK_SERVER_AUTH_PASSTHRU, FALSE);
if(!result) {
/* Start handshake. Try asynchronous first. */
memset(&commarea, 0, sizeof commarea);
- connssl->iocport = QsoCreateIOCompletionPort();
- if(connssl->iocport != -1) {
+ BACKEND->iocport = QsoCreateIOCompletionPort();
+ if(BACKEND->iocport != -1) {
result = gskit_status(data,
- gsk_secure_soc_startInit(connssl->handle,
- connssl->iocport,
+ gsk_secure_soc_startInit(BACKEND->handle,
+ BACKEND->iocport,
&commarea),
"gsk_secure_soc_startInit()",
CURLE_SSL_CONNECT_ERROR);
@@ -993,7 +1004,7 @@ static CURLcode gskit_connect_step1(struct connectdata *conn, int sockindex)
}
else {
/* No more completion port available. Use synchronous IO. */
- result = gskit_status(data, gsk_secure_soc_init(connssl->handle),
+ result = gskit_status(data, gsk_secure_soc_init(BACKEND->handle),
"gsk_secure_soc_init()", CURLE_SSL_CONNECT_ERROR);
if(!result) {
connssl->connecting_state = ssl_connect_3;
@@ -1026,7 +1037,7 @@ static CURLcode gskit_connect_step2(struct connectdata *conn, int sockindex,
timeout_ms = 0;
stmv.tv_sec = timeout_ms / 1000;
stmv.tv_usec = (timeout_ms - stmv.tv_sec * 1000) * 1000;
- switch(QsoWaitForIOCompletion(connssl->iocport, &cstat, &stmv)) {
+ switch(QsoWaitForIOCompletion(BACKEND->iocport, &cstat, &stmv)) {
case 1: /* Operation complete. */
break;
case -1: /* An error occurred: handshake still in progress. */
@@ -1075,7 +1086,7 @@ static CURLcode gskit_connect_step3(struct connectdata *conn, int sockindex)
/* SSL handshake done: gather certificate info and verify host. */
- if(gskit_status(data, gsk_attribute_get_cert_info(connssl->handle,
+ if(gskit_status(data, gsk_attribute_get_cert_info(BACKEND->handle,
GSK_PARTNER_CERT_INFO,
&cdev, &cdec),
"gsk_attribute_get_cert_info()", CURLE_SSL_CONNECT_ERROR) ==
@@ -1216,9 +1227,8 @@ static CURLcode gskit_connect_common(struct connectdata *conn, int sockindex,
}
-CURLcode Curl_gskit_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done)
+static CURLcode Curl_gskit_connect_nonblocking(struct connectdata *conn,
+ int sockindex, bool *done)
{
CURLcode result;
@@ -1229,7 +1239,7 @@ CURLcode Curl_gskit_connect_nonblocking(struct connectdata *conn,
}
-CURLcode Curl_gskit_connect(struct connectdata *conn, int sockindex)
+static CURLcode Curl_gskit_connect(struct connectdata *conn, int sockindex)
{
CURLcode result;
bool done;
@@ -1245,14 +1255,14 @@ CURLcode Curl_gskit_connect(struct connectdata *conn, int sockindex)
}
-void Curl_gskit_close(struct connectdata *conn, int sockindex)
+static void Curl_gskit_close(struct connectdata *conn, int sockindex)
{
close_one(&conn->ssl[sockindex], conn, sockindex);
close_one(&conn->proxy_ssl[sockindex], conn, sockindex);
}
-int Curl_gskit_shutdown(struct connectdata *conn, int sockindex)
+static int Curl_gskit_shutdown(struct connectdata *conn, int sockindex)
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
struct Curl_easy *data = conn->data;
@@ -1261,7 +1271,7 @@ int Curl_gskit_shutdown(struct connectdata *conn, int sockindex)
int rc;
char buf[120];
- if(!connssl->handle)
+ if(!BACKEND->handle)
return 0;
if(data->set.ftp_ccc != CURLFTPSSL_CCC_ACTIVE)
@@ -1306,21 +1316,22 @@ int Curl_gskit_shutdown(struct connectdata *conn, int sockindex)
}
-size_t Curl_gskit_version(char *buffer, size_t size)
+static size_t Curl_gskit_version(char *buffer, size_t size)
{
strncpy(buffer, "GSKit", size);
return strlen(buffer);
}
-int Curl_gskit_check_cxn(struct connectdata *cxn)
+static int Curl_gskit_check_cxn(struct connectdata *cxn)
{
+ struct ssl_connect_data *connssl = &cxn->ssl[FIRSTSOCKET];
int err;
int errlen;
/* The only thing that can be tested here is at the socket level. */
- if(!cxn->ssl[FIRSTSOCKET].handle)
+ if(!BACKEND->handle)
return 0; /* connection has been closed */
err = 0;
@@ -1334,4 +1345,46 @@ int Curl_gskit_check_cxn(struct connectdata *cxn)
return -1; /* connection status unknown */
}
+static void *Curl_gskit_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info UNUSED_PARAM)
+{
+ (void)info;
+ return BACKEND->handle;
+}
+
+const struct Curl_ssl Curl_ssl_gskit = {
+ { CURLSSLBACKEND_GSKIT, "gskit" }, /* info */
+
+ 0, /* have_ca_path */
+ 1, /* have_certinfo */
+ 0, /* have_pinnedpubkey */
+ 0, /* have_ssl_ctx */
+ /* TODO: convert to 1 and fix test #1014 (if need) */
+ 0, /* support_https_proxy */
+
+ sizeof(struct ssl_backend_data),
+
+ Curl_gskit_init, /* init */
+ Curl_gskit_cleanup, /* cleanup */
+ Curl_gskit_version, /* version */
+ Curl_gskit_check_cxn, /* check_cxn */
+ Curl_gskit_shutdown, /* shutdown */
+ Curl_none_data_pending, /* data_pending */
+ Curl_none_random, /* random */
+ Curl_none_cert_status_request, /* cert_status_request */
+ Curl_gskit_connect, /* connect */
+ Curl_gskit_connect_nonblocking, /* connect_nonblocking */
+ Curl_gskit_get_internals, /* get_internals */
+ Curl_gskit_close, /* close */
+ Curl_none_close_all, /* close_all */
+ /* No session handling for GSKit */
+ Curl_none_session_free, /* session_free */
+ Curl_none_set_engine, /* set_engine */
+ Curl_none_set_engine_default, /* set_engine_default */
+ Curl_none_engines_list, /* engines_list */
+ Curl_none_false_start, /* false_start */
+ Curl_none_md5sum, /* md5sum */
+ NULL /* sha256sum */
+};
+
#endif /* USE_GSKIT */
diff --git a/Utilities/cmcurl/lib/vtls/gskit.h b/Utilities/cmcurl/lib/vtls/gskit.h
index 229759217..466ee4d9d 100644
--- a/Utilities/cmcurl/lib/vtls/gskit.h
+++ b/Utilities/cmcurl/lib/vtls/gskit.h
@@ -30,44 +30,8 @@
#include "urldata.h"
#ifdef USE_GSKIT
-int Curl_gskit_init(void);
-void Curl_gskit_cleanup(void);
-CURLcode Curl_gskit_connect(struct connectdata *conn, int sockindex);
-CURLcode Curl_gskit_connect_nonblocking(struct connectdata *conn,
- int sockindex, bool *done);
-void Curl_gskit_close(struct connectdata *conn, int sockindex);
-int Curl_gskit_shutdown(struct connectdata *conn, int sockindex);
-size_t Curl_gskit_version(char *buffer, size_t size);
-int Curl_gskit_check_cxn(struct connectdata *cxn);
-
-/* Support HTTPS-proxy */
-/* TODO: add '#define HTTPS_PROXY_SUPPORT 1' and fix test #1014 (if need) */
-
-/* Set the API backend definition to GSKit */
-#define CURL_SSL_BACKEND CURLSSLBACKEND_GSKIT
-
-/* this backend supports CURLOPT_CERTINFO */
-#define have_curlssl_certinfo 1
-
-/* API setup for GSKit */
-#define curlssl_init Curl_gskit_init
-#define curlssl_cleanup Curl_gskit_cleanup
-#define curlssl_connect Curl_gskit_connect
-#define curlssl_connect_nonblocking Curl_gskit_connect_nonblocking
-
-/* No session handling for GSKit */
-#define curlssl_session_free(x) Curl_nop_stmt
-#define curlssl_close_all(x) ((void)x)
-#define curlssl_close Curl_gskit_close
-#define curlssl_shutdown(x,y) Curl_gskit_shutdown(x,y)
-#define curlssl_set_engine(x,y) CURLE_NOT_BUILT_IN
-#define curlssl_set_engine_default(x) CURLE_NOT_BUILT_IN
-#define curlssl_engines_list(x) NULL
-#define curlssl_version Curl_gskit_version
-#define curlssl_check_cxn(x) Curl_gskit_check_cxn(x)
-#define curlssl_data_pending(x,y) 0
-#define curlssl_random(x,y,z) (x=x, y=y, z=z, CURLE_NOT_BUILT_IN)
+extern const struct Curl_ssl Curl_ssl_gskit;
#endif /* USE_GSKIT */
diff --git a/Utilities/cmcurl/lib/vtls/gtls.c b/Utilities/cmcurl/lib/vtls/gtls.c
index 844be2de1..a844915ef 100644
--- a/Utilities/cmcurl/lib/vtls/gtls.c
+++ b/Utilities/cmcurl/lib/vtls/gtls.c
@@ -60,15 +60,13 @@
/* The last #include file should be: */
#include "memdebug.h"
-/*
- Some hackish cast macros based on:
- https://developer.gnome.org/glib/unstable/glib-Type-Conversion-Macros.html
-*/
-#ifndef GNUTLS_POINTER_TO_INT_CAST
-#define GNUTLS_POINTER_TO_INT_CAST(p) ((int) (long) (p))
+#ifndef GNUTLS_POINTER_TO_SOCKET_CAST
+#define GNUTLS_POINTER_TO_SOCKET_CAST(p) \
+ ((curl_socket_t) ((char *)(p) - (char *)NULL))
#endif
-#ifndef GNUTLS_INT_TO_POINTER_CAST
-#define GNUTLS_INT_TO_POINTER_CAST(i) ((void *) (long) (i))
+#ifndef GNUTLS_SOCKET_TO_POINTER_CAST
+#define GNUTLS_SOCKET_TO_POINTER_CAST(s) \
+ ((void *) ((char *)NULL + (s)))
#endif
/* Enable GnuTLS debugging by defining GTLSDEBUG */
@@ -109,6 +107,16 @@ static bool gtls_inited = FALSE;
# include <gnutls/ocsp.h>
#endif
+struct ssl_backend_data {
+ gnutls_session_t session;
+ gnutls_certificate_credentials_t cred;
+#ifdef USE_TLS_SRP
+ gnutls_srp_client_credentials_t srp_client_cred;
+#endif
+};
+
+#define BACKEND connssl->backend
+
/*
* Custom push and pull callback functions used by GNU TLS to read and write
* to the socket. These functions are simple wrappers to send() and recv()
@@ -153,7 +161,7 @@ static int gtls_mapped_sockerrno(void)
static ssize_t Curl_gtls_push(void *s, const void *buf, size_t len)
{
- ssize_t ret = swrite(GNUTLS_POINTER_TO_INT_CAST(s), buf, len);
+ ssize_t ret = swrite(GNUTLS_POINTER_TO_SOCKET_CAST(s), buf, len);
#if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
if(ret < 0)
gnutls_transport_set_global_errno(gtls_mapped_sockerrno());
@@ -163,7 +171,7 @@ static ssize_t Curl_gtls_push(void *s, const void *buf, size_t len)
static ssize_t Curl_gtls_pull(void *s, void *buf, size_t len)
{
- ssize_t ret = sread(GNUTLS_POINTER_TO_INT_CAST(s), buf, len);
+ ssize_t ret = sread(GNUTLS_POINTER_TO_SOCKET_CAST(s), buf, len);
#if defined(USE_WINSOCK) && !defined(GNUTLS_MAPS_WINSOCK_ERRORS)
if(ret < 0)
gnutls_transport_set_global_errno(gtls_mapped_sockerrno());
@@ -188,7 +196,7 @@ static ssize_t Curl_gtls_pull_ssl(void *s, void *buf, size_t len)
* must only be called from within curl_global_init() to keep the thread
* situation under control!
*/
-int Curl_gtls_init(void)
+static int Curl_gtls_init(void)
{
int ret = 1;
if(!gtls_inited) {
@@ -202,13 +210,12 @@ int Curl_gtls_init(void)
return ret;
}
-int Curl_gtls_cleanup(void)
+static void Curl_gtls_cleanup(void)
{
if(gtls_inited) {
gnutls_global_deinit();
gtls_inited = FALSE;
}
- return 1;
}
#ifndef CURL_DISABLE_VERBOSE_STRINGS
@@ -279,7 +286,7 @@ static CURLcode handshake(struct connectdata *conn,
{
struct Curl_easy *data = conn->data;
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
- gnutls_session_t session = conn->ssl[sockindex].session;
+ gnutls_session_t session = BACKEND->session;
curl_socket_t sockfd = conn->sock[sockindex];
time_t timeout_ms;
int rc;
@@ -299,9 +306,9 @@ static CURLcode handshake(struct connectdata *conn,
if(connssl->connecting_state == ssl_connect_2_reading
|| connssl->connecting_state == ssl_connect_2_writing) {
- curl_socket_t writefd = ssl_connect_2_writing==
+ curl_socket_t writefd = ssl_connect_2_writing ==
connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
- curl_socket_t readfd = ssl_connect_2_reading==
+ curl_socket_t readfd = ssl_connect_2_reading ==
connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
@@ -477,6 +484,7 @@ gtls_connect_step1(struct connectdata *conn,
int sockindex)
{
struct Curl_easy *data = conn->data;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
unsigned int init_flags;
gnutls_session_t session;
int rc;
@@ -512,7 +520,7 @@ gtls_connect_step1(struct connectdata *conn,
const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
conn->host.name;
- if(conn->ssl[sockindex].state == ssl_connection_complete)
+ if(connssl->state == ssl_connection_complete)
/* to make us tolerant against being called more than once for the
same connection */
return CURLE_OK;
@@ -528,7 +536,7 @@ gtls_connect_step1(struct connectdata *conn,
sni = FALSE; /* SSLv3 has no SNI */
/* allocate a cred struct */
- rc = gnutls_certificate_allocate_credentials(&conn->ssl[sockindex].cred);
+ rc = gnutls_certificate_allocate_credentials(&BACKEND->cred);
if(rc != GNUTLS_E_SUCCESS) {
failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc));
return CURLE_SSL_CONNECT_ERROR;
@@ -539,15 +547,14 @@ gtls_connect_step1(struct connectdata *conn,
infof(data, "Using TLS-SRP username: %s\n", SSL_SET_OPTION(username));
rc = gnutls_srp_allocate_client_credentials(
- &conn->ssl[sockindex].srp_client_cred);
+ &BACKEND->srp_client_cred);
if(rc != GNUTLS_E_SUCCESS) {
failf(data, "gnutls_srp_allocate_client_cred() failed: %s",
gnutls_strerror(rc));
return CURLE_OUT_OF_MEMORY;
}
- rc = gnutls_srp_set_client_credentials(conn->ssl[sockindex].
- srp_client_cred,
+ rc = gnutls_srp_set_client_credentials(BACKEND->srp_client_cred,
SSL_SET_OPTION(username),
SSL_SET_OPTION(password));
if(rc != GNUTLS_E_SUCCESS) {
@@ -560,10 +567,10 @@ gtls_connect_step1(struct connectdata *conn,
if(SSL_CONN_CONFIG(CAfile)) {
/* set the trusted CA cert bundle file */
- gnutls_certificate_set_verify_flags(conn->ssl[sockindex].cred,
+ gnutls_certificate_set_verify_flags(BACKEND->cred,
GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
- rc = gnutls_certificate_set_x509_trust_file(conn->ssl[sockindex].cred,
+ rc = gnutls_certificate_set_x509_trust_file(BACKEND->cred,
SSL_CONN_CONFIG(CAfile),
GNUTLS_X509_FMT_PEM);
if(rc < 0) {
@@ -580,7 +587,7 @@ gtls_connect_step1(struct connectdata *conn,
#ifdef HAS_CAPATH
if(SSL_CONN_CONFIG(CApath)) {
/* set the trusted CA cert directory */
- rc = gnutls_certificate_set_x509_trust_dir(conn->ssl[sockindex].cred,
+ rc = gnutls_certificate_set_x509_trust_dir(BACKEND->cred,
SSL_CONN_CONFIG(CApath),
GNUTLS_X509_FMT_PEM);
if(rc < 0) {
@@ -599,13 +606,13 @@ gtls_connect_step1(struct connectdata *conn,
/* use system ca certificate store as fallback */
if(SSL_CONN_CONFIG(verifypeer) &&
!(SSL_CONN_CONFIG(CAfile) || SSL_CONN_CONFIG(CApath))) {
- gnutls_certificate_set_x509_system_trust(conn->ssl[sockindex].cred);
+ gnutls_certificate_set_x509_system_trust(BACKEND->cred);
}
#endif
if(SSL_SET_OPTION(CRLfile)) {
/* set the CRL list file */
- rc = gnutls_certificate_set_x509_crl_file(conn->ssl[sockindex].cred,
+ rc = gnutls_certificate_set_x509_crl_file(BACKEND->cred,
SSL_SET_OPTION(CRLfile),
GNUTLS_X509_FMT_PEM);
if(rc < 0) {
@@ -626,14 +633,14 @@ gtls_connect_step1(struct connectdata *conn,
init_flags |= GNUTLS_NO_TICKETS;
#endif
- rc = gnutls_init(&conn->ssl[sockindex].session, init_flags);
+ rc = gnutls_init(&BACKEND->session, init_flags);
if(rc != GNUTLS_E_SUCCESS) {
failf(data, "gnutls_init() failed: %d", rc);
return CURLE_SSL_CONNECT_ERROR;
}
/* convenient assign */
- session = conn->ssl[sockindex].session;
+ session = BACKEND->session;
if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
#ifdef ENABLE_IPV6
@@ -763,7 +770,8 @@ gtls_connect_step1(struct connectdata *conn,
gnutls_datum_t protocols[2];
#ifdef USE_NGHTTP2
- if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
+ if(data->set.httpversion >= CURL_HTTP_VERSION_2 &&
+ (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) {
protocols[cur].data = (unsigned char *)NGHTTP2_PROTO_VERSION_ID;
protocols[cur].size = NGHTTP2_PROTO_VERSION_ID_LEN;
cur++;
@@ -789,7 +797,7 @@ gtls_connect_step1(struct connectdata *conn,
GNUTLS_PKCS_USE_PBES2_AES_128 | GNUTLS_PKCS_USE_PBES2_AES_192 |
GNUTLS_PKCS_USE_PBES2_AES_256;
rc = gnutls_certificate_set_x509_key_file2(
- conn->ssl[sockindex].cred,
+ BACKEND->cred,
SSL_SET_OPTION(cert),
SSL_SET_OPTION(key) ?
SSL_SET_OPTION(key) : SSL_SET_OPTION(cert),
@@ -809,7 +817,7 @@ gtls_connect_step1(struct connectdata *conn,
}
else {
if(gnutls_certificate_set_x509_key_file(
- conn->ssl[sockindex].cred,
+ BACKEND->cred,
SSL_SET_OPTION(cert),
SSL_SET_OPTION(key) ?
SSL_SET_OPTION(key) : SSL_SET_OPTION(cert),
@@ -825,7 +833,7 @@ gtls_connect_step1(struct connectdata *conn,
/* put the credentials to the current session */
if(SSL_SET_OPTION(authtype) == CURL_TLSAUTH_SRP) {
rc = gnutls_credentials_set(session, GNUTLS_CRD_SRP,
- conn->ssl[sockindex].srp_client_cred);
+ BACKEND->srp_client_cred);
if(rc != GNUTLS_E_SUCCESS) {
failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
return CURLE_SSL_CONNECT_ERROR;
@@ -835,7 +843,7 @@ gtls_connect_step1(struct connectdata *conn,
#endif
{
rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE,
- conn->ssl[sockindex].cred);
+ BACKEND->cred);
if(rc != GNUTLS_E_SUCCESS) {
failf(data, "gnutls_credentials_set() failed: %s", gnutls_strerror(rc));
return CURLE_SSL_CONNECT_ERROR;
@@ -843,13 +851,13 @@ gtls_connect_step1(struct connectdata *conn,
}
if(conn->proxy_ssl[sockindex].use) {
- transport_ptr = conn->proxy_ssl[sockindex].session;
+ transport_ptr = conn->proxy_ssl[sockindex].backend->session;
gnutls_transport_push = Curl_gtls_push_ssl;
gnutls_transport_pull = Curl_gtls_pull_ssl;
}
else {
/* file descriptor for the socket */
- transport_ptr = GNUTLS_INT_TO_POINTER_CAST(conn->sock[sockindex]);
+ transport_ptr = GNUTLS_SOCKET_TO_POINTER_CAST(conn->sock[sockindex]);
gnutls_transport_push = Curl_gtls_push;
gnutls_transport_pull = Curl_gtls_pull;
}
@@ -968,7 +976,8 @@ gtls_connect_step3(struct connectdata *conn,
time_t certclock;
const char *ptr;
struct Curl_easy *data = conn->data;
- gnutls_session_t session = conn->ssl[sockindex].session;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ gnutls_session_t session = BACKEND->session;
int rc;
#ifdef HAS_ALPN
gnutls_datum_t proto;
@@ -1199,7 +1208,7 @@ gtls_connect_step3(struct connectdata *conn,
SSL_SET_OPTION(issuercert)?SSL_SET_OPTION(issuercert):"none");
}
- size=sizeof(certbuf);
+ size = sizeof(certbuf);
rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,
0, /* the first and only one */
FALSE,
@@ -1239,7 +1248,7 @@ gtls_connect_step3(struct connectdata *conn,
#endif
if(addrlen) {
- for(i=0; ; i++) {
+ for(i = 0; ; i++) {
certaddrlen = sizeof(certaddr);
ret = gnutls_x509_crt_get_subject_alt_name(x509_cert, i, certaddr,
&certaddrlen, NULL);
@@ -1472,7 +1481,7 @@ gtls_connect_common(struct connectdata *conn,
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
/* Initiate the connection, if not already done */
- if(ssl_connect_1==connssl->connecting_state) {
+ if(ssl_connect_1 == connssl->connecting_state) {
rc = gtls_connect_step1(conn, sockindex);
if(rc)
return rc;
@@ -1484,29 +1493,24 @@ gtls_connect_common(struct connectdata *conn,
return rc;
/* Finish connecting once the handshake is done */
- if(ssl_connect_1==connssl->connecting_state) {
+ if(ssl_connect_1 == connssl->connecting_state) {
rc = gtls_connect_step3(conn, sockindex);
if(rc)
return rc;
}
- *done = ssl_connect_1==connssl->connecting_state;
+ *done = ssl_connect_1 == connssl->connecting_state;
return CURLE_OK;
}
-CURLcode
-Curl_gtls_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done)
+static CURLcode Curl_gtls_connect_nonblocking(struct connectdata *conn,
+ int sockindex, bool *done)
{
return gtls_connect_common(conn, sockindex, TRUE, done);
}
-CURLcode
-Curl_gtls_connect(struct connectdata *conn,
- int sockindex)
-
+static CURLcode Curl_gtls_connect(struct connectdata *conn, int sockindex)
{
CURLcode result;
bool done = FALSE;
@@ -1520,15 +1524,18 @@ Curl_gtls_connect(struct connectdata *conn,
return CURLE_OK;
}
-bool Curl_gtls_data_pending(const struct connectdata *conn, int connindex)
+static bool Curl_gtls_data_pending(const struct connectdata *conn,
+ int connindex)
{
+ const struct ssl_connect_data *connssl = &conn->ssl[connindex];
bool res = FALSE;
- if(conn->ssl[connindex].session &&
- 0 != gnutls_record_check_pending(conn->ssl[connindex].session))
+ if(BACKEND->session &&
+ 0 != gnutls_record_check_pending(BACKEND->session))
res = TRUE;
- if(conn->proxy_ssl[connindex].session &&
- 0 != gnutls_record_check_pending(conn->proxy_ssl[connindex].session))
+ connssl = &conn->proxy_ssl[connindex];
+ if(BACKEND->session &&
+ 0 != gnutls_record_check_pending(BACKEND->session))
res = TRUE;
return res;
@@ -1540,7 +1547,8 @@ static ssize_t gtls_send(struct connectdata *conn,
size_t len,
CURLcode *curlcode)
{
- ssize_t rc = gnutls_record_send(conn->ssl[sockindex].session, mem, len);
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ ssize_t rc = gnutls_record_send(BACKEND->session, mem, len);
if(rc < 0) {
*curlcode = (rc == GNUTLS_E_AGAIN)
@@ -1553,26 +1561,26 @@ static ssize_t gtls_send(struct connectdata *conn,
return rc;
}
-static void close_one(struct ssl_connect_data *ssl)
+static void close_one(struct ssl_connect_data *connssl)
{
- if(ssl->session) {
- gnutls_bye(ssl->session, GNUTLS_SHUT_RDWR);
- gnutls_deinit(ssl->session);
- ssl->session = NULL;
+ if(BACKEND->session) {
+ gnutls_bye(BACKEND->session, GNUTLS_SHUT_RDWR);
+ gnutls_deinit(BACKEND->session);
+ BACKEND->session = NULL;
}
- if(ssl->cred) {
- gnutls_certificate_free_credentials(ssl->cred);
- ssl->cred = NULL;
+ if(BACKEND->cred) {
+ gnutls_certificate_free_credentials(BACKEND->cred);
+ BACKEND->cred = NULL;
}
#ifdef USE_TLS_SRP
- if(ssl->srp_client_cred) {
- gnutls_srp_free_client_credentials(ssl->srp_client_cred);
- ssl->srp_client_cred = NULL;
+ if(BACKEND->srp_client_cred) {
+ gnutls_srp_free_client_credentials(BACKEND->srp_client_cred);
+ BACKEND->srp_client_cred = NULL;
}
#endif
}
-void Curl_gtls_close(struct connectdata *conn, int sockindex)
+static void Curl_gtls_close(struct connectdata *conn, int sockindex)
{
close_one(&conn->ssl[sockindex]);
close_one(&conn->proxy_ssl[sockindex]);
@@ -1582,8 +1590,9 @@ void Curl_gtls_close(struct connectdata *conn, int sockindex)
* This function is called to shut down the SSL layer but keep the
* socket open (CCC - Clear Command Channel)
*/
-int Curl_gtls_shutdown(struct connectdata *conn, int sockindex)
+static int Curl_gtls_shutdown(struct connectdata *conn, int sockindex)
{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
ssize_t result;
int retval = 0;
struct Curl_easy *data = conn->data;
@@ -1596,16 +1605,16 @@ int Curl_gtls_shutdown(struct connectdata *conn, int sockindex)
we do not send one. Let's hope other servers do the same... */
if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
- gnutls_bye(conn->ssl[sockindex].session, GNUTLS_SHUT_WR);
+ gnutls_bye(BACKEND->session, GNUTLS_SHUT_WR);
- if(conn->ssl[sockindex].session) {
+ if(BACKEND->session) {
while(!done) {
int what = SOCKET_READABLE(conn->sock[sockindex],
SSL_SHUTDOWN_TIMEOUT);
if(what > 0) {
/* Something to read, let's do it and hope that it is the close
notify alert from the server */
- result = gnutls_record_recv(conn->ssl[sockindex].session,
+ result = gnutls_record_recv(BACKEND->session,
buf, sizeof(buf));
switch(result) {
case 0:
@@ -1636,18 +1645,18 @@ int Curl_gtls_shutdown(struct connectdata *conn, int sockindex)
done = 1;
}
}
- gnutls_deinit(conn->ssl[sockindex].session);
+ gnutls_deinit(BACKEND->session);
}
- gnutls_certificate_free_credentials(conn->ssl[sockindex].cred);
+ gnutls_certificate_free_credentials(BACKEND->cred);
#ifdef USE_TLS_SRP
if(SSL_SET_OPTION(authtype) == CURL_TLSAUTH_SRP
&& SSL_SET_OPTION(username) != NULL)
- gnutls_srp_free_client_credentials(conn->ssl[sockindex].srp_client_cred);
+ gnutls_srp_free_client_credentials(BACKEND->srp_client_cred);
#endif
- conn->ssl[sockindex].cred = NULL;
- conn->ssl[sockindex].session = NULL;
+ BACKEND->cred = NULL;
+ BACKEND->session = NULL;
return retval;
}
@@ -1658,9 +1667,10 @@ static ssize_t gtls_recv(struct connectdata *conn, /* connection data */
size_t buffersize, /* max amount to read */
CURLcode *curlcode)
{
+ struct ssl_connect_data *connssl = &conn->ssl[num];
ssize_t ret;
- ret = gnutls_record_recv(conn->ssl[num].session, buf, buffersize);
+ ret = gnutls_record_recv(BACKEND->session, buf, buffersize);
if((ret == GNUTLS_E_AGAIN) || (ret == GNUTLS_E_INTERRUPTED)) {
*curlcode = CURLE_AGAIN;
return -1;
@@ -1680,6 +1690,7 @@ static ssize_t gtls_recv(struct connectdata *conn, /* connection data */
if(ret < 0) {
failf(conn->data, "GnuTLS recv error (%d): %s",
+
(int)ret, gnutls_strerror((int)ret));
*curlcode = CURLE_RECV_ERROR;
return -1;
@@ -1688,12 +1699,12 @@ static ssize_t gtls_recv(struct connectdata *conn, /* connection data */
return ret;
}
-void Curl_gtls_session_free(void *ptr)
+static void Curl_gtls_session_free(void *ptr)
{
free(ptr);
}
-size_t Curl_gtls_version(char *buffer, size_t size)
+static size_t Curl_gtls_version(char *buffer, size_t size)
{
return snprintf(buffer, size, "GnuTLS/%s", gnutls_check_version(NULL));
}
@@ -1723,9 +1734,8 @@ static int Curl_gtls_seed(struct Curl_easy *data)
#endif
/* data might be NULL! */
-CURLcode Curl_gtls_random(struct Curl_easy *data,
- unsigned char *entropy,
- size_t length)
+static CURLcode Curl_gtls_random(struct Curl_easy *data,
+ unsigned char *entropy, size_t length)
{
#if defined(USE_GNUTLS_NETTLE)
int rc;
@@ -1740,10 +1750,10 @@ CURLcode Curl_gtls_random(struct Curl_easy *data,
return CURLE_OK;
}
-void Curl_gtls_md5sum(unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *md5sum, /* output */
- size_t md5len)
+static CURLcode Curl_gtls_md5sum(unsigned char *tmp, /* input */
+ size_t tmplen,
+ unsigned char *md5sum, /* output */
+ size_t md5len)
{
#if defined(USE_GNUTLS_NETTLE)
struct md5_ctx MD5pw;
@@ -1757,12 +1767,13 @@ void Curl_gtls_md5sum(unsigned char *tmp, /* input */
memcpy(md5sum, gcry_md_read(MD5pw, 0), md5len);
gcry_md_close(MD5pw);
#endif
+ return CURLE_OK;
}
-void Curl_gtls_sha256sum(const unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *sha256sum, /* output */
- size_t sha256len)
+static void Curl_gtls_sha256sum(const unsigned char *tmp, /* input */
+ size_t tmplen,
+ unsigned char *sha256sum, /* output */
+ size_t sha256len)
{
#if defined(USE_GNUTLS_NETTLE)
struct sha256_ctx SHA256pw;
@@ -1778,7 +1789,7 @@ void Curl_gtls_sha256sum(const unsigned char *tmp, /* input */
#endif
}
-bool Curl_gtls_cert_status_request(void)
+static bool Curl_gtls_cert_status_request(void)
{
#ifdef HAS_OCSP
return TRUE;
@@ -1787,4 +1798,44 @@ bool Curl_gtls_cert_status_request(void)
#endif
}
+static void *Curl_gtls_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info UNUSED_PARAM)
+{
+ (void)info;
+ return BACKEND->session;
+}
+
+const struct Curl_ssl Curl_ssl_gnutls = {
+ { CURLSSLBACKEND_GNUTLS, "gnutls" }, /* info */
+
+ 1, /* have_ca_path */
+ 1, /* have_certinfo */
+ 1, /* have_pinnedpubkey */
+ 0, /* have_ssl_ctx */
+ 1, /* support_https_proxy */
+
+ sizeof(struct ssl_backend_data),
+
+ Curl_gtls_init, /* init */
+ Curl_gtls_cleanup, /* cleanup */
+ Curl_gtls_version, /* version */
+ Curl_none_check_cxn, /* check_cxn */
+ Curl_gtls_shutdown, /* shutdown */
+ Curl_gtls_data_pending, /* data_pending */
+ Curl_gtls_random, /* random */
+ Curl_gtls_cert_status_request, /* cert_status_request */
+ Curl_gtls_connect, /* connect */
+ Curl_gtls_connect_nonblocking, /* connect_nonblocking */
+ Curl_gtls_get_internals, /* get_internals */
+ Curl_gtls_close, /* close */
+ Curl_none_close_all, /* close_all */
+ Curl_gtls_session_free, /* session_free */
+ Curl_none_set_engine, /* set_engine */
+ Curl_none_set_engine_default, /* set_engine_default */
+ Curl_none_engines_list, /* engines_list */
+ Curl_none_false_start, /* false_start */
+ Curl_gtls_md5sum, /* md5sum */
+ Curl_gtls_sha256sum /* sha256sum */
+};
+
#endif /* USE_GNUTLS */
diff --git a/Utilities/cmcurl/lib/vtls/gtls.h b/Utilities/cmcurl/lib/vtls/gtls.h
index 462c04853..780fc109d 100644
--- a/Utilities/cmcurl/lib/vtls/gtls.h
+++ b/Utilities/cmcurl/lib/vtls/gtls.h
@@ -28,69 +28,7 @@
#include "urldata.h"
-int Curl_gtls_init(void);
-int Curl_gtls_cleanup(void);
-CURLcode Curl_gtls_connect(struct connectdata *conn, int sockindex);
-CURLcode Curl_gtls_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done);
-bool Curl_gtls_data_pending(const struct connectdata *conn,
- int connindex);
-
- /* close a SSL connection */
-void Curl_gtls_close(struct connectdata *conn, int sockindex);
-
-void Curl_gtls_session_free(void *ptr);
-size_t Curl_gtls_version(char *buffer, size_t size);
-int Curl_gtls_shutdown(struct connectdata *conn, int sockindex);
-CURLcode Curl_gtls_random(struct Curl_easy *data,
- unsigned char *entropy,
- size_t length);
-void Curl_gtls_md5sum(unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *md5sum, /* output */
- size_t md5len);
-void Curl_gtls_sha256sum(const unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *sha256sum, /* output */
- size_t sha256len);
-
-bool Curl_gtls_cert_status_request(void);
-
-/* Support HTTPS-proxy */
-#define HTTPS_PROXY_SUPPORT 1
-
-/* Set the API backend definition to GnuTLS */
-#define CURL_SSL_BACKEND CURLSSLBACKEND_GNUTLS
-
-/* this backend supports the CAPATH option */
-#define have_curlssl_ca_path 1
-
-/* this backend supports CURLOPT_CERTINFO */
-#define have_curlssl_certinfo 1
-
-/* this backend supports CURLOPT_PINNEDPUBLICKEY */
-#define have_curlssl_pinnedpubkey 1
-
-/* API setup for GnuTLS */
-#define curlssl_init Curl_gtls_init
-#define curlssl_cleanup Curl_gtls_cleanup
-#define curlssl_connect Curl_gtls_connect
-#define curlssl_connect_nonblocking Curl_gtls_connect_nonblocking
-#define curlssl_session_free(x) Curl_gtls_session_free(x)
-#define curlssl_close_all(x) ((void)x)
-#define curlssl_close Curl_gtls_close
-#define curlssl_shutdown(x,y) Curl_gtls_shutdown(x,y)
-#define curlssl_set_engine(x,y) ((void)x, (void)y, CURLE_NOT_BUILT_IN)
-#define curlssl_set_engine_default(x) ((void)x, CURLE_NOT_BUILT_IN)
-#define curlssl_engines_list(x) ((void)x, (struct curl_slist *)NULL)
-#define curlssl_version Curl_gtls_version
-#define curlssl_check_cxn(x) ((void)x, -1)
-#define curlssl_data_pending(x,y) Curl_gtls_data_pending(x,y)
-#define curlssl_random(x,y,z) Curl_gtls_random(x,y,z)
-#define curlssl_md5sum(a,b,c,d) Curl_gtls_md5sum(a,b,c,d)
-#define curlssl_sha256sum(a,b,c,d) Curl_gtls_sha256sum(a,b,c,d)
-#define curlssl_cert_status_request() Curl_gtls_cert_status_request()
+extern const struct Curl_ssl Curl_ssl_gnutls;
#endif /* USE_GNUTLS */
#endif /* HEADER_CURL_GTLS_H */
diff --git a/Utilities/cmcurl/lib/vtls/mbedtls.c b/Utilities/cmcurl/lib/vtls/mbedtls.c
index 037babe38..ce1f8eba8 100644
--- a/Utilities/cmcurl/lib/vtls/mbedtls.c
+++ b/Utilities/cmcurl/lib/vtls/mbedtls.c
@@ -61,6 +61,21 @@
#include "curl_memory.h"
#include "memdebug.h"
+struct ssl_backend_data {
+ mbedtls_ctr_drbg_context ctr_drbg;
+ mbedtls_entropy_context entropy;
+ mbedtls_ssl_context ssl;
+ int server_fd;
+ mbedtls_x509_crt cacert;
+ mbedtls_x509_crt clicert;
+ mbedtls_x509_crl crl;
+ mbedtls_pk_context pk;
+ mbedtls_ssl_config config;
+ const char *protocols[3];
+};
+
+#define BACKEND connssl->backend
+
/* apply threading? */
#if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)
#define THREADING_SUPPORT
@@ -214,9 +229,9 @@ set_ssl_version_min_max(struct connectdata *conn, int sockindex)
return result;
}
- mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,
+ mbedtls_ssl_conf_min_version(&BACKEND->config, MBEDTLS_SSL_MAJOR_VERSION_3,
mbedtls_ver_min);
- mbedtls_ssl_conf_max_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,
+ mbedtls_ssl_conf_max_version(&BACKEND->config, MBEDTLS_SSL_MAJOR_VERSION_3,
mbedtls_ver_max);
return result;
@@ -238,7 +253,7 @@ mbed_connect_step1(struct connectdata *conn,
const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
int ret = -1;
char errorbuf[128];
- errorbuf[0]=0;
+ errorbuf[0] = 0;
/* mbedTLS only supports SSLv3 and TLSv1 */
if(SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv2) {
@@ -248,9 +263,9 @@ mbed_connect_step1(struct connectdata *conn,
#ifdef THREADING_SUPPORT
entropy_init_mutex(&ts_entropy);
- mbedtls_ctr_drbg_init(&connssl->ctr_drbg);
+ mbedtls_ctr_drbg_init(&BACKEND->ctr_drbg);
- ret = mbedtls_ctr_drbg_seed(&connssl->ctr_drbg, entropy_func_mutex,
+ ret = mbedtls_ctr_drbg_seed(&BACKEND->ctr_drbg, entropy_func_mutex,
&ts_entropy, NULL, 0);
if(ret) {
#ifdef MBEDTLS_ERROR_C
@@ -260,11 +275,11 @@ mbed_connect_step1(struct connectdata *conn,
-ret, errorbuf);
}
#else
- mbedtls_entropy_init(&connssl->entropy);
- mbedtls_ctr_drbg_init(&connssl->ctr_drbg);
+ mbedtls_entropy_init(&BACKEND->entropy);
+ mbedtls_ctr_drbg_init(&BACKEND->ctr_drbg);
- ret = mbedtls_ctr_drbg_seed(&connssl->ctr_drbg, mbedtls_entropy_func,
- &connssl->entropy, NULL, 0);
+ ret = mbedtls_ctr_drbg_seed(&BACKEND->ctr_drbg, mbedtls_entropy_func,
+ &BACKEND->entropy, NULL, 0);
if(ret) {
#ifdef MBEDTLS_ERROR_C
mbedtls_strerror(ret, errorbuf, sizeof(errorbuf));
@@ -275,10 +290,10 @@ mbed_connect_step1(struct connectdata *conn,
#endif /* THREADING_SUPPORT */
/* Load the trusted CA */
- mbedtls_x509_crt_init(&connssl->cacert);
+ mbedtls_x509_crt_init(&BACKEND->cacert);
if(ssl_cafile) {
- ret = mbedtls_x509_crt_parse_file(&connssl->cacert, ssl_cafile);
+ ret = mbedtls_x509_crt_parse_file(&BACKEND->cacert, ssl_cafile);
if(ret<0) {
#ifdef MBEDTLS_ERROR_C
@@ -293,7 +308,7 @@ mbed_connect_step1(struct connectdata *conn,
}
if(ssl_capath) {
- ret = mbedtls_x509_crt_parse_path(&connssl->cacert, ssl_capath);
+ ret = mbedtls_x509_crt_parse_path(&BACKEND->cacert, ssl_capath);
if(ret<0) {
#ifdef MBEDTLS_ERROR_C
@@ -308,10 +323,10 @@ mbed_connect_step1(struct connectdata *conn,
}
/* Load the client certificate */
- mbedtls_x509_crt_init(&connssl->clicert);
+ mbedtls_x509_crt_init(&BACKEND->clicert);
if(ssl_cert) {
- ret = mbedtls_x509_crt_parse_file(&connssl->clicert, ssl_cert);
+ ret = mbedtls_x509_crt_parse_file(&BACKEND->clicert, ssl_cert);
if(ret) {
#ifdef MBEDTLS_ERROR_C
@@ -325,12 +340,12 @@ mbed_connect_step1(struct connectdata *conn,
}
/* Load the client private key */
- mbedtls_pk_init(&connssl->pk);
+ mbedtls_pk_init(&BACKEND->pk);
if(SSL_SET_OPTION(key)) {
- ret = mbedtls_pk_parse_keyfile(&connssl->pk, SSL_SET_OPTION(key),
+ ret = mbedtls_pk_parse_keyfile(&BACKEND->pk, SSL_SET_OPTION(key),
SSL_SET_OPTION(key_passwd));
- if(ret == 0 && !mbedtls_pk_can_do(&connssl->pk, MBEDTLS_PK_RSA))
+ if(ret == 0 && !mbedtls_pk_can_do(&BACKEND->pk, MBEDTLS_PK_RSA))
ret = MBEDTLS_ERR_PK_TYPE_MISMATCH;
if(ret) {
@@ -345,10 +360,10 @@ mbed_connect_step1(struct connectdata *conn,
}
/* Load the CRL */
- mbedtls_x509_crl_init(&connssl->crl);
+ mbedtls_x509_crl_init(&BACKEND->crl);
if(ssl_crlfile) {
- ret = mbedtls_x509_crl_parse_file(&connssl->crl, ssl_crlfile);
+ ret = mbedtls_x509_crl_parse_file(&BACKEND->crl, ssl_crlfile);
if(ret) {
#ifdef MBEDTLS_ERROR_C
@@ -363,14 +378,14 @@ mbed_connect_step1(struct connectdata *conn,
infof(data, "mbedTLS: Connecting to %s:%d\n", hostname, port);
- mbedtls_ssl_config_init(&connssl->config);
+ mbedtls_ssl_config_init(&BACKEND->config);
- mbedtls_ssl_init(&connssl->ssl);
- if(mbedtls_ssl_setup(&connssl->ssl, &connssl->config)) {
+ mbedtls_ssl_init(&BACKEND->ssl);
+ if(mbedtls_ssl_setup(&BACKEND->ssl, &BACKEND->config)) {
failf(data, "mbedTLS: ssl_init failed");
return CURLE_SSL_CONNECT_ERROR;
}
- ret = mbedtls_ssl_config_defaults(&connssl->config,
+ ret = mbedtls_ssl_config_defaults(&BACKEND->config,
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
@@ -380,20 +395,20 @@ mbed_connect_step1(struct connectdata *conn,
}
/* new profile with RSA min key len = 1024 ... */
- mbedtls_ssl_conf_cert_profile(&connssl->config,
+ mbedtls_ssl_conf_cert_profile(&BACKEND->config,
&mbedtls_x509_crt_profile_fr);
switch(SSL_CONN_CONFIG(version)) {
case CURL_SSLVERSION_DEFAULT:
case CURL_SSLVERSION_TLSv1:
- mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,
+ mbedtls_ssl_conf_min_version(&BACKEND->config, MBEDTLS_SSL_MAJOR_VERSION_3,
MBEDTLS_SSL_MINOR_VERSION_1);
infof(data, "mbedTLS: Set min SSL version to TLS 1.0\n");
break;
case CURL_SSLVERSION_SSLv3:
- mbedtls_ssl_conf_min_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,
+ mbedtls_ssl_conf_min_version(&BACKEND->config, MBEDTLS_SSL_MAJOR_VERSION_3,
MBEDTLS_SSL_MINOR_VERSION_0);
- mbedtls_ssl_conf_max_version(&connssl->config, MBEDTLS_SSL_MAJOR_VERSION_3,
+ mbedtls_ssl_conf_max_version(&BACKEND->config, MBEDTLS_SSL_MAJOR_VERSION_3,
MBEDTLS_SSL_MINOR_VERSION_0);
infof(data, "mbedTLS: Set SSL version to SSLv3\n");
break;
@@ -412,25 +427,25 @@ mbed_connect_step1(struct connectdata *conn,
return CURLE_SSL_CONNECT_ERROR;
}
- mbedtls_ssl_conf_authmode(&connssl->config, MBEDTLS_SSL_VERIFY_OPTIONAL);
+ mbedtls_ssl_conf_authmode(&BACKEND->config, MBEDTLS_SSL_VERIFY_OPTIONAL);
- mbedtls_ssl_conf_rng(&connssl->config, mbedtls_ctr_drbg_random,
- &connssl->ctr_drbg);
- mbedtls_ssl_set_bio(&connssl->ssl, &conn->sock[sockindex],
+ mbedtls_ssl_conf_rng(&BACKEND->config, mbedtls_ctr_drbg_random,
+ &BACKEND->ctr_drbg);
+ mbedtls_ssl_set_bio(&BACKEND->ssl, &conn->sock[sockindex],
mbedtls_net_send,
mbedtls_net_recv,
NULL /* rev_timeout() */);
- mbedtls_ssl_conf_ciphersuites(&connssl->config,
+ mbedtls_ssl_conf_ciphersuites(&BACKEND->config,
mbedtls_ssl_list_ciphersuites());
#if defined(MBEDTLS_SSL_RENEGOTIATION)
- mbedtls_ssl_conf_renegotiation(&connssl->config,
+ mbedtls_ssl_conf_renegotiation(&BACKEND->config,
MBEDTLS_SSL_RENEGOTIATION_ENABLED);
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
- mbedtls_ssl_conf_session_tickets(&connssl->config,
+ mbedtls_ssl_conf_session_tickets(&BACKEND->config,
MBEDTLS_SSL_SESSION_TICKETS_DISABLED);
#endif
@@ -440,7 +455,7 @@ mbed_connect_step1(struct connectdata *conn,
Curl_ssl_sessionid_lock(conn);
if(!Curl_ssl_getsessionid(conn, &old_session, NULL, sockindex)) {
- ret = mbedtls_ssl_set_session(&connssl->ssl, old_session);
+ ret = mbedtls_ssl_set_session(&BACKEND->ssl, old_session);
if(ret) {
Curl_ssl_sessionid_unlock(conn);
failf(data, "mbedtls_ssl_set_session returned -0x%x", -ret);
@@ -451,15 +466,15 @@ mbed_connect_step1(struct connectdata *conn,
Curl_ssl_sessionid_unlock(conn);
}
- mbedtls_ssl_conf_ca_chain(&connssl->config,
- &connssl->cacert,
- &connssl->crl);
+ mbedtls_ssl_conf_ca_chain(&BACKEND->config,
+ &BACKEND->cacert,
+ &BACKEND->crl);
if(SSL_SET_OPTION(key)) {
- mbedtls_ssl_conf_own_cert(&connssl->config,
- &connssl->clicert, &connssl->pk);
+ mbedtls_ssl_conf_own_cert(&BACKEND->config,
+ &BACKEND->clicert, &BACKEND->pk);
}
- if(mbedtls_ssl_set_hostname(&connssl->ssl, hostname)) {
+ if(mbedtls_ssl_set_hostname(&BACKEND->ssl, hostname)) {
/* mbedtls_ssl_set_hostname() sets the name to use in CN/SAN checks *and*
the name to set in the SNI extension. So even if curl connects to a
host specified as an IP address, this function must be used. */
@@ -469,7 +484,7 @@ mbed_connect_step1(struct connectdata *conn,
#ifdef HAS_ALPN
if(conn->bits.tls_enable_alpn) {
- const char **p = &connssl->protocols[0];
+ const char **p = &BACKEND->protocols[0];
#ifdef USE_NGHTTP2
if(data->set.httpversion >= CURL_HTTP_VERSION_2)
*p++ = NGHTTP2_PROTO_VERSION_ID;
@@ -478,19 +493,19 @@ mbed_connect_step1(struct connectdata *conn,
*p = NULL;
/* this function doesn't clone the protocols array, which is why we need
to keep it around */
- if(mbedtls_ssl_conf_alpn_protocols(&connssl->config,
- &connssl->protocols[0])) {
+ if(mbedtls_ssl_conf_alpn_protocols(&BACKEND->config,
+ &BACKEND->protocols[0])) {
failf(data, "Failed setting ALPN protocols");
return CURLE_SSL_CONNECT_ERROR;
}
- for(p = &connssl->protocols[0]; *p; ++p)
+ for(p = &BACKEND->protocols[0]; *p; ++p)
infof(data, "ALPN, offering %s\n", *p);
}
#endif
#ifdef MBEDTLS_DEBUG
/* In order to make that work in mbedtls MBEDTLS_DEBUG_C must be defined. */
- mbedtls_ssl_conf_dbg(&connssl->config, mbed_debug, data);
+ mbedtls_ssl_conf_dbg(&BACKEND->config, mbed_debug, data);
/* - 0 No debug
* - 1 Error
* - 2 State change
@@ -502,7 +517,7 @@ mbed_connect_step1(struct connectdata *conn,
/* give application a chance to interfere with mbedTLS set up. */
if(data->set.ssl.fsslctx) {
- ret = (*data->set.ssl.fsslctx)(data, &connssl->config,
+ ret = (*data->set.ssl.fsslctx)(data, &BACKEND->config,
data->set.ssl.fsslctxp);
if(ret) {
failf(data, "error signaled by ssl ctx callback");
@@ -537,7 +552,7 @@ mbed_connect_step2(struct connectdata *conn,
conn->recv[sockindex] = mbed_recv;
conn->send[sockindex] = mbed_send;
- ret = mbedtls_ssl_handshake(&connssl->ssl);
+ ret = mbedtls_ssl_handshake(&BACKEND->ssl);
if(ret == MBEDTLS_ERR_SSL_WANT_READ) {
connssl->connecting_state = ssl_connect_2_reading;
@@ -557,10 +572,10 @@ mbed_connect_step2(struct connectdata *conn,
}
infof(data, "mbedTLS: Handshake complete, cipher is %s\n",
- mbedtls_ssl_get_ciphersuite(&conn->ssl[sockindex].ssl)
+ mbedtls_ssl_get_ciphersuite(&BACKEND->ssl)
);
- ret = mbedtls_ssl_get_verify_result(&conn->ssl[sockindex].ssl);
+ ret = mbedtls_ssl_get_verify_result(&BACKEND->ssl);
if(ret && SSL_CONN_CONFIG(verifypeer)) {
if(ret & MBEDTLS_X509_BADCERT_EXPIRED)
@@ -580,7 +595,7 @@ mbed_connect_step2(struct connectdata *conn,
return CURLE_PEER_FAILED_VERIFICATION;
}
- peercert = mbedtls_ssl_get_peer_cert(&connssl->ssl);
+ peercert = mbedtls_ssl_get_peer_cert(&BACKEND->ssl);
if(peercert && data->set.verbose) {
const size_t bufsize = 16384;
@@ -650,7 +665,7 @@ mbed_connect_step2(struct connectdata *conn,
#ifdef HAS_ALPN
if(conn->bits.tls_enable_alpn) {
- next_protocol = mbedtls_ssl_get_alpn_protocol(&connssl->ssl);
+ next_protocol = mbedtls_ssl_get_alpn_protocol(&BACKEND->ssl);
if(next_protocol) {
infof(data, "ALPN, server accepted to use %s\n", next_protocol);
@@ -700,7 +715,7 @@ mbed_connect_step3(struct connectdata *conn,
mbedtls_ssl_session_init(our_ssl_sessionid);
- ret = mbedtls_ssl_get_session(&connssl->ssl, our_ssl_sessionid);
+ ret = mbedtls_ssl_get_session(&BACKEND->ssl, our_ssl_sessionid);
if(ret) {
free(our_ssl_sessionid);
failf(data, "mbedtls_ssl_get_session returned -0x%x", -ret);
@@ -730,9 +745,10 @@ static ssize_t mbed_send(struct connectdata *conn, int sockindex,
const void *mem, size_t len,
CURLcode *curlcode)
{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
int ret = -1;
- ret = mbedtls_ssl_write(&conn->ssl[sockindex].ssl,
+ ret = mbedtls_ssl_write(&BACKEND->ssl,
(unsigned char *)mem, len);
if(ret < 0) {
@@ -744,22 +760,23 @@ static ssize_t mbed_send(struct connectdata *conn, int sockindex,
return ret;
}
-void Curl_mbedtls_close_all(struct Curl_easy *data)
+static void Curl_mbedtls_close_all(struct Curl_easy *data)
{
(void)data;
}
-void Curl_mbedtls_close(struct connectdata *conn, int sockindex)
+static void Curl_mbedtls_close(struct connectdata *conn, int sockindex)
{
- mbedtls_pk_free(&conn->ssl[sockindex].pk);
- mbedtls_x509_crt_free(&conn->ssl[sockindex].clicert);
- mbedtls_x509_crt_free(&conn->ssl[sockindex].cacert);
- mbedtls_x509_crl_free(&conn->ssl[sockindex].crl);
- mbedtls_ssl_config_free(&conn->ssl[sockindex].config);
- mbedtls_ssl_free(&conn->ssl[sockindex].ssl);
- mbedtls_ctr_drbg_free(&conn->ssl[sockindex].ctr_drbg);
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ mbedtls_pk_free(&BACKEND->pk);
+ mbedtls_x509_crt_free(&BACKEND->clicert);
+ mbedtls_x509_crt_free(&BACKEND->cacert);
+ mbedtls_x509_crl_free(&BACKEND->crl);
+ mbedtls_ssl_config_free(&BACKEND->config);
+ mbedtls_ssl_free(&BACKEND->ssl);
+ mbedtls_ctr_drbg_free(&BACKEND->ctr_drbg);
#ifndef THREADING_SUPPORT
- mbedtls_entropy_free(&conn->ssl[sockindex].entropy);
+ mbedtls_entropy_free(&BACKEND->entropy);
#endif /* THREADING_SUPPORT */
}
@@ -767,11 +784,12 @@ static ssize_t mbed_recv(struct connectdata *conn, int num,
char *buf, size_t buffersize,
CURLcode *curlcode)
{
+ struct ssl_connect_data *connssl = &conn->ssl[num];
int ret = -1;
ssize_t len = -1;
memset(buf, 0, buffersize);
- ret = mbedtls_ssl_read(&conn->ssl[num].ssl, (unsigned char *)buf,
+ ret = mbedtls_ssl_read(&BACKEND->ssl, (unsigned char *)buf,
buffersize);
if(ret <= 0) {
@@ -788,21 +806,21 @@ static ssize_t mbed_recv(struct connectdata *conn, int num,
return len;
}
-void Curl_mbedtls_session_free(void *ptr)
+static void Curl_mbedtls_session_free(void *ptr)
{
mbedtls_ssl_session_free(ptr);
free(ptr);
}
-size_t Curl_mbedtls_version(char *buffer, size_t size)
+static size_t Curl_mbedtls_version(char *buffer, size_t size)
{
unsigned int version = mbedtls_version_get_number();
return snprintf(buffer, size, "mbedTLS/%d.%d.%d", version>>24,
(version>>16)&0xff, (version>>8)&0xff);
}
-CURLcode Curl_mbedtls_random(struct Curl_easy *data, unsigned char *entropy,
- size_t length)
+static CURLcode Curl_mbedtls_random(struct Curl_easy *data,
+ unsigned char *entropy, size_t length)
{
#if defined(MBEDTLS_CTR_DRBG_C)
int ret = -1;
@@ -811,7 +829,7 @@ CURLcode Curl_mbedtls_random(struct Curl_easy *data, unsigned char *entropy,
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_entropy_init(&ctr_entropy);
mbedtls_ctr_drbg_init(&ctr_drbg);
- errorbuf[0]=0;
+ errorbuf[0] = 0;
ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func,
&ctr_entropy, NULL, 0);
@@ -869,7 +887,7 @@ mbed_connect_common(struct connectdata *conn,
return CURLE_OK;
}
- if(ssl_connect_1==connssl->connecting_state) {
+ if(ssl_connect_1 == connssl->connecting_state) {
/* Find out how much more time we're allowed */
timeout_ms = Curl_timeleft(data, NULL, TRUE);
@@ -900,9 +918,9 @@ mbed_connect_common(struct connectdata *conn,
if(connssl->connecting_state == ssl_connect_2_reading
|| connssl->connecting_state == ssl_connect_2_writing) {
- curl_socket_t writefd = ssl_connect_2_writing==
+ curl_socket_t writefd = ssl_connect_2_writing ==
connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
- curl_socket_t readfd = ssl_connect_2_reading==
+ curl_socket_t readfd = ssl_connect_2_reading ==
connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
@@ -942,13 +960,13 @@ mbed_connect_common(struct connectdata *conn,
} /* repeat step2 until all transactions are done. */
- if(ssl_connect_3==connssl->connecting_state) {
+ if(ssl_connect_3 == connssl->connecting_state) {
retcode = mbed_connect_step3(conn, sockindex);
if(retcode)
return retcode;
}
- if(ssl_connect_done==connssl->connecting_state) {
+ if(ssl_connect_done == connssl->connecting_state) {
connssl->state = ssl_connection_complete;
conn->recv[sockindex] = mbed_recv;
conn->send[sockindex] = mbed_send;
@@ -963,18 +981,14 @@ mbed_connect_common(struct connectdata *conn,
return CURLE_OK;
}
-CURLcode
-Curl_mbedtls_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done)
+static CURLcode Curl_mbedtls_connect_nonblocking(struct connectdata *conn,
+ int sockindex, bool *done)
{
return mbed_connect_common(conn, sockindex, TRUE, done);
}
-CURLcode
-Curl_mbedtls_connect(struct connectdata *conn,
- int sockindex)
+static CURLcode Curl_mbedtls_connect(struct connectdata *conn, int sockindex)
{
CURLcode retcode;
bool done = FALSE;
@@ -992,19 +1006,70 @@ Curl_mbedtls_connect(struct connectdata *conn,
* return 0 error initializing SSL
* return 1 SSL initialized successfully
*/
-int Curl_mbedtls_init(void)
+static int Curl_mbedtls_init(void)
{
return Curl_polarsslthreadlock_thread_setup();
}
-void Curl_mbedtls_cleanup(void)
+static void Curl_mbedtls_cleanup(void)
{
(void)Curl_polarsslthreadlock_thread_cleanup();
}
-int Curl_mbedtls_data_pending(const struct connectdata *conn, int sockindex)
+static bool Curl_mbedtls_data_pending(const struct connectdata *conn,
+ int sockindex)
{
- return mbedtls_ssl_get_bytes_avail(&conn->ssl[sockindex].ssl) != 0;
+ const struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ return mbedtls_ssl_get_bytes_avail(&BACKEND->ssl) != 0;
}
+static void Curl_mbedtls_sha256sum(const unsigned char *input,
+ size_t inputlen,
+ unsigned char *sha256sum,
+ size_t sha256len UNUSED_PARAM)
+{
+ (void)sha256len;
+ mbedtls_sha256(input, inputlen, sha256sum, 0);
+}
+
+static void *Curl_mbedtls_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info UNUSED_PARAM)
+{
+ (void)info;
+ return &BACKEND->ssl;
+}
+
+const struct Curl_ssl Curl_ssl_mbedtls = {
+ { CURLSSLBACKEND_MBEDTLS, "mbedtls" }, /* info */
+
+ 1, /* have_ca_path */
+ 0, /* have_certinfo */
+ 1, /* have_pinnedpubkey */
+ 1, /* have_ssl_ctx */
+ 0, /* support_https_proxy */
+
+ sizeof(struct ssl_backend_data),
+
+ Curl_mbedtls_init, /* init */
+ Curl_mbedtls_cleanup, /* cleanup */
+ Curl_mbedtls_version, /* version */
+ Curl_none_check_cxn, /* check_cxn */
+ Curl_none_shutdown, /* shutdown */
+ Curl_mbedtls_data_pending, /* data_pending */
+ Curl_mbedtls_random, /* random */
+ Curl_none_cert_status_request, /* cert_status_request */
+ Curl_mbedtls_connect, /* connect */
+ Curl_mbedtls_connect_nonblocking, /* connect_nonblocking */
+ Curl_mbedtls_get_internals, /* get_internals */
+ Curl_mbedtls_close, /* close */
+ Curl_mbedtls_close_all, /* close_all */
+ Curl_mbedtls_session_free, /* session_free */
+ Curl_none_set_engine, /* set_engine */
+ Curl_none_set_engine_default, /* set_engine_default */
+ Curl_none_engines_list, /* engines_list */
+ Curl_none_false_start, /* false_start */
+ Curl_none_md5sum, /* md5sum */
+ Curl_mbedtls_sha256sum /* sha256sum */
+};
+
#endif /* USE_MBEDTLS */
diff --git a/Utilities/cmcurl/lib/vtls/mbedtls.h b/Utilities/cmcurl/lib/vtls/mbedtls.h
index 71d17a491..4a938605b 100644
--- a/Utilities/cmcurl/lib/vtls/mbedtls.h
+++ b/Utilities/cmcurl/lib/vtls/mbedtls.h
@@ -26,57 +26,7 @@
#ifdef USE_MBEDTLS
-#include <mbedtls/sha256.h>
-
-/* Called on first use mbedTLS, setup threading if supported */
-int Curl_mbedtls_init(void);
-void Curl_mbedtls_cleanup(void);
-int Curl_mbedtls_data_pending(const struct connectdata *conn, int sockindex);
-
-CURLcode Curl_mbedtls_connect(struct connectdata *conn, int sockindex);
-
-CURLcode Curl_mbedtls_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done);
-
-/* tell mbedTLS to close down all open information regarding connections (and
- thus session ID caching etc) */
-void Curl_mbedtls_close_all(struct Curl_easy *data);
-
- /* close a SSL connection */
-void Curl_mbedtls_close(struct connectdata *conn, int sockindex);
-
-void Curl_mbedtls_session_free(void *ptr);
-size_t Curl_mbedtls_version(char *buffer, size_t size);
-int Curl_mbedtls_shutdown(struct connectdata *conn, int sockindex);
-
-CURLcode Curl_mbedtls_random(struct Curl_easy *data, unsigned char *entropy,
- size_t length);
-
-/* this backends supports CURLOPT_PINNEDPUBLICKEY */
-#define have_curlssl_pinnedpubkey 1
-
-/* this backend supports CURLOPT_SSL_CTX_* */
-#define have_curlssl_ssl_ctx 1
-
-/* API setup for mbedTLS */
-#define curlssl_init() Curl_mbedtls_init()
-#define curlssl_cleanup() Curl_mbedtls_cleanup()
-#define curlssl_connect Curl_mbedtls_connect
-#define curlssl_connect_nonblocking Curl_mbedtls_connect_nonblocking
-#define curlssl_session_free(x) Curl_mbedtls_session_free(x)
-#define curlssl_close_all Curl_mbedtls_close_all
-#define curlssl_close Curl_mbedtls_close
-#define curlssl_shutdown(x,y) 0
-#define curlssl_set_engine(x,y) (x=x, y=y, CURLE_NOT_BUILT_IN)
-#define curlssl_set_engine_default(x) (x=x, CURLE_NOT_BUILT_IN)
-#define curlssl_engines_list(x) (x=x, (struct curl_slist *)NULL)
-#define curlssl_version Curl_mbedtls_version
-#define curlssl_check_cxn(x) (x=x, -1)
-#define curlssl_data_pending(x,y) Curl_mbedtls_data_pending(x, y)
-#define CURL_SSL_BACKEND CURLSSLBACKEND_MBEDTLS
-#define curlssl_sha256sum(a,b,c,d) mbedtls_sha256(a,b,c,0)
-#define curlssl_random(x,y,z) Curl_mbedtls_random(x, y, z)
+extern const struct Curl_ssl Curl_ssl_mbedtls;
#endif /* USE_MBEDTLS */
#endif /* HEADER_CURL_MBEDTLS_H */
diff --git a/Utilities/cmcurl/lib/vtls/nss.c b/Utilities/cmcurl/lib/vtls/nss.c
index cd0138930..c0b7e63ab 100644
--- a/Utilities/cmcurl/lib/vtls/nss.c
+++ b/Utilities/cmcurl/lib/vtls/nss.c
@@ -78,6 +78,16 @@
/* enough to fit the string "PEM Token #[0|1]" */
#define SLOTSIZE 13
+struct ssl_backend_data {
+ PRFileDesc *handle;
+ char *client_nickname;
+ struct Curl_easy *data;
+ struct curl_llist obj_list;
+ PK11GenericObject *obj_clicert;
+};
+
+#define BACKEND connssl->backend
+
static PRLock *nss_initlock = NULL;
static PRLock *nss_crllock = NULL;
static PRLock *nss_findslot_lock = NULL;
@@ -271,7 +281,7 @@ static SECStatus set_ciphers(struct Curl_easy *data, PRFileDesc * model,
found = PR_FALSE;
- for(i=0; i<NUM_OF_CIPHERS; i++) {
+ for(i = 0; i<NUM_OF_CIPHERS; i++) {
if(strcasecompare(cipher, cipherlist[i].name)) {
cipher_state[i] = PR_TRUE;
found = PR_TRUE;
@@ -290,7 +300,7 @@ static SECStatus set_ciphers(struct Curl_easy *data, PRFileDesc * model,
}
/* Finally actually enable the selected ciphers */
- for(i=0; i<NUM_OF_CIPHERS; i++) {
+ for(i = 0; i<NUM_OF_CIPHERS; i++) {
if(!cipher_state[i])
continue;
@@ -311,7 +321,7 @@ static bool any_cipher_enabled(void)
{
unsigned int i;
- for(i=0; i<NUM_OF_CIPHERS; i++) {
+ for(i = 0; i<NUM_OF_CIPHERS; i++) {
PRInt32 policy = 0;
SSL_CipherPolicyGet(cipherlist[i].num, &policy);
if(policy)
@@ -396,7 +406,7 @@ static CURLcode insert_wrapped_ptr(struct curl_llist *list, void *ptr)
/* Call PK11_CreateGenericObject() with the given obj_class and filename. If
* the call succeeds, append the object handle to the list of objects so that
* the object can be destroyed in Curl_nss_close(). */
-static CURLcode nss_create_object(struct ssl_connect_data *ssl,
+static CURLcode nss_create_object(struct ssl_connect_data *connssl,
CK_OBJECT_CLASS obj_class,
const char *filename, bool cacert)
{
@@ -435,14 +445,14 @@ static CURLcode nss_create_object(struct ssl_connect_data *ssl,
if(!obj)
return result;
- if(insert_wrapped_ptr(&ssl->obj_list, obj) != CURLE_OK) {
+ if(insert_wrapped_ptr(&BACKEND->obj_list, obj) != CURLE_OK) {
PK11_DestroyGenericObject(obj);
return CURLE_OUT_OF_MEMORY;
}
if(!cacert && CKO_CERTIFICATE == obj_class)
/* store reference to a client certificate */
- ssl->obj_clicert = obj;
+ BACKEND->obj_clicert = obj;
return CURLE_OK;
}
@@ -992,7 +1002,7 @@ static SECStatus check_issuer_cert(PRFileDesc *sock,
char *issuer_nickname)
{
CERTCertificate *cert, *cert_issuer, *issuer;
- SECStatus res=SECSuccess;
+ SECStatus res = SECSuccess;
void *proto_win = NULL;
cert = SSL_PeerCertificate(sock);
@@ -1004,7 +1014,7 @@ static SECStatus check_issuer_cert(PRFileDesc *sock,
if((!cert_issuer) || (!issuer))
res = SECFailure;
else if(SECITEM_CompareItem(&cert_issuer->derCert,
- &issuer->derCert)!=SECEqual)
+ &issuer->derCert) != SECEqual)
res = SECFailure;
CERT_DestroyCertificate(cert);
@@ -1017,7 +1027,7 @@ static CURLcode cmp_peer_pubkey(struct ssl_connect_data *connssl,
const char *pinnedpubkey)
{
CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
- struct Curl_easy *data = connssl->data;
+ struct Curl_easy *data = BACKEND->data;
CERTCertificate *cert;
if(!pinnedpubkey)
@@ -1025,7 +1035,7 @@ static CURLcode cmp_peer_pubkey(struct ssl_connect_data *connssl,
return CURLE_OK;
/* get peer certificate */
- cert = SSL_PeerCertificate(connssl->handle);
+ cert = SSL_PeerCertificate(BACKEND->handle);
if(cert) {
/* extract public key from peer certificate */
SECKEYPublicKey *pubkey = CERT_ExtractPublicKey(cert);
@@ -1069,11 +1079,11 @@ static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
struct SECKEYPrivateKeyStr **pRetKey)
{
struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
- struct Curl_easy *data = connssl->data;
- const char *nickname = connssl->client_nickname;
+ struct Curl_easy *data = BACKEND->data;
+ const char *nickname = BACKEND->client_nickname;
static const char pem_slotname[] = "PEM Token #1";
- if(connssl->obj_clicert) {
+ if(BACKEND->obj_clicert) {
/* use the cert/key provided by PEM reader */
SECItem cert_der = { 0, NULL, 0 };
void *proto_win = SSL_RevealPinArg(sock);
@@ -1086,7 +1096,7 @@ static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
return SECFailure;
}
- if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
+ if(PK11_ReadRawAttribute(PK11_TypeGeneric, BACKEND->obj_clicert, CKA_VALUE,
&cert_der) != SECSuccess) {
failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
PK11_FreeSlot(slot);
@@ -1351,7 +1361,7 @@ static CURLcode nss_init(struct Curl_easy *data)
* @retval 0 error initializing SSL
* @retval 1 SSL initialized successfully
*/
-int Curl_nss_init(void)
+static int Curl_nss_init(void)
{
/* curl_global_init() is not thread-safe so this test is ok */
if(nss_initlock == NULL) {
@@ -1386,7 +1396,7 @@ CURLcode Curl_nss_force_init(struct Curl_easy *data)
}
/* Global cleanup */
-void Curl_nss_cleanup(void)
+static void Curl_nss_cleanup(void)
{
/* This function isn't required to be threadsafe and this is only done
* as a safety feature.
@@ -1426,14 +1436,14 @@ void Curl_nss_cleanup(void)
* 0 means the connection has been closed
* -1 means the connection status is unknown
*/
-int
-Curl_nss_check_cxn(struct connectdata *conn)
+static int Curl_nss_check_cxn(struct connectdata *conn)
{
+ struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET];
int rc;
char buf;
rc =
- PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
+ PR_Recv(BACKEND->handle, (void *)&buf, 1, PR_MSG_PEEK,
PR_SecondsToInterval(1));
if(rc > 0)
return 1; /* connection still in place */
@@ -1447,48 +1457,49 @@ Curl_nss_check_cxn(struct connectdata *conn)
static void nss_close(struct ssl_connect_data *connssl)
{
/* before the cleanup, check whether we are using a client certificate */
- const bool client_cert = (connssl->client_nickname != NULL)
- || (connssl->obj_clicert != NULL);
+ const bool client_cert = (BACKEND->client_nickname != NULL)
+ || (BACKEND->obj_clicert != NULL);
- free(connssl->client_nickname);
- connssl->client_nickname = NULL;
+ free(BACKEND->client_nickname);
+ BACKEND->client_nickname = NULL;
/* destroy all NSS objects in order to avoid failure of NSS shutdown */
- Curl_llist_destroy(&connssl->obj_list, NULL);
- connssl->obj_clicert = NULL;
+ Curl_llist_destroy(&BACKEND->obj_list, NULL);
+ BACKEND->obj_clicert = NULL;
- if(connssl->handle) {
+ if(BACKEND->handle) {
if(client_cert)
/* A server might require different authentication based on the
* particular path being requested by the client. To support this
* scenario, we must ensure that a connection will never reuse the
* authentication data from a previous connection. */
- SSL_InvalidateSession(connssl->handle);
+ SSL_InvalidateSession(BACKEND->handle);
- PR_Close(connssl->handle);
- connssl->handle = NULL;
+ PR_Close(BACKEND->handle);
+ BACKEND->handle = NULL;
}
}
/*
* This function is called when an SSL connection is closed.
*/
-void Curl_nss_close(struct connectdata *conn, int sockindex)
+static void Curl_nss_close(struct connectdata *conn, int sockindex)
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
struct ssl_connect_data *connssl_proxy = &conn->proxy_ssl[sockindex];
- if(connssl->handle || connssl_proxy->handle) {
+ if(BACKEND->handle || connssl_proxy->backend->handle) {
/* NSS closes the socket we previously handed to it, so we must mark it
as closed to avoid double close */
fake_sclose(conn->sock[sockindex]);
conn->sock[sockindex] = CURL_SOCKET_BAD;
}
- if(connssl->handle)
- /* nss_close(connssl) will transitively close also connssl_proxy->handle
- if both are used. Clear it to avoid a double close leading to crash. */
- connssl_proxy->handle = NULL;
+ if(BACKEND->handle)
+ /* nss_close(connssl) will transitively close also
+ connssl_proxy->backend->handle if both are used. Clear it to avoid
+ a double close leading to crash. */
+ connssl_proxy->backend->handle = NULL;
nss_close(connssl);
nss_close(connssl_proxy);
@@ -1732,7 +1743,7 @@ static CURLcode nss_fail_connect(struct ssl_connect_data *connssl,
}
/* cleanup on connection failure */
- Curl_llist_destroy(&connssl->obj_list, NULL);
+ Curl_llist_destroy(&BACKEND->obj_list, NULL);
return curlerr;
}
@@ -1746,7 +1757,7 @@ static CURLcode nss_set_blocking(struct ssl_connect_data *connssl,
sock_opt.option = PR_SockOpt_Nonblocking;
sock_opt.value.non_blocking = !blocking;
- if(PR_SetSocketOption(connssl->handle, &sock_opt) != PR_SUCCESS)
+ if(PR_SetSocketOption(BACKEND->handle, &sock_opt) != PR_SUCCESS)
return nss_fail_connect(connssl, data, CURLE_SSL_CONNECT_ERROR);
return CURLE_OK;
@@ -1770,10 +1781,10 @@ static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
SSL_LIBRARY_VERSION_TLS_1_0 /* max */
};
- connssl->data = data;
+ BACKEND->data = data;
/* list of all NSS objects we need to destroy in Curl_nss_close() */
- Curl_llist_init(&connssl->obj_list, nss_destroy_object);
+ Curl_llist_init(&BACKEND->obj_list, nss_destroy_object);
/* FIXME. NSS doesn't support multiple databases open at the same time. */
PR_Lock(nss_initlock);
@@ -1882,7 +1893,7 @@ static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
char *nickname = dup_nickname(data, SSL_SET_OPTION(cert));
if(nickname) {
/* we are not going to use libnsspem.so to read the client cert */
- connssl->obj_clicert = NULL;
+ BACKEND->obj_clicert = NULL;
}
else {
CURLcode rv = cert_stuff(conn, sockindex, SSL_SET_OPTION(cert),
@@ -1895,10 +1906,10 @@ static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
}
/* store the nickname for SelectClientCert() called during handshake */
- connssl->client_nickname = nickname;
+ BACKEND->client_nickname = nickname;
}
else
- connssl->client_nickname = NULL;
+ BACKEND->client_nickname = NULL;
if(SSL_GetClientAuthDataHook(model, SelectClientCert,
(void *)connssl) != SECSuccess) {
@@ -1908,8 +1919,8 @@ static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
if(conn->proxy_ssl[sockindex].use) {
DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
- DEBUGASSERT(conn->proxy_ssl[sockindex].handle != NULL);
- nspr_io = conn->proxy_ssl[sockindex].handle;
+ DEBUGASSERT(conn->proxy_ssl[sockindex].backend->handle != NULL);
+ nspr_io = conn->proxy_ssl[sockindex].backend->handle;
second_layer = TRUE;
}
else {
@@ -1939,8 +1950,8 @@ static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
}
/* import our model socket onto the current I/O stack */
- connssl->handle = SSL_ImportFD(model, nspr_io);
- if(!connssl->handle) {
+ BACKEND->handle = SSL_ImportFD(model, nspr_io);
+ if(!BACKEND->handle) {
if(!second_layer)
PR_Close(nspr_io);
goto error;
@@ -1951,36 +1962,36 @@ static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
/* This is the password associated with the cert that we're using */
if(SSL_SET_OPTION(key_passwd)) {
- SSL_SetPKCS11PinArg(connssl->handle, SSL_SET_OPTION(key_passwd));
+ SSL_SetPKCS11PinArg(BACKEND->handle, SSL_SET_OPTION(key_passwd));
}
#ifdef SSL_ENABLE_OCSP_STAPLING
if(SSL_CONN_CONFIG(verifystatus)) {
- if(SSL_OptionSet(connssl->handle, SSL_ENABLE_OCSP_STAPLING, PR_TRUE)
+ if(SSL_OptionSet(BACKEND->handle, SSL_ENABLE_OCSP_STAPLING, PR_TRUE)
!= SECSuccess)
goto error;
}
#endif
#ifdef SSL_ENABLE_NPN
- if(SSL_OptionSet(connssl->handle, SSL_ENABLE_NPN, conn->bits.tls_enable_npn
+ if(SSL_OptionSet(BACKEND->handle, SSL_ENABLE_NPN, conn->bits.tls_enable_npn
? PR_TRUE : PR_FALSE) != SECSuccess)
goto error;
#endif
#ifdef SSL_ENABLE_ALPN
- if(SSL_OptionSet(connssl->handle, SSL_ENABLE_ALPN, conn->bits.tls_enable_alpn
+ if(SSL_OptionSet(BACKEND->handle, SSL_ENABLE_ALPN, conn->bits.tls_enable_alpn
? PR_TRUE : PR_FALSE) != SECSuccess)
goto error;
#endif
#if NSSVERNUM >= 0x030f04 /* 3.15.4 */
if(data->set.ssl.falsestart) {
- if(SSL_OptionSet(connssl->handle, SSL_ENABLE_FALSE_START, PR_TRUE)
+ if(SSL_OptionSet(BACKEND->handle, SSL_ENABLE_FALSE_START, PR_TRUE)
!= SECSuccess)
goto error;
- if(SSL_SetCanFalseStartCallback(connssl->handle, CanFalseStartCallback,
+ if(SSL_SetCanFalseStartCallback(BACKEND->handle, CanFalseStartCallback,
conn) != SECSuccess)
goto error;
}
@@ -1992,7 +2003,8 @@ static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
unsigned char protocols[128];
#ifdef USE_NGHTTP2
- if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
+ if(data->set.httpversion >= CURL_HTTP_VERSION_2 &&
+ (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) {
protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
NGHTTP2_PROTO_VERSION_ID_LEN);
@@ -2003,24 +2015,24 @@ static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
cur += ALPN_HTTP_1_1_LENGTH;
- if(SSL_SetNextProtoNego(connssl->handle, protocols, cur) != SECSuccess)
+ if(SSL_SetNextProtoNego(BACKEND->handle, protocols, cur) != SECSuccess)
goto error;
}
#endif
/* Force handshake on next I/O */
- if(SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE)
+ if(SSL_ResetHandshake(BACKEND->handle, /* asServer */ PR_FALSE)
!= SECSuccess)
goto error;
/* propagate hostname to the TLS layer */
- if(SSL_SetURL(connssl->handle, SSL_IS_PROXY() ? conn->http_proxy.host.name :
+ if(SSL_SetURL(BACKEND->handle, SSL_IS_PROXY() ? conn->http_proxy.host.name :
conn->host.name) != SECSuccess)
goto error;
/* prevent NSS from re-using the session for a different hostname */
- if(SSL_SetSockPeerID(connssl->handle, SSL_IS_PROXY() ?
+ if(SSL_SetSockPeerID(BACKEND->handle, SSL_IS_PROXY() ?
conn->http_proxy.host.name : conn->host.name)
!= SECSuccess)
goto error;
@@ -2057,7 +2069,7 @@ static CURLcode nss_do_connect(struct connectdata *conn, int sockindex)
/* Force the handshake now */
timeout = PR_MillisecondsToInterval((PRUint32) time_left);
- if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
+ if(SSL_ForceHandshakeWithTimeout(BACKEND->handle, timeout) != SECSuccess) {
if(PR_GetError() == PR_WOULD_BLOCK_ERROR)
/* blocking direction is updated by nss_update_connecting_state() */
return CURLE_AGAIN;
@@ -2068,7 +2080,7 @@ static CURLcode nss_do_connect(struct connectdata *conn, int sockindex)
goto error;
}
- result = display_conn_info(conn, connssl->handle);
+ result = display_conn_info(conn, BACKEND->handle);
if(result)
goto error;
@@ -2077,7 +2089,7 @@ static CURLcode nss_do_connect(struct connectdata *conn, int sockindex)
char *nickname = dup_nickname(data, SSL_SET_OPTION(issuercert));
if(nickname) {
/* we support only nicknames in case of issuercert for now */
- ret = check_issuer_cert(connssl->handle, nickname);
+ ret = check_issuer_cert(BACKEND->handle, nickname);
free(nickname);
}
@@ -2163,13 +2175,13 @@ static CURLcode nss_connect_common(struct connectdata *conn, int sockindex,
return CURLE_OK;
}
-CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
+static CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
{
return nss_connect_common(conn, sockindex, /* blocking */ NULL);
}
-CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
- int sockindex, bool *done)
+static CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
+ int sockindex, bool *done)
{
return nss_connect_common(conn, sockindex, done);
}
@@ -2180,8 +2192,14 @@ static ssize_t nss_send(struct connectdata *conn, /* connection data */
size_t len, /* amount to write */
CURLcode *curlcode)
{
- ssize_t rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0,
- PR_INTERVAL_NO_WAIT);
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ ssize_t rc;
+
+ /* The SelectClientCert() hook uses this for infof() and failf() but the
+ handle stored in nss_setup_connect() could have already been freed. */
+ BACKEND->data = conn->data;
+
+ rc = PR_Send(BACKEND->handle, mem, (int)len, 0, PR_INTERVAL_NO_WAIT);
if(rc < 0) {
PRInt32 err = PR_GetError();
if(err == PR_WOULD_BLOCK_ERROR)
@@ -2205,14 +2223,21 @@ static ssize_t nss_send(struct connectdata *conn, /* connection data */
return rc; /* number of bytes */
}
-static ssize_t nss_recv(struct connectdata * conn, /* connection data */
- int num, /* socketindex */
+static ssize_t nss_recv(struct connectdata *conn, /* connection data */
+ int sockindex, /* socketindex */
char *buf, /* store read data here */
size_t buffersize, /* max amount to read */
CURLcode *curlcode)
{
- ssize_t nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0,
- PR_INTERVAL_NO_WAIT);
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ ssize_t nread;
+
+ /* The SelectClientCert() hook uses this for infof() and failf() but the
+ handle stored in nss_setup_connect() could have already been freed. */
+ BACKEND->data = conn->data;
+
+ nread = PR_Recv(BACKEND->handle, buf, (int)buffersize, 0,
+ PR_INTERVAL_NO_WAIT);
if(nread < 0) {
/* failed SSL read */
PRInt32 err = PR_GetError();
@@ -2238,22 +2263,22 @@ static ssize_t nss_recv(struct connectdata * conn, /* connection data */
return nread;
}
-size_t Curl_nss_version(char *buffer, size_t size)
+static size_t Curl_nss_version(char *buffer, size_t size)
{
return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
}
/* data might be NULL */
-int Curl_nss_seed(struct Curl_easy *data)
+static int Curl_nss_seed(struct Curl_easy *data)
{
/* make sure that NSS is initialized */
return !!Curl_nss_force_init(data);
}
/* data might be NULL */
-CURLcode Curl_nss_random(struct Curl_easy *data,
- unsigned char *entropy,
- size_t length)
+static CURLcode Curl_nss_random(struct Curl_easy *data,
+ unsigned char *entropy,
+ size_t length)
{
Curl_nss_seed(data); /* Initiate the seed if not already done */
@@ -2264,10 +2289,10 @@ CURLcode Curl_nss_random(struct Curl_easy *data,
return CURLE_OK;
}
-void Curl_nss_md5sum(unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *md5sum, /* output */
- size_t md5len)
+static CURLcode Curl_nss_md5sum(unsigned char *tmp, /* input */
+ size_t tmplen,
+ unsigned char *md5sum, /* output */
+ size_t md5len)
{
PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5);
unsigned int MD5out;
@@ -2275,12 +2300,14 @@ void Curl_nss_md5sum(unsigned char *tmp, /* input */
PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen));
PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len));
PK11_DestroyContext(MD5pw, PR_TRUE);
+
+ return CURLE_OK;
}
-void Curl_nss_sha256sum(const unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *sha256sum, /* output */
- size_t sha256len)
+static void Curl_nss_sha256sum(const unsigned char *tmp, /* input */
+ size_t tmplen,
+ unsigned char *sha256sum, /* output */
+ size_t sha256len)
{
PK11Context *SHA256pw = PK11_CreateDigestContext(SEC_OID_SHA256);
unsigned int SHA256out;
@@ -2290,7 +2317,7 @@ void Curl_nss_sha256sum(const unsigned char *tmp, /* input */
PK11_DestroyContext(SHA256pw, PR_TRUE);
}
-bool Curl_nss_cert_status_request(void)
+static bool Curl_nss_cert_status_request(void)
{
#ifdef SSL_ENABLE_OCSP_STAPLING
return TRUE;
@@ -2299,7 +2326,7 @@ bool Curl_nss_cert_status_request(void)
#endif
}
-bool Curl_nss_false_start(void)
+static bool Curl_nss_false_start(void)
{
#if NSSVERNUM >= 0x030f04 /* 3.15.4 */
return TRUE;
@@ -2308,4 +2335,46 @@ bool Curl_nss_false_start(void)
#endif
}
+static void *Curl_nss_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info UNUSED_PARAM)
+{
+ (void)info;
+ return BACKEND->handle;
+}
+
+const struct Curl_ssl Curl_ssl_nss = {
+ { CURLSSLBACKEND_NSS, "nss" }, /* info */
+
+ 1, /* have_ca_path */
+ 1, /* have_certinfo */
+ 1, /* have_pinnedpubkey */
+ 0, /* have_ssl_ctx */
+ 1, /* support_https_proxy */
+
+ sizeof(struct ssl_backend_data),
+
+ Curl_nss_init, /* init */
+ Curl_nss_cleanup, /* cleanup */
+ Curl_nss_version, /* version */
+ Curl_nss_check_cxn, /* check_cxn */
+ /* NSS has no shutdown function provided and thus always fail */
+ Curl_none_shutdown, /* shutdown */
+ Curl_none_data_pending, /* data_pending */
+ Curl_nss_random, /* random */
+ Curl_nss_cert_status_request, /* cert_status_request */
+ Curl_nss_connect, /* connect */
+ Curl_nss_connect_nonblocking, /* connect_nonblocking */
+ Curl_nss_get_internals, /* get_internals */
+ Curl_nss_close, /* close */
+ Curl_none_close_all, /* close_all */
+ /* NSS has its own session ID cache */
+ Curl_none_session_free, /* session_free */
+ Curl_none_set_engine, /* set_engine */
+ Curl_none_set_engine_default, /* set_engine_default */
+ Curl_none_engines_list, /* engines_list */
+ Curl_nss_false_start, /* false_start */
+ Curl_nss_md5sum, /* md5sum */
+ Curl_nss_sha256sum /* sha256sum */
+};
+
#endif /* USE_NSS */
diff --git a/Utilities/cmcurl/lib/vtls/nssg.h b/Utilities/cmcurl/lib/vtls/nssg.h
index 8c46929ff..41e51b021 100644
--- a/Utilities/cmcurl/lib/vtls/nssg.h
+++ b/Utilities/cmcurl/lib/vtls/nssg.h
@@ -30,79 +30,10 @@
#include "urldata.h"
-CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex);
-CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done);
-/* close a SSL connection */
-void Curl_nss_close(struct connectdata *conn, int sockindex);
-
-int Curl_nss_init(void);
-void Curl_nss_cleanup(void);
-
-size_t Curl_nss_version(char *buffer, size_t size);
-int Curl_nss_check_cxn(struct connectdata *cxn);
-int Curl_nss_seed(struct Curl_easy *data);
-
/* initialize NSS library if not already */
CURLcode Curl_nss_force_init(struct Curl_easy *data);
-CURLcode Curl_nss_random(struct Curl_easy *data,
- unsigned char *entropy,
- size_t length);
-
-void Curl_nss_md5sum(unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *md5sum, /* output */
- size_t md5len);
-
-void Curl_nss_sha256sum(const unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *sha256sum, /* output */
- size_t sha256len);
-
-bool Curl_nss_cert_status_request(void);
-
-bool Curl_nss_false_start(void);
-
-/* Support HTTPS-proxy */
-#define HTTPS_PROXY_SUPPORT 1
-
-/* Set the API backend definition to NSS */
-#define CURL_SSL_BACKEND CURLSSLBACKEND_NSS
-
-/* this backend supports the CAPATH option */
-#define have_curlssl_ca_path 1
-
-/* this backend supports CURLOPT_CERTINFO */
-#define have_curlssl_certinfo 1
-
-/* this backends supports CURLOPT_PINNEDPUBLICKEY */
-#define have_curlssl_pinnedpubkey 1
-
-/* API setup for NSS */
-#define curlssl_init Curl_nss_init
-#define curlssl_cleanup Curl_nss_cleanup
-#define curlssl_connect Curl_nss_connect
-#define curlssl_connect_nonblocking Curl_nss_connect_nonblocking
-
-/* NSS has its own session ID cache */
-#define curlssl_session_free(x) Curl_nop_stmt
-#define curlssl_close_all(x) ((void)x)
-#define curlssl_close Curl_nss_close
-/* NSS has no shutdown function provided and thus always fail */
-#define curlssl_shutdown(x,y) ((void)x, (void)y, 1)
-#define curlssl_set_engine(x,y) ((void)x, (void)y, CURLE_NOT_BUILT_IN)
-#define curlssl_set_engine_default(x) ((void)x, CURLE_NOT_BUILT_IN)
-#define curlssl_engines_list(x) ((void)x, (struct curl_slist *)NULL)
-#define curlssl_version Curl_nss_version
-#define curlssl_check_cxn(x) Curl_nss_check_cxn(x)
-#define curlssl_data_pending(x,y) ((void)x, (void)y, 0)
-#define curlssl_random(x,y,z) Curl_nss_random(x,y,z)
-#define curlssl_md5sum(a,b,c,d) Curl_nss_md5sum(a,b,c,d)
-#define curlssl_sha256sum(a,b,c,d) Curl_nss_sha256sum(a,b,c,d)
-#define curlssl_cert_status_request() Curl_nss_cert_status_request()
-#define curlssl_false_start() Curl_nss_false_start()
+extern const struct Curl_ssl Curl_ssl_nss;
#endif /* USE_NSS */
#endif /* HEADER_CURL_NSSG_H */
diff --git a/Utilities/cmcurl/lib/vtls/openssl.c b/Utilities/cmcurl/lib/vtls/openssl.c
index dbee36929..4253160aa 100644
--- a/Utilities/cmcurl/lib/vtls/openssl.c
+++ b/Utilities/cmcurl/lib/vtls/openssl.c
@@ -51,8 +51,10 @@
#include "strcase.h"
#include "hostcheck.h"
#include "curl_printf.h"
-
#include <openssl/ssl.h>
+#ifdef HAVE_OPENSSL_ENGINE_H
+#include <openssl/engine.h>
+#endif
#include <openssl/rand.h>
#include <openssl/x509v3.h>
#ifndef OPENSSL_NO_DSA
@@ -64,6 +66,8 @@
#include <openssl/conf.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
+#include <openssl/bio.h>
+#include <openssl/buffer.h>
#ifdef HAVE_OPENSSL_PKCS12_H
#include <openssl/pkcs12.h>
@@ -111,7 +115,6 @@
#define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
#define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
#define CONST_EXTS const
-#define CONST_ASN1_BIT_STRING const
#define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
#else
/* For OpenSSL before 1.1.0 */
@@ -119,7 +122,6 @@
#define X509_get0_notBefore(x) X509_get_notBefore(x)
#define X509_get0_notAfter(x) X509_get_notAfter(x)
#define CONST_EXTS /* nope */
-#define CONST_ASN1_BIT_STRING /* nope */
#ifdef LIBRESSL_VERSION_NUMBER
static unsigned long OpenSSL_version_num(void)
{
@@ -146,6 +148,20 @@ static unsigned long OpenSSL_version_num(void)
#define OPENSSL_load_builtin_modules(x)
#endif
+/*
+ * Whether SSL_CTX_set_keylog_callback is available.
+ * OpenSSL: supported since 1.1.1 https://github.com/openssl/openssl/pull/2287
+ * BoringSSL: supported since d28f59c27bac (committed 2015-11-19), the
+ * BORINGSSL_201512 macro from 2016-01-21 should be close enough.
+ * LibreSSL: unsupported in at least 2.5.1 (explicitly check for it since it
+ * lies and pretends to be OpenSSL 2.0.0).
+ */
+#if (OPENSSL_VERSION_NUMBER >= 0x10101000L && \
+ !defined(LIBRESSL_VERSION_NUMBER)) || \
+ defined(BORINGSSL_201512)
+#define HAVE_KEYLOG_CALLBACK
+#endif
+
#if defined(LIBRESSL_VERSION_NUMBER)
#define OSSL_PACKAGE "LibreSSL"
#elif defined(OPENSSL_IS_BORINGSSL)
@@ -154,6 +170,38 @@ static unsigned long OpenSSL_version_num(void)
#define OSSL_PACKAGE "OpenSSL"
#endif
+#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
+/* up2date versions of OpenSSL maintain the default reasonably secure without
+ * breaking compatibility, so it is better not to override the default by curl
+ */
+#define DEFAULT_CIPHER_SELECTION NULL
+#else
+/* ... but it is not the case with old versions of OpenSSL */
+#define DEFAULT_CIPHER_SELECTION \
+ "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH"
+#endif
+
+#ifdef ENABLE_SSLKEYLOGFILE
+typedef struct ssl_tap_state {
+ int master_key_length;
+ unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
+ unsigned char client_random[SSL3_RANDOM_SIZE];
+} ssl_tap_state_t;
+#endif /* ENABLE_SSLKEYLOGFILE */
+
+struct ssl_backend_data {
+ /* these ones requires specific SSL-types */
+ SSL_CTX* ctx;
+ SSL* handle;
+ X509* server_cert;
+#ifdef ENABLE_SSLKEYLOGFILE
+ /* tap_state holds the last seen master key if we're logging them */
+ ssl_tap_state_t tap_state;
+#endif
+};
+
+#define BACKEND connssl->backend
+
/*
* Number of bytes to read from the random number seed file. This must be
* a finite value (because some entropy "files" like /dev/urandom have
@@ -162,6 +210,112 @@ static unsigned long OpenSSL_version_num(void)
*/
#define RAND_LOAD_LENGTH 1024
+#ifdef ENABLE_SSLKEYLOGFILE
+/* The fp for the open SSLKEYLOGFILE, or NULL if not open */
+static FILE *keylog_file_fp;
+
+#ifdef HAVE_KEYLOG_CALLBACK
+static void ossl_keylog_callback(const SSL *ssl, const char *line)
+{
+ (void)ssl;
+
+ /* Using fputs here instead of fprintf since libcurl's fprintf replacement
+ may not be thread-safe. */
+ if(keylog_file_fp && line && *line) {
+ char stackbuf[256];
+ char *buf;
+ size_t linelen = strlen(line);
+
+ if(linelen <= sizeof(stackbuf) - 2)
+ buf = stackbuf;
+ else {
+ buf = malloc(linelen + 2);
+ if(!buf)
+ return;
+ }
+ strncpy(buf, line, linelen);
+ buf[linelen] = '\n';
+ buf[linelen + 1] = '\0';
+
+ fputs(buf, keylog_file_fp);
+ if(buf != stackbuf)
+ free(buf);
+ }
+}
+#else
+#define KEYLOG_PREFIX "CLIENT_RANDOM "
+#define KEYLOG_PREFIX_LEN (sizeof(KEYLOG_PREFIX) - 1)
+/*
+ * tap_ssl_key is called by libcurl to make the CLIENT_RANDOMs if the OpenSSL
+ * being used doesn't have native support for doing that.
+ */
+static void tap_ssl_key(const SSL *ssl, ssl_tap_state_t *state)
+{
+ const char *hex = "0123456789ABCDEF";
+ int pos, i;
+ char line[KEYLOG_PREFIX_LEN + 2 * SSL3_RANDOM_SIZE + 1 +
+ 2 * SSL_MAX_MASTER_KEY_LENGTH + 1 + 1];
+ const SSL_SESSION *session = SSL_get_session(ssl);
+ unsigned char client_random[SSL3_RANDOM_SIZE];
+ unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
+ int master_key_length = 0;
+
+ if(!session || !keylog_file_fp)
+ return;
+
+#if OPENSSL_VERSION_NUMBER >= 0x10100000L
+ /* ssl->s3 is not checked in openssl 1.1.0-pre6, but let's assume that
+ * we have a valid SSL context if we have a non-NULL session. */
+ SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE);
+ master_key_length =
+ SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH);
+#else
+ if(ssl->s3 && session->master_key_length > 0) {
+ master_key_length = session->master_key_length;
+ memcpy(master_key, session->master_key, session->master_key_length);
+ memcpy(client_random, ssl->s3->client_random, SSL3_RANDOM_SIZE);
+ }
+#endif
+
+ if(master_key_length <= 0)
+ return;
+
+ /* Skip writing keys if there is no key or it did not change. */
+ if(state->master_key_length == master_key_length &&
+ !memcmp(state->master_key, master_key, master_key_length) &&
+ !memcmp(state->client_random, client_random, SSL3_RANDOM_SIZE)) {
+ return;
+ }
+
+ state->master_key_length = master_key_length;
+ memcpy(state->master_key, master_key, master_key_length);
+ memcpy(state->client_random, client_random, SSL3_RANDOM_SIZE);
+
+ memcpy(line, KEYLOG_PREFIX, KEYLOG_PREFIX_LEN);
+ pos = KEYLOG_PREFIX_LEN;
+
+ /* Client Random for SSLv3/TLS */
+ for(i = 0; i < SSL3_RANDOM_SIZE; i++) {
+ line[pos++] = hex[client_random[i] >> 4];
+ line[pos++] = hex[client_random[i] & 0xF];
+ }
+ line[pos++] = ' ';
+
+ /* Master Secret (size is at most SSL_MAX_MASTER_KEY_LENGTH) */
+ for(i = 0; i < master_key_length; i++) {
+ line[pos++] = hex[master_key[i] >> 4];
+ line[pos++] = hex[master_key[i] & 0xF];
+ }
+ line[pos++] = '\n';
+ line[pos] = '\0';
+
+ /* Using fputs here instead of fprintf since libcurl's fprintf replacement
+ may not be thread-safe. */
+ fputs(line, keylog_file_fp);
+}
+#endif /* !HAVE_KEYLOG_CALLBACK */
+#endif /* ENABLE_SSLKEYLOGFILE */
+
static const char *SSL_ERROR_to_str(int err)
{
switch(err) {
@@ -216,7 +370,7 @@ static int passwd_callback(char *buf, int num, int encrypting,
if(!encrypting) {
int klen = curlx_uztosi(strlen((char *)global_passwd));
if(num > klen) {
- memcpy(buf, global_passwd, klen+1);
+ memcpy(buf, global_passwd, klen + 1);
return klen;
}
}
@@ -236,7 +390,6 @@ static CURLcode Curl_ossl_seed(struct Curl_easy *data)
/* we have the "SSL is seeded" boolean static to prevent multiple
time-consuming seedings in vain */
static bool ssl_seeded = FALSE;
- int nread=0;
char fname[256];
if(ssl_seeded)
@@ -256,12 +409,12 @@ static CURLcode Curl_ossl_seed(struct Curl_easy *data)
#endif
{
/* let the option override the define */
- nread += RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
- data->set.str[STRING_SSL_RANDOM_FILE]:
- RANDOM_FILE),
- RAND_LOAD_LENGTH);
+ RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
+ data->set.str[STRING_SSL_RANDOM_FILE]:
+ RANDOM_FILE),
+ RAND_LOAD_LENGTH);
if(rand_enough())
- return nread;
+ return CURLE_OK;
}
#if defined(HAVE_RAND_EGD)
@@ -279,35 +432,47 @@ static CURLcode Curl_ossl_seed(struct Curl_easy *data)
int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
if(-1 != ret) {
- nread += ret;
if(rand_enough())
- return nread;
+ return CURLE_OK;
}
}
#endif
- /* If we get here, it means we need to seed the PRNG using a "silly"
- approach! */
+ /* fallback to a custom seeding of the PRNG using a hash based on a current
+ time */
do {
unsigned char randb[64];
- int len = sizeof(randb);
- if(!RAND_bytes(randb, len))
- break;
- RAND_add(randb, len, (len >> 1));
+ size_t len = sizeof(randb);
+ size_t i, i_max;
+ for(i = 0, i_max = len / sizeof(struct curltime); i < i_max; ++i) {
+ struct curltime tv = curlx_tvnow();
+ Curl_wait_ms(1);
+ tv.tv_sec *= i + 1;
+ tv.tv_usec *= (unsigned int)i + 2;
+ tv.tv_sec ^= ((curlx_tvnow().tv_sec + curlx_tvnow().tv_usec) *
+ (i + 3)) << 8;
+ tv.tv_usec ^= (unsigned int) ((curlx_tvnow().tv_sec +
+ curlx_tvnow().tv_usec) *
+ (i + 4)) << 16;
+ memcpy(&randb[i * sizeof(struct curltime)], &tv,
+ sizeof(struct curltime));
+ }
+ RAND_add(randb, (int)len, (double)len/2);
} while(!rand_enough());
/* generates a default path for the random seed file */
- fname[0]=0; /* blank it first */
+ fname[0] = 0; /* blank it first */
RAND_file_name(fname, sizeof(fname));
if(fname[0]) {
/* we got a file name to try */
- nread += RAND_load_file(fname, RAND_LOAD_LENGTH);
+ RAND_load_file(fname, RAND_LOAD_LENGTH);
if(rand_enough())
- return nread;
+ return CURLE_OK;
}
infof(data, "libcurl is now using a weak random seed!\n");
- return CURLE_SSL_CONNECT_ERROR; /* confusing error code */
+ return (rand_enough() ? CURLE_OK :
+ CURLE_SSL_CONNECT_ERROR /* confusing error code */);
}
#ifndef SSL_FILETYPE_ENGINE
@@ -384,6 +549,7 @@ int cert_stuff(struct connectdata *conn,
{
struct Curl_easy *data = conn->data;
char error_buffer[256];
+ bool check_privkey = TRUE;
int file_type = do_file_type(cert_type);
@@ -592,7 +758,7 @@ int cert_stuff(struct connectdata *conn,
break;
if(!key_file)
/* cert & key can only be in PEM case in the same file */
- key_file=cert_file;
+ key_file = cert_file;
/* FALLTHROUGH */
case SSL_FILETYPE_ASN1:
if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
@@ -655,13 +821,13 @@ int cert_stuff(struct connectdata *conn,
return 0;
}
- ssl=SSL_new(ctx);
+ ssl = SSL_new(ctx);
if(!ssl) {
failf(data, "unable to create an SSL structure");
return 0;
}
- x509=SSL_get_certificate(ssl);
+ x509 = SSL_get_certificate(ssl);
/* This version was provided by Evan Jordan and is supposed to not
leak memory as the previous version: */
@@ -671,17 +837,32 @@ int cert_stuff(struct connectdata *conn,
EVP_PKEY_free(pktmp);
}
+#ifndef OPENSSL_NO_RSA
+ {
+ /* If RSA is used, don't check the private key if its flags indicate
+ * it doesn't support it. */
+ EVP_PKEY *priv_key = SSL_get_privatekey(ssl);
+ if(EVP_PKEY_id(priv_key) == EVP_PKEY_RSA) {
+ RSA *rsa = EVP_PKEY_get1_RSA(priv_key);
+ if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK)
+ check_privkey = FALSE;
+ RSA_free(rsa); /* Decrement reference count */
+ }
+ }
+#endif
+
SSL_free(ssl);
/* If we are using DSA, we can copy the parameters from
* the private key */
-
- /* Now we know that a key and cert have been set against
- * the SSL context */
- if(!SSL_CTX_check_private_key(ctx)) {
- failf(data, "Private key does not match the certificate public key");
- return 0;
+ if(check_privkey == TRUE) {
+ /* Now we know that a key and cert have been set against
+ * the SSL context */
+ if(!SSL_CTX_check_private_key(ctx)) {
+ failf(data, "Private key does not match the certificate public key");
+ return 0;
+ }
}
}
return 1;
@@ -709,7 +890,7 @@ static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
size--; /* don't overwrite the buffer end */
memcpy(buf, biomem->data, size);
- buf[size]=0;
+ buf[size] = 0;
BIO_free(bio_out);
@@ -723,8 +904,12 @@ static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
* @retval 0 error initializing SSL
* @retval 1 SSL initialized successfully
*/
-int Curl_ossl_init(void)
+static int Curl_ossl_init(void)
{
+#ifdef ENABLE_SSLKEYLOGFILE
+ const char *keylog_file_name;
+#endif
+
OPENSSL_load_builtin_modules();
#ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
@@ -761,11 +946,24 @@ int Curl_ossl_init(void)
OpenSSL_add_all_algorithms();
#endif
+#ifdef ENABLE_SSLKEYLOGFILE
+ keylog_file_name = curl_getenv("SSLKEYLOGFILE");
+ if(keylog_file_name && !keylog_file_fp) {
+ keylog_file_fp = fopen(keylog_file_name, FOPEN_APPENDTEXT);
+ if(keylog_file_fp) {
+ if(setvbuf(keylog_file_fp, NULL, _IOLBF, 4096)) {
+ fclose(keylog_file_fp);
+ keylog_file_fp = NULL;
+ }
+ }
+ }
+#endif
+
return 1;
}
/* Global cleanup */
-void Curl_ossl_cleanup(void)
+static void Curl_ossl_cleanup(void)
{
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
!defined(LIBRESSL_VERSION_NUMBER)
@@ -797,6 +995,13 @@ void Curl_ossl_cleanup(void)
SSL_COMP_free_compression_methods();
#endif
#endif
+
+#ifdef ENABLE_SSLKEYLOGFILE
+ if(keylog_file_fp) {
+ fclose(keylog_file_fp);
+ keylog_file_fp = NULL;
+ }
+#endif
}
/*
@@ -807,7 +1012,7 @@ void Curl_ossl_cleanup(void)
* 0 means the connection has been closed
* -1 means the connection status is unknown
*/
-int Curl_ossl_check_cxn(struct connectdata *conn)
+static int Curl_ossl_check_cxn(struct connectdata *conn)
{
/* SSL_peek takes data out of the raw recv buffer without peeking so we use
recv MSG_PEEK instead. Bug #795 */
@@ -853,7 +1058,8 @@ int Curl_ossl_check_cxn(struct connectdata *conn)
/* Selects an OpenSSL crypto engine
*/
-CURLcode Curl_ossl_set_engine(struct Curl_easy *data, const char *engine)
+static CURLcode Curl_ossl_set_engine(struct Curl_easy *data,
+ const char *engine)
{
#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
ENGINE *e;
@@ -898,7 +1104,7 @@ CURLcode Curl_ossl_set_engine(struct Curl_easy *data, const char *engine)
/* Sets engine as default for all SSL operations
*/
-CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data)
+static CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data)
{
#ifdef HAVE_OPENSSL_ENGINE_H
if(data->state.engine) {
@@ -920,7 +1126,7 @@ CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data)
/* Return list of OpenSSL crypto engine names.
*/
-struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data)
+static struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data)
{
struct curl_slist *list = NULL;
#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
@@ -943,23 +1149,23 @@ struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data)
static void ossl_close(struct ssl_connect_data *connssl)
{
- if(connssl->handle) {
- (void)SSL_shutdown(connssl->handle);
- SSL_set_connect_state(connssl->handle);
+ if(BACKEND->handle) {
+ (void)SSL_shutdown(BACKEND->handle);
+ SSL_set_connect_state(BACKEND->handle);
- SSL_free(connssl->handle);
- connssl->handle = NULL;
+ SSL_free(BACKEND->handle);
+ BACKEND->handle = NULL;
}
- if(connssl->ctx) {
- SSL_CTX_free(connssl->ctx);
- connssl->ctx = NULL;
+ if(BACKEND->ctx) {
+ SSL_CTX_free(BACKEND->ctx);
+ BACKEND->ctx = NULL;
}
}
/*
* This function is called when an SSL connection is closed.
*/
-void Curl_ossl_close(struct connectdata *conn, int sockindex)
+static void Curl_ossl_close(struct connectdata *conn, int sockindex)
{
ossl_close(&conn->ssl[sockindex]);
ossl_close(&conn->proxy_ssl[sockindex]);
@@ -969,7 +1175,7 @@ void Curl_ossl_close(struct connectdata *conn, int sockindex)
* This function is called to shut down the SSL layer but keep the
* socket open (CCC - Clear Command Channel)
*/
-int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
+static int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
{
int retval = 0;
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
@@ -988,9 +1194,9 @@ int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
we do not send one. Let's hope other servers do the same... */
if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
- (void)SSL_shutdown(connssl->handle);
+ (void)SSL_shutdown(BACKEND->handle);
- if(connssl->handle) {
+ if(BACKEND->handle) {
buffsize = (int)sizeof(buf);
while(!done) {
int what = SOCKET_READABLE(conn->sock[sockindex],
@@ -1000,9 +1206,8 @@ int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
/* Something to read, let's do it and hope that it is the close
notify alert from the server */
- nread = (ssize_t)SSL_read(conn->ssl[sockindex].handle, buf,
- buffsize);
- err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread);
+ nread = (ssize_t)SSL_read(BACKEND->handle, buf, buffsize);
+ err = SSL_get_error(BACKEND->handle, (int)nread);
switch(err) {
case SSL_ERROR_NONE: /* this is not an error */
@@ -1047,7 +1252,7 @@ int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
if(data->set.verbose) {
#ifdef HAVE_SSL_GET_SHUTDOWN
- switch(SSL_get_shutdown(connssl->handle)) {
+ switch(SSL_get_shutdown(BACKEND->handle)) {
case SSL_SENT_SHUTDOWN:
infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
break;
@@ -1062,13 +1267,13 @@ int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
#endif
}
- SSL_free(connssl->handle);
- connssl->handle = NULL;
+ SSL_free(BACKEND->handle);
+ BACKEND->handle = NULL;
}
return retval;
}
-void Curl_ossl_session_free(void *ptr)
+static void Curl_ossl_session_free(void *ptr)
{
/* free the ID */
SSL_SESSION_free(ptr);
@@ -1078,7 +1283,7 @@ void Curl_ossl_session_free(void *ptr)
* This function is called when the 'data' struct is going away. Close
* down everything and free all resources!
*/
-void Curl_ossl_close_all(struct Curl_easy *data)
+static void Curl_ossl_close_all(struct Curl_easy *data)
{
#ifdef HAVE_OPENSSL_ENGINE_H
if(data->state.engine) {
@@ -1170,7 +1375,7 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
numalts = sk_GENERAL_NAME_num(altnames);
/* loop through all alternatives - until a dnsmatch */
- for(i=0; (i < numalts) && !dnsmatched; i++) {
+ for(i = 0; (i < numalts) && !dnsmatched; i++) {
/* get a handle to alternative name number i */
const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
@@ -1239,7 +1444,7 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
else {
/* we have to look to the last occurrence of a commonName in the
distinguished one to get the most significant one. */
- int j, i=-1;
+ int j, i = -1;
/* The following is done because of a bug in 0.9.6b */
@@ -1248,14 +1453,14 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
X509_NAME *name = X509_get_subject_name(server_cert);
if(name)
- while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i))>=0)
- i=j;
+ while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0)
+ i = j;
/* we have the name entry and we will now convert this to a string
that we can use for comparison. Doing this we support BMPstring,
UTF8 etc. */
- if(i>=0) {
+ if(i >= 0) {
ASN1_STRING *tmp =
X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
@@ -1268,7 +1473,7 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
j = ASN1_STRING_length(tmp);
if(j >= 0) {
- peer_CN = OPENSSL_malloc(j+1);
+ peer_CN = OPENSSL_malloc(j + 1);
if(peer_CN) {
memcpy(peer_CN, ASN1_STRING_get0_data(tmp), j);
peer_CN[j] = '\0';
@@ -1291,7 +1496,8 @@ static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
peer_CN = NULL;
else {
/* convert peer_CN from UTF8 */
- CURLcode rc = Curl_convert_from_utf8(data, peer_CN, strlen(peer_CN));
+ CURLcode rc = Curl_convert_from_utf8(data, (char *)peer_CN,
+ strlen((char *)peer_CN));
/* Curl_convert_from_utf8 calls failf if unsuccessful */
if(rc) {
OPENSSL_free(peer_CN);
@@ -1337,7 +1543,7 @@ static CURLcode verifystatus(struct connectdata *conn,
X509_STORE *st = NULL;
STACK_OF(X509) *ch = NULL;
- long len = SSL_get_tlsext_status_ocsp_resp(connssl->handle, &p);
+ long len = SSL_get_tlsext_status_ocsp_resp(BACKEND->handle, &p);
if(!p) {
failf(data, "No OCSP response received");
@@ -1367,8 +1573,8 @@ static CURLcode verifystatus(struct connectdata *conn,
goto end;
}
- ch = SSL_get_peer_cert_chain(connssl->handle);
- st = SSL_CTX_get_cert_store(connssl->ctx);
+ ch = SSL_get_peer_cert_chain(BACKEND->handle);
+ st = SSL_CTX_get_cert_store(BACKEND->ctx);
#if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \
(defined(LIBRESSL_VERSION_NUMBER) && \
@@ -1759,7 +1965,7 @@ set_ssl_version_min_max(long *ctx_options, struct connectdata *conn,
#ifdef TLS1_3_VERSION
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
- SSL_CTX_set_max_proto_version(connssl->ctx, TLS1_3_VERSION);
+ SSL_CTX_set_max_proto_version(BACKEND->ctx, TLS1_3_VERSION);
*ctx_options |= SSL_OP_NO_TLSv1_2;
}
#else
@@ -1767,6 +1973,7 @@ set_ssl_version_min_max(long *ctx_options, struct connectdata *conn,
failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
return CURLE_NOT_BUILT_IN;
#endif
+ /* FALLTHROUGH */
case CURL_SSLVERSION_TLSv1_2:
#if OPENSSL_VERSION_NUMBER >= 0x1000100FL
*ctx_options |= SSL_OP_NO_TLSv1_1;
@@ -1909,25 +2116,25 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
return CURLE_SSL_CONNECT_ERROR;
}
- if(connssl->ctx)
- SSL_CTX_free(connssl->ctx);
- connssl->ctx = SSL_CTX_new(req_method);
+ if(BACKEND->ctx)
+ SSL_CTX_free(BACKEND->ctx);
+ BACKEND->ctx = SSL_CTX_new(req_method);
- if(!connssl->ctx) {
+ if(!BACKEND->ctx) {
failf(data, "SSL: couldn't create a context: %s",
ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
return CURLE_OUT_OF_MEMORY;
}
#ifdef SSL_MODE_RELEASE_BUFFERS
- SSL_CTX_set_mode(connssl->ctx, SSL_MODE_RELEASE_BUFFERS);
+ SSL_CTX_set_mode(BACKEND->ctx, SSL_MODE_RELEASE_BUFFERS);
#endif
#ifdef SSL_CTRL_SET_MSG_CALLBACK
if(data->set.fdebug && data->set.verbose) {
/* the SSL trace callback is only used for verbose logging */
- SSL_CTX_set_msg_callback(connssl->ctx, ssl_tls_trace);
- SSL_CTX_set_msg_callback_arg(connssl->ctx, conn);
+ SSL_CTX_set_msg_callback(BACKEND->ctx, ssl_tls_trace);
+ SSL_CTX_set_msg_callback_arg(BACKEND->ctx, conn);
}
#endif
@@ -2044,11 +2251,11 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
return CURLE_SSL_CONNECT_ERROR;
}
- SSL_CTX_set_options(connssl->ctx, ctx_options);
+ SSL_CTX_set_options(BACKEND->ctx, ctx_options);
#ifdef HAS_NPN
if(conn->bits.tls_enable_npn)
- SSL_CTX_set_next_proto_select_cb(connssl->ctx, select_next_proto_cb, conn);
+ SSL_CTX_set_next_proto_select_cb(BACKEND->ctx, select_next_proto_cb, conn);
#endif
#ifdef HAS_ALPN
@@ -2057,7 +2264,8 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
unsigned char protocols[128];
#ifdef USE_NGHTTP2
- if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
+ if(data->set.httpversion >= CURL_HTTP_VERSION_2 &&
+ (!SSL_IS_PROXY() || !conn->bits.tunnel_proxy)) {
protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
@@ -2075,12 +2283,12 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
/* expects length prefixed preference ordered list of protocols in wire
* format
*/
- SSL_CTX_set_alpn_protos(connssl->ctx, protocols, cur);
+ SSL_CTX_set_alpn_protos(BACKEND->ctx, protocols, cur);
}
#endif
if(ssl_cert || ssl_cert_type) {
- if(!cert_stuff(conn, connssl->ctx, ssl_cert, ssl_cert_type,
+ if(!cert_stuff(conn, BACKEND->ctx, ssl_cert, ssl_cert_type,
SSL_SET_OPTION(key), SSL_SET_OPTION(key_type),
SSL_SET_OPTION(key_passwd))) {
/* failf() is already done in cert_stuff() */
@@ -2091,11 +2299,13 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
ciphers = SSL_CONN_CONFIG(cipher_list);
if(!ciphers)
ciphers = (char *)DEFAULT_CIPHER_SELECTION;
- if(!SSL_CTX_set_cipher_list(connssl->ctx, ciphers)) {
- failf(data, "failed setting cipher list: %s", ciphers);
- return CURLE_SSL_CIPHER;
+ if(ciphers) {
+ if(!SSL_CTX_set_cipher_list(BACKEND->ctx, ciphers)) {
+ failf(data, "failed setting cipher list: %s", ciphers);
+ return CURLE_SSL_CIPHER;
+ }
+ infof(data, "Cipher selection: %s\n", ciphers);
}
- infof(data, "Cipher selection: %s\n", ciphers);
#ifdef USE_TLS_SRP
if(ssl_authtype == CURL_TLSAUTH_SRP) {
@@ -2103,18 +2313,18 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
infof(data, "Using TLS-SRP username: %s\n", ssl_username);
- if(!SSL_CTX_set_srp_username(connssl->ctx, ssl_username)) {
+ if(!SSL_CTX_set_srp_username(BACKEND->ctx, ssl_username)) {
failf(data, "Unable to set SRP user name");
return CURLE_BAD_FUNCTION_ARGUMENT;
}
- if(!SSL_CTX_set_srp_password(connssl->ctx, SSL_SET_OPTION(password))) {
+ if(!SSL_CTX_set_srp_password(BACKEND->ctx, SSL_SET_OPTION(password))) {
failf(data, "failed setting SRP password");
return CURLE_BAD_FUNCTION_ARGUMENT;
}
if(!SSL_CONN_CONFIG(cipher_list)) {
infof(data, "Setting cipher list SRP\n");
- if(!SSL_CTX_set_cipher_list(connssl->ctx, "SRP")) {
+ if(!SSL_CTX_set_cipher_list(BACKEND->ctx, "SRP")) {
failf(data, "failed setting SRP cipher list");
return CURLE_SSL_CIPHER;
}
@@ -2125,7 +2335,7 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
if(ssl_cafile || ssl_capath) {
/* tell SSL where to find CA certificates that are used to verify
the servers certificate. */
- if(!SSL_CTX_load_verify_locations(connssl->ctx, ssl_cafile, ssl_capath)) {
+ if(!SSL_CTX_load_verify_locations(BACKEND->ctx, ssl_cafile, ssl_capath)) {
if(verifypeer) {
/* Fail if we insist on successfully verifying the server. */
failf(data, "error setting certificate verify locations:\n"
@@ -2153,14 +2363,14 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
else if(verifypeer) {
/* verfying the peer without any CA certificates won't
work so use openssl's built in default as fallback */
- SSL_CTX_set_default_verify_paths(connssl->ctx);
+ SSL_CTX_set_default_verify_paths(BACKEND->ctx);
}
#endif
if(ssl_crlfile) {
/* tell SSL where to find CRL file that is used to check certificate
* revocation */
- lookup=X509_STORE_add_lookup(SSL_CTX_get_cert_store(connssl->ctx),
+ lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(BACKEND->ctx),
X509_LOOKUP_file());
if(!lookup ||
(!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
@@ -2169,7 +2379,7 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
}
/* Everything is fine. */
infof(data, "successfully load CRL file:\n");
- X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
+ X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx),
X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
infof(data, " CRLfile: %s\n", ssl_crlfile);
@@ -2184,7 +2394,7 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
*/
#if defined(X509_V_FLAG_TRUSTED_FIRST) && !defined(X509_V_FLAG_NO_ALT_CHAINS)
if(verifypeer) {
- X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
+ X509_STORE_set_flags(SSL_CTX_get_cert_store(BACKEND->ctx),
X509_V_FLAG_TRUSTED_FIRST);
}
#endif
@@ -2193,12 +2403,19 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
* fail to connect if the verification fails, or if it should continue
* anyway. In the latter case the result of the verification is checked with
* SSL_get_verify_result() below. */
- SSL_CTX_set_verify(connssl->ctx,
+ SSL_CTX_set_verify(BACKEND->ctx,
verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
+ /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */
+#if defined(ENABLE_SSLKEYLOGFILE) && defined(HAVE_KEYLOG_CALLBACK)
+ if(keylog_file) {
+ SSL_CTX_set_keylog_callback(connssl->ctx, ossl_keylog_callback);
+ }
+#endif
+
/* give application a chance to interfere with SSL set up. */
if(data->set.ssl.fsslctx) {
- result = (*data->set.ssl.fsslctx)(data, connssl->ctx,
+ result = (*data->set.ssl.fsslctx)(data, BACKEND->ctx,
data->set.ssl.fsslctxp);
if(result) {
failf(data, "error signaled by ssl ctx callback");
@@ -2207,10 +2424,10 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
}
/* Lets make an SSL structure */
- if(connssl->handle)
- SSL_free(connssl->handle);
- connssl->handle = SSL_new(connssl->ctx);
- if(!connssl->handle) {
+ if(BACKEND->handle)
+ SSL_free(BACKEND->handle);
+ BACKEND->handle = SSL_new(BACKEND->ctx);
+ if(!BACKEND->handle) {
failf(data, "SSL: couldn't create a context (handle)!");
return CURLE_OUT_OF_MEMORY;
}
@@ -2218,19 +2435,19 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
!defined(OPENSSL_NO_OCSP)
if(SSL_CONN_CONFIG(verifystatus))
- SSL_set_tlsext_status_type(connssl->handle, TLSEXT_STATUSTYPE_ocsp);
+ SSL_set_tlsext_status_type(BACKEND->handle, TLSEXT_STATUSTYPE_ocsp);
#endif
- SSL_set_connect_state(connssl->handle);
+ SSL_set_connect_state(BACKEND->handle);
- connssl->server_cert = 0x0;
+ BACKEND->server_cert = 0x0;
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
#ifdef ENABLE_IPV6
(0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&
#endif
sni &&
- !SSL_set_tlsext_host_name(connssl->handle, hostname))
+ !SSL_set_tlsext_host_name(BACKEND->handle, hostname))
infof(data, "WARNING: failed to configure server name indication (SNI) "
"TLS extension\n");
#endif
@@ -2242,7 +2459,7 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
Curl_ssl_sessionid_lock(conn);
if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) {
/* we got a session id, use it! */
- if(!SSL_set_session(connssl->handle, ssl_sessionid)) {
+ if(!SSL_set_session(BACKEND->handle, ssl_sessionid)) {
Curl_ssl_sessionid_unlock(conn);
failf(data, "SSL: SSL_set_session failed: %s",
ossl_strerror(ERR_get_error(), error_buffer,
@@ -2257,13 +2474,14 @@ static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
if(conn->proxy_ssl[sockindex].use) {
BIO *const bio = BIO_new(BIO_f_ssl());
+ SSL *handle = conn->proxy_ssl[sockindex].backend->handle;
DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
- DEBUGASSERT(conn->proxy_ssl[sockindex].handle != NULL);
+ DEBUGASSERT(handle != NULL);
DEBUGASSERT(bio != NULL);
- BIO_set_ssl(bio, conn->proxy_ssl[sockindex].handle, FALSE);
- SSL_set_bio(connssl->handle, bio, bio);
+ BIO_set_ssl(bio, handle, FALSE);
+ SSL_set_bio(BACKEND->handle, bio, bio);
}
- else if(!SSL_set_fd(connssl->handle, (int)sockfd)) {
+ else if(!SSL_set_fd(BACKEND->handle, (int)sockfd)) {
/* pass the raw socket into the SSL layers */
failf(data, "SSL: SSL_set_fd failed: %s",
ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
@@ -2288,13 +2506,18 @@ static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
ERR_clear_error();
- err = SSL_connect(connssl->handle);
+ err = SSL_connect(BACKEND->handle);
+ /* If keylogging is enabled but the keylog callback is not supported then log
+ secrets here, immediately after SSL_connect by using tap_ssl_key. */
+#if defined(ENABLE_SSLKEYLOGFILE) && !defined(HAVE_KEYLOG_CALLBACK)
+ tap_ssl_key(BACKEND->handle, &BACKEND->tap_state);
+#endif
/* 1 is fine
0 is "not successful but was shut down controlled"
<0 is "handshake was not successful, because a fatal error occurred" */
if(1 != err) {
- int detail = SSL_get_error(connssl->handle, err);
+ int detail = SSL_get_error(BACKEND->handle, err);
if(SSL_ERROR_WANT_READ == detail) {
connssl->connecting_state = ssl_connect_2_reading;
@@ -2328,7 +2551,7 @@ static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
(reason == SSL_R_CERTIFICATE_VERIFY_FAILED)) {
result = CURLE_SSL_CACERT;
- lerr = SSL_get_verify_result(connssl->handle);
+ lerr = SSL_get_verify_result(BACKEND->handle);
if(lerr != X509_V_OK) {
*certverifyresult = lerr;
snprintf(error_buffer, sizeof(error_buffer),
@@ -2372,8 +2595,8 @@ static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
/* Informational message */
infof(data, "SSL connection using %s / %s\n",
- get_ssl_version_txt(connssl->handle),
- SSL_get_cipher(connssl->handle));
+ get_ssl_version_txt(BACKEND->handle),
+ SSL_get_cipher(BACKEND->handle));
#ifdef HAS_ALPN
/* Sets data and len to negotiated protocol, len is 0 if no protocol was
@@ -2382,7 +2605,7 @@ static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
if(conn->bits.tls_enable_alpn) {
const unsigned char *neg_protocol;
unsigned int len;
- SSL_get0_alpn_selected(connssl->handle, &neg_protocol, &len);
+ SSL_get0_alpn_selected(BACKEND->handle, &neg_protocol, &len);
if(len != 0) {
infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol);
@@ -2427,7 +2650,7 @@ static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
do { \
long info_len = BIO_get_mem_data(mem, &ptr); \
Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
- if(1!=BIO_reset(mem)) \
+ if(1 != BIO_reset(mem)) \
break; \
} WHILE_FALSE
@@ -2475,12 +2698,12 @@ static int X509V3_ext(struct Curl_easy *data,
/* no extensions, bail out */
return 1;
- for(i=0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
+ for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
ASN1_OBJECT *obj;
X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
BUF_MEM *biomem;
char buf[512];
- char *ptr=buf;
+ char *ptr = buf;
char namebuf[128];
BIO *bio_out = BIO_new(BIO_s_mem());
@@ -2497,16 +2720,16 @@ static int X509V3_ext(struct Curl_easy *data,
BIO_get_mem_ptr(bio_out, &biomem);
for(j = 0; j < (size_t)biomem->length; j++) {
- const char *sep="";
+ const char *sep = "";
if(biomem->data[j] == '\n') {
- sep=", ";
+ sep = ", ";
j++; /* skip the newline */
};
while((j<(size_t)biomem->length) && (biomem->data[j] == ' '))
j++;
if(j<(size_t)biomem->length)
- ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep,
- biomem->data[j]);
+ ptr += snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep,
+ biomem->data[j]);
}
Curl_ssl_push_certinfo(data, certnum, namebuf, buf);
@@ -2528,7 +2751,7 @@ static CURLcode get_cert_chain(struct connectdata *conn,
int numcerts;
BIO *mem;
- sk = SSL_get_peer_cert_chain(connssl->handle);
+ sk = SSL_get_peer_cert_chain(BACKEND->handle);
if(!sk) {
return CURLE_OUT_OF_MEMORY;
}
@@ -2545,10 +2768,10 @@ static CURLcode get_cert_chain(struct connectdata *conn,
for(i = 0; i < numcerts; i++) {
ASN1_INTEGER *num;
X509 *x = sk_X509_value(sk, i);
- EVP_PKEY *pubkey=NULL;
+ EVP_PKEY *pubkey = NULL;
int j;
char *ptr;
- CONST_ASN1_BIT_STRING ASN1_BIT_STRING *psig = NULL;
+ const ASN1_BIT_STRING *psig = NULL;
X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
push_certinfo("Subject", i);
@@ -2818,8 +3041,8 @@ static CURLcode servercert(struct connectdata *conn,
/* we've been asked to gather certificate info! */
(void)get_cert_chain(conn, connssl);
- connssl->server_cert = SSL_get_peer_certificate(connssl->handle);
- if(!connssl->server_cert) {
+ BACKEND->server_cert = SSL_get_peer_certificate(BACKEND->handle);
+ if(!BACKEND->server_cert) {
BIO_free(mem);
if(!strict)
return CURLE_OK;
@@ -2830,16 +3053,16 @@ static CURLcode servercert(struct connectdata *conn,
infof(data, "%s certificate:\n", SSL_IS_PROXY() ? "Proxy" : "Server");
- rc = x509_name_oneline(X509_get_subject_name(connssl->server_cert),
+ rc = x509_name_oneline(X509_get_subject_name(BACKEND->server_cert),
buffer, sizeof(buffer));
infof(data, " subject: %s\n", rc?"[NONE]":buffer);
- ASN1_TIME_print(mem, X509_get0_notBefore(connssl->server_cert));
+ ASN1_TIME_print(mem, X509_get0_notBefore(BACKEND->server_cert));
len = BIO_get_mem_data(mem, (char **) &ptr);
infof(data, " start date: %.*s\n", len, ptr);
rc = BIO_reset(mem);
- ASN1_TIME_print(mem, X509_get0_notAfter(connssl->server_cert));
+ ASN1_TIME_print(mem, X509_get0_notAfter(BACKEND->server_cert));
len = BIO_get_mem_data(mem, (char **) &ptr);
infof(data, " expire date: %.*s\n", len, ptr);
rc = BIO_reset(mem);
@@ -2847,15 +3070,15 @@ static CURLcode servercert(struct connectdata *conn,
BIO_free(mem);
if(SSL_CONN_CONFIG(verifyhost)) {
- result = verifyhost(conn, connssl->server_cert);
+ result = verifyhost(conn, BACKEND->server_cert);
if(result) {
- X509_free(connssl->server_cert);
- connssl->server_cert = NULL;
+ X509_free(BACKEND->server_cert);
+ BACKEND->server_cert = NULL;
return result;
}
}
- rc = x509_name_oneline(X509_get_issuer_name(connssl->server_cert),
+ rc = x509_name_oneline(X509_get_issuer_name(BACKEND->server_cert),
buffer, sizeof(buffer));
if(rc) {
if(strict)
@@ -2875,8 +3098,8 @@ static CURLcode servercert(struct connectdata *conn,
if(strict)
failf(data, "SSL: Unable to open issuer cert (%s)",
SSL_SET_OPTION(issuercert));
- X509_free(connssl->server_cert);
- connssl->server_cert = NULL;
+ X509_free(BACKEND->server_cert);
+ BACKEND->server_cert = NULL;
return CURLE_SSL_ISSUER_ERROR;
}
@@ -2885,7 +3108,7 @@ static CURLcode servercert(struct connectdata *conn,
if(strict)
failf(data, "SSL: Unable to read issuer cert (%s)",
SSL_SET_OPTION(issuercert));
- X509_free(connssl->server_cert);
+ X509_free(BACKEND->server_cert);
X509_free(issuer);
fclose(fp);
return CURLE_SSL_ISSUER_ERROR;
@@ -2893,13 +3116,13 @@ static CURLcode servercert(struct connectdata *conn,
fclose(fp);
- if(X509_check_issued(issuer, connssl->server_cert) != X509_V_OK) {
+ if(X509_check_issued(issuer, BACKEND->server_cert) != X509_V_OK) {
if(strict)
failf(data, "SSL: Certificate issuer check failed (%s)",
SSL_SET_OPTION(issuercert));
- X509_free(connssl->server_cert);
+ X509_free(BACKEND->server_cert);
X509_free(issuer);
- connssl->server_cert = NULL;
+ BACKEND->server_cert = NULL;
return CURLE_SSL_ISSUER_ERROR;
}
@@ -2908,7 +3131,7 @@ static CURLcode servercert(struct connectdata *conn,
X509_free(issuer);
}
- lerr = *certverifyresult = SSL_get_verify_result(connssl->handle);
+ lerr = *certverifyresult = SSL_get_verify_result(BACKEND->handle);
if(*certverifyresult != X509_V_OK) {
if(SSL_CONN_CONFIG(verifypeer)) {
@@ -2933,8 +3156,8 @@ static CURLcode servercert(struct connectdata *conn,
if(SSL_CONN_CONFIG(verifystatus)) {
result = verifystatus(conn, connssl);
if(result) {
- X509_free(connssl->server_cert);
- connssl->server_cert = NULL;
+ X509_free(BACKEND->server_cert);
+ BACKEND->server_cert = NULL;
return result;
}
}
@@ -2947,13 +3170,13 @@ static CURLcode servercert(struct connectdata *conn,
ptr = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
if(!result && ptr) {
- result = pkp_pin_peer_pubkey(data, connssl->server_cert, ptr);
+ result = pkp_pin_peer_pubkey(data, BACKEND->server_cert, ptr);
if(result)
failf(data, "SSL: public key does not match pinned public key!");
}
- X509_free(connssl->server_cert);
- connssl->server_cert = NULL;
+ X509_free(BACKEND->server_cert);
+ BACKEND->server_cert = NULL;
connssl->connecting_state = ssl_connect_done;
return result;
@@ -2972,7 +3195,7 @@ static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex)
SSL_SESSION *our_ssl_sessionid;
void *old_ssl_sessionid = NULL;
- our_ssl_sessionid = SSL_get1_session(connssl->handle);
+ our_ssl_sessionid = SSL_get1_session(BACKEND->handle);
/* SSL_get1_session() will increment the reference count and the session
will stay in memory until explicitly freed with SSL_SESSION_free(3),
@@ -3077,9 +3300,9 @@ static CURLcode ossl_connect_common(struct connectdata *conn,
if(connssl->connecting_state == ssl_connect_2_reading ||
connssl->connecting_state == ssl_connect_2_writing) {
- curl_socket_t writefd = ssl_connect_2_writing==
+ curl_socket_t writefd = ssl_connect_2_writing ==
connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
- curl_socket_t readfd = ssl_connect_2_reading==
+ curl_socket_t readfd = ssl_connect_2_reading ==
connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
@@ -3137,14 +3360,14 @@ static CURLcode ossl_connect_common(struct connectdata *conn,
return CURLE_OK;
}
-CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done)
+static CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn,
+ int sockindex,
+ bool *done)
{
return ossl_connect_common(conn, sockindex, TRUE, done);
}
-CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex)
+static CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex)
{
CURLcode result;
bool done = FALSE;
@@ -3158,17 +3381,22 @@ CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex)
return CURLE_OK;
}
-bool Curl_ossl_data_pending(const struct connectdata *conn, int connindex)
+static bool Curl_ossl_data_pending(const struct connectdata *conn,
+ int connindex)
{
- if(conn->ssl[connindex].handle)
+ const struct ssl_connect_data *connssl = &conn->ssl[connindex];
+ const struct ssl_connect_data *proxyssl = &conn->proxy_ssl[connindex];
+ if(BACKEND->handle)
/* SSL is in use */
- return (0 != SSL_pending(conn->ssl[connindex].handle) ||
- (conn->proxy_ssl[connindex].handle &&
- 0 != SSL_pending(conn->proxy_ssl[connindex].handle))) ?
+ return (0 != SSL_pending(BACKEND->handle) ||
+ (proxyssl->backend->handle &&
+ 0 != SSL_pending(proxyssl->backend->handle))) ?
TRUE : FALSE;
return FALSE;
}
+static size_t Curl_ossl_version(char *buffer, size_t size);
+
static ssize_t ossl_send(struct connectdata *conn,
int sockindex,
const void *mem,
@@ -3182,14 +3410,15 @@ static ssize_t ossl_send(struct connectdata *conn,
unsigned long sslerror;
int memlen;
int rc;
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
ERR_clear_error();
memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
- rc = SSL_write(conn->ssl[sockindex].handle, mem, memlen);
+ rc = SSL_write(BACKEND->handle, mem, memlen);
if(rc <= 0) {
- err = SSL_get_error(conn->ssl[sockindex].handle, rc);
+ err = SSL_get_error(BACKEND->handle, rc);
switch(err) {
case SSL_ERROR_WANT_READ:
@@ -3243,14 +3472,15 @@ static ssize_t ossl_recv(struct connectdata *conn, /* connection data */
unsigned long sslerror;
ssize_t nread;
int buffsize;
+ struct ssl_connect_data *connssl = &conn->ssl[num];
ERR_clear_error();
buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
- nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf, buffsize);
+ nread = (ssize_t)SSL_read(BACKEND->handle, buf, buffsize);
if(nread <= 0) {
/* failed SSL_read */
- int err = SSL_get_error(conn->ssl[num].handle, (int)nread);
+ int err = SSL_get_error(BACKEND->handle, (int)nread);
switch(err) {
case SSL_ERROR_NONE: /* this is not an error */
@@ -3282,7 +3512,7 @@ static ssize_t ossl_recv(struct connectdata *conn, /* connection data */
return nread;
}
-size_t Curl_ossl_version(char *buffer, size_t size)
+static size_t Curl_ossl_version(char *buffer, size_t size)
{
#ifdef OPENSSL_IS_BORINGSSL
return snprintf(buffer, size, OSSL_PACKAGE);
@@ -3291,9 +3521,9 @@ size_t Curl_ossl_version(char *buffer, size_t size)
unsigned long ssleay_value;
sub[2]='\0';
sub[1]='\0';
- ssleay_value=OpenSSL_version_num();
+ ssleay_value = OpenSSL_version_num();
if(ssleay_value < 0x906000) {
- ssleay_value=SSLEAY_VERSION_NUMBER;
+ ssleay_value = SSLEAY_VERSION_NUMBER;
sub[0]='\0';
}
else {
@@ -3322,8 +3552,8 @@ size_t Curl_ossl_version(char *buffer, size_t size)
}
/* can be called with data == NULL */
-CURLcode Curl_ossl_random(struct Curl_easy *data, unsigned char *entropy,
- size_t length)
+static CURLcode Curl_ossl_random(struct Curl_easy *data,
+ unsigned char *entropy, size_t length)
{
int rc;
if(data) {
@@ -3339,23 +3569,24 @@ CURLcode Curl_ossl_random(struct Curl_easy *data, unsigned char *entropy,
return (rc == 1 ? CURLE_OK : CURLE_FAILED_INIT);
}
-void Curl_ossl_md5sum(unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *md5sum /* output */,
- size_t unused)
+static CURLcode Curl_ossl_md5sum(unsigned char *tmp, /* input */
+ size_t tmplen,
+ unsigned char *md5sum /* output */,
+ size_t unused)
{
MD5_CTX MD5pw;
(void)unused;
MD5_Init(&MD5pw);
MD5_Update(&MD5pw, tmp, tmplen);
MD5_Final(md5sum, &MD5pw);
+ return CURLE_OK;
}
#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
-void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *sha256sum /* output */,
- size_t unused)
+static void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
+ size_t tmplen,
+ unsigned char *sha256sum /* output */,
+ size_t unused)
{
SHA256_CTX SHA256pw;
(void)unused;
@@ -3365,7 +3596,7 @@ void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
}
#endif
-bool Curl_ossl_cert_status_request(void)
+static bool Curl_ossl_cert_status_request(void)
{
#if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
!defined(OPENSSL_NO_OCSP)
@@ -3374,4 +3605,50 @@ bool Curl_ossl_cert_status_request(void)
return FALSE;
#endif
}
+
+static void *Curl_ossl_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info)
+{
+ /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */
+ return info == CURLINFO_TLS_SESSION ?
+ (void *)BACKEND->ctx : (void *)BACKEND->handle;
+}
+
+const struct Curl_ssl Curl_ssl_openssl = {
+ { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */
+
+ 1, /* have_ca_path */
+ 1, /* have_certinfo */
+ 1, /* have_pinnedpubkey */
+ 1, /* have_ssl_ctx */
+ 1, /* support_https_proxy */
+
+ sizeof(struct ssl_backend_data),
+
+ Curl_ossl_init, /* init */
+ Curl_ossl_cleanup, /* cleanup */
+ Curl_ossl_version, /* version */
+ Curl_ossl_check_cxn, /* check_cxn */
+ Curl_ossl_shutdown, /* shutdown */
+ Curl_ossl_data_pending, /* data_pending */
+ Curl_ossl_random, /* random */
+ Curl_ossl_cert_status_request, /* cert_status_request */
+ Curl_ossl_connect, /* connect */
+ Curl_ossl_connect_nonblocking, /* connect_nonblocking */
+ Curl_ossl_get_internals, /* get_internals */
+ Curl_ossl_close, /* close */
+ Curl_ossl_close_all, /* close_all */
+ Curl_ossl_session_free, /* session_free */
+ Curl_ossl_set_engine, /* set_engine */
+ Curl_ossl_set_engine_default, /* set_engine_default */
+ Curl_ossl_engines_list, /* engines_list */
+ Curl_none_false_start, /* false_start */
+ Curl_ossl_md5sum, /* md5sum */
+#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
+ Curl_ossl_sha256sum /* sha256sum */
+#else
+ NULL /* sha256sum */
+#endif
+};
+
#endif /* USE_OPENSSL */
diff --git a/Utilities/cmcurl/lib/vtls/openssl.h b/Utilities/cmcurl/lib/vtls/openssl.h
index b9648d514..114dc4bae 100644
--- a/Utilities/cmcurl/lib/vtls/openssl.h
+++ b/Utilities/cmcurl/lib/vtls/openssl.h
@@ -31,96 +31,7 @@
#include "urldata.h"
-CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex);
-CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done);
-
-/* close a SSL connection */
-void Curl_ossl_close(struct connectdata *conn, int sockindex);
-
-/* tell OpenSSL to close down all open information regarding connections (and
- thus session ID caching etc) */
-void Curl_ossl_close_all(struct Curl_easy *data);
-
-/* Sets an OpenSSL engine */
-CURLcode Curl_ossl_set_engine(struct Curl_easy *data, const char *engine);
-
-/* function provided for the generic SSL-layer, called when a session id
- should be freed */
-void Curl_ossl_session_free(void *ptr);
-
-/* Sets engine as default for all SSL operations */
-CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data);
-
-/* Build list of OpenSSL engines */
-struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data);
-
-int Curl_ossl_init(void);
-void Curl_ossl_cleanup(void);
-
-size_t Curl_ossl_version(char *buffer, size_t size);
-int Curl_ossl_check_cxn(struct connectdata *cxn);
-int Curl_ossl_shutdown(struct connectdata *conn, int sockindex);
-bool Curl_ossl_data_pending(const struct connectdata *conn,
- int connindex);
-
-/* return 0 if a find random is filled in */
-CURLcode Curl_ossl_random(struct Curl_easy *data, unsigned char *entropy,
- size_t length);
-void Curl_ossl_md5sum(unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *md5sum /* output */,
- size_t unused);
-void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
- size_t tmplen,
- unsigned char *sha256sum /* output */,
- size_t unused);
-
-bool Curl_ossl_cert_status_request(void);
-
-/* Support HTTPS-proxy */
-#define HTTPS_PROXY_SUPPORT 1
-
-/* Set the API backend definition to OpenSSL */
-#define CURL_SSL_BACKEND CURLSSLBACKEND_OPENSSL
-
-/* this backend supports the CAPATH option */
-#define have_curlssl_ca_path 1
-
-/* this backend supports CURLOPT_CERTINFO */
-#define have_curlssl_certinfo 1
-
-/* this backend supports CURLOPT_SSL_CTX_* */
-#define have_curlssl_ssl_ctx 1
-
-/* this backend supports CURLOPT_PINNEDPUBLICKEY */
-#define have_curlssl_pinnedpubkey 1
-
-/* API setup for OpenSSL */
-#define curlssl_init Curl_ossl_init
-#define curlssl_cleanup Curl_ossl_cleanup
-#define curlssl_connect Curl_ossl_connect
-#define curlssl_connect_nonblocking Curl_ossl_connect_nonblocking
-#define curlssl_session_free(x) Curl_ossl_session_free(x)
-#define curlssl_close_all Curl_ossl_close_all
-#define curlssl_close Curl_ossl_close
-#define curlssl_shutdown(x,y) Curl_ossl_shutdown(x,y)
-#define curlssl_set_engine(x,y) Curl_ossl_set_engine(x,y)
-#define curlssl_set_engine_default(x) Curl_ossl_set_engine_default(x)
-#define curlssl_engines_list(x) Curl_ossl_engines_list(x)
-#define curlssl_version Curl_ossl_version
-#define curlssl_check_cxn Curl_ossl_check_cxn
-#define curlssl_data_pending(x,y) Curl_ossl_data_pending(x,y)
-#define curlssl_random(x,y,z) Curl_ossl_random(x,y,z)
-#define curlssl_md5sum(a,b,c,d) Curl_ossl_md5sum(a,b,c,d)
-#if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
-#define curlssl_sha256sum(a,b,c,d) Curl_ossl_sha256sum(a,b,c,d)
-#endif
-#define curlssl_cert_status_request() Curl_ossl_cert_status_request()
-
-#define DEFAULT_CIPHER_SELECTION \
- "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH"
+extern const struct Curl_ssl Curl_ssl_openssl;
#endif /* USE_OPENSSL */
#endif /* HEADER_CURL_SSLUSE_H */
diff --git a/Utilities/cmcurl/lib/vtls/polarssl.c b/Utilities/cmcurl/lib/vtls/polarssl.c
index 669091cb5..fc0644f89 100644
--- a/Utilities/cmcurl/lib/vtls/polarssl.c
+++ b/Utilities/cmcurl/lib/vtls/polarssl.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 2012 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 2012 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
* Copyright (C) 2010 - 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com>
*
* This software is licensed as described in the file COPYING, which
@@ -30,7 +30,6 @@
#include "curl_setup.h"
#ifdef USE_POLARSSL
-
#include <polarssl/net.h>
#include <polarssl/ssl.h>
#include <polarssl/certs.h>
@@ -70,6 +69,19 @@
#define PUB_DER_MAX_BYTES (RSA_PUB_DER_MAX_BYTES > ECP_PUB_DER_MAX_BYTES ? \
RSA_PUB_DER_MAX_BYTES : ECP_PUB_DER_MAX_BYTES)
+struct ssl_backend_data {
+ ctr_drbg_context ctr_drbg;
+ entropy_context entropy;
+ ssl_context ssl;
+ int server_fd;
+ x509_crt cacert;
+ x509_crt clicert;
+ x509_crl crl;
+ rsa_context rsa;
+};
+
+#define BACKEND connssl->backend
+
/* apply threading? */
#if defined(USE_THREADS_POSIX) || defined(USE_THREADS_WIN32)
#define THREADING_SUPPORT
@@ -197,8 +209,8 @@ set_ssl_version_min_max(struct connectdata *conn, int sockindex)
return result;
}
- ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3, ssl_min_ver);
- ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3, ssl_max_ver);
+ ssl_set_min_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3, ssl_min_ver);
+ ssl_set_max_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3, ssl_max_ver);
return result;
}
@@ -215,7 +227,7 @@ polarssl_connect_step1(struct connectdata *conn,
const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
int ret = -1;
char errorbuf[128];
- errorbuf[0]=0;
+ errorbuf[0] = 0;
/* PolarSSL only supports SSLv3 and TLSv1 */
if(SSL_CONN_CONFIG(version) == CURL_SSLVERSION_SSLv2) {
@@ -226,16 +238,16 @@ polarssl_connect_step1(struct connectdata *conn,
#ifdef THREADING_SUPPORT
entropy_init_mutex(&entropy);
- if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func_mutex, &entropy,
+ if((ret = ctr_drbg_init(&BACKEND->ctr_drbg, entropy_func_mutex, &entropy,
NULL, 0)) != 0) {
error_strerror(ret, errorbuf, sizeof(errorbuf));
failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n",
-ret, errorbuf);
}
#else
- entropy_init(&connssl->entropy);
+ entropy_init(&BACKEND->entropy);
- if((ret = ctr_drbg_init(&connssl->ctr_drbg, entropy_func, &connssl->entropy,
+ if((ret = ctr_drbg_init(&BACKEND->ctr_drbg, entropy_func, &BACKEND->entropy,
NULL, 0)) != 0) {
error_strerror(ret, errorbuf, sizeof(errorbuf));
failf(data, "Failed - PolarSSL: ctr_drbg_init returned (-0x%04X) %s\n",
@@ -244,10 +256,10 @@ polarssl_connect_step1(struct connectdata *conn,
#endif /* THREADING_SUPPORT */
/* Load the trusted CA */
- memset(&connssl->cacert, 0, sizeof(x509_crt));
+ memset(&BACKEND->cacert, 0, sizeof(x509_crt));
if(SSL_CONN_CONFIG(CAfile)) {
- ret = x509_crt_parse_file(&connssl->cacert,
+ ret = x509_crt_parse_file(&BACKEND->cacert,
SSL_CONN_CONFIG(CAfile));
if(ret<0) {
@@ -261,7 +273,7 @@ polarssl_connect_step1(struct connectdata *conn,
}
if(capath) {
- ret = x509_crt_parse_path(&connssl->cacert, capath);
+ ret = x509_crt_parse_path(&BACKEND->cacert, capath);
if(ret<0) {
error_strerror(ret, errorbuf, sizeof(errorbuf));
@@ -274,10 +286,10 @@ polarssl_connect_step1(struct connectdata *conn,
}
/* Load the client certificate */
- memset(&connssl->clicert, 0, sizeof(x509_crt));
+ memset(&BACKEND->clicert, 0, sizeof(x509_crt));
if(SSL_SET_OPTION(cert)) {
- ret = x509_crt_parse_file(&connssl->clicert,
+ ret = x509_crt_parse_file(&BACKEND->clicert,
SSL_SET_OPTION(cert));
if(ret) {
@@ -298,9 +310,9 @@ polarssl_connect_step1(struct connectdata *conn,
if(ret == 0 && !pk_can_do(&pk, POLARSSL_PK_RSA))
ret = POLARSSL_ERR_PK_TYPE_MISMATCH;
if(ret == 0)
- rsa_copy(&connssl->rsa, pk_rsa(pk));
+ rsa_copy(&BACKEND->rsa, pk_rsa(pk));
else
- rsa_free(&connssl->rsa);
+ rsa_free(&BACKEND->rsa);
pk_free(&pk);
if(ret) {
@@ -313,10 +325,10 @@ polarssl_connect_step1(struct connectdata *conn,
}
/* Load the CRL */
- memset(&connssl->crl, 0, sizeof(x509_crl));
+ memset(&BACKEND->crl, 0, sizeof(x509_crl));
if(SSL_SET_OPTION(CRLfile)) {
- ret = x509_crl_parse_file(&connssl->crl,
+ ret = x509_crl_parse_file(&BACKEND->crl,
SSL_SET_OPTION(CRLfile));
if(ret) {
@@ -330,7 +342,7 @@ polarssl_connect_step1(struct connectdata *conn,
infof(data, "PolarSSL: Connecting to %s:%d\n", hostname, port);
- if(ssl_init(&connssl->ssl)) {
+ if(ssl_init(&BACKEND->ssl)) {
failf(data, "PolarSSL: ssl_init failed");
return CURLE_SSL_CONNECT_ERROR;
}
@@ -338,13 +350,13 @@ polarssl_connect_step1(struct connectdata *conn,
switch(SSL_CONN_CONFIG(version)) {
case CURL_SSLVERSION_DEFAULT:
case CURL_SSLVERSION_TLSv1:
- ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3,
+ ssl_set_min_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3,
SSL_MINOR_VERSION_1);
break;
case CURL_SSLVERSION_SSLv3:
- ssl_set_min_version(&connssl->ssl, SSL_MAJOR_VERSION_3,
+ ssl_set_min_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3,
SSL_MINOR_VERSION_0);
- ssl_set_max_version(&connssl->ssl, SSL_MAJOR_VERSION_3,
+ ssl_set_max_version(&BACKEND->ssl, SSL_MAJOR_VERSION_3,
SSL_MINOR_VERSION_0);
infof(data, "PolarSSL: Forced min. SSL Version to be SSLv3\n");
break;
@@ -363,16 +375,16 @@ polarssl_connect_step1(struct connectdata *conn,
return CURLE_SSL_CONNECT_ERROR;
}
- ssl_set_endpoint(&connssl->ssl, SSL_IS_CLIENT);
- ssl_set_authmode(&connssl->ssl, SSL_VERIFY_OPTIONAL);
+ ssl_set_endpoint(&BACKEND->ssl, SSL_IS_CLIENT);
+ ssl_set_authmode(&BACKEND->ssl, SSL_VERIFY_OPTIONAL);
- ssl_set_rng(&connssl->ssl, ctr_drbg_random,
- &connssl->ctr_drbg);
- ssl_set_bio(&connssl->ssl,
+ ssl_set_rng(&BACKEND->ssl, ctr_drbg_random,
+ &BACKEND->ctr_drbg);
+ ssl_set_bio(&BACKEND->ssl,
net_recv, &conn->sock[sockindex],
net_send, &conn->sock[sockindex]);
- ssl_set_ciphersuites(&connssl->ssl, ssl_list_ciphersuites());
+ ssl_set_ciphersuites(&BACKEND->ssl, ssl_list_ciphersuites());
/* Check if there's a cached ID we can/should use here! */
if(SSL_SET_OPTION(primary.sessionid)) {
@@ -380,7 +392,7 @@ polarssl_connect_step1(struct connectdata *conn,
Curl_ssl_sessionid_lock(conn);
if(!Curl_ssl_getsessionid(conn, &old_session, NULL, sockindex)) {
- ret = ssl_set_session(&connssl->ssl, old_session);
+ ret = ssl_set_session(&BACKEND->ssl, old_session);
if(ret) {
Curl_ssl_sessionid_unlock(conn);
failf(data, "ssl_set_session returned -0x%x", -ret);
@@ -391,15 +403,15 @@ polarssl_connect_step1(struct connectdata *conn,
Curl_ssl_sessionid_unlock(conn);
}
- ssl_set_ca_chain(&connssl->ssl,
- &connssl->cacert,
- &connssl->crl,
+ ssl_set_ca_chain(&BACKEND->ssl,
+ &BACKEND->cacert,
+ &BACKEND->crl,
hostname);
- ssl_set_own_cert_rsa(&connssl->ssl,
- &connssl->clicert, &connssl->rsa);
+ ssl_set_own_cert_rsa(&BACKEND->ssl,
+ &BACKEND->clicert, &BACKEND->rsa);
- if(ssl_set_hostname(&connssl->ssl, hostname)) {
+ if(ssl_set_hostname(&BACKEND->ssl, hostname)) {
/* ssl_set_hostname() sets the name to use in CN/SAN checks *and* the name
to set in the SNI extension. So even if curl connects to a host
specified as an IP address, this function must be used. */
@@ -424,12 +436,12 @@ polarssl_connect_step1(struct connectdata *conn,
protocols[cur] = NULL;
- ssl_set_alpn_protocols(&connssl->ssl, protocols);
+ ssl_set_alpn_protocols(&BACKEND->ssl, protocols);
}
#endif
#ifdef POLARSSL_DEBUG
- ssl_set_dbg(&connssl->ssl, polarssl_debug, data);
+ ssl_set_dbg(&BACKEND->ssl, polarssl_debug, data);
#endif
connssl->connecting_state = ssl_connect_2;
@@ -456,7 +468,7 @@ polarssl_connect_step2(struct connectdata *conn,
conn->recv[sockindex] = polarssl_recv;
conn->send[sockindex] = polarssl_send;
- ret = ssl_handshake(&connssl->ssl);
+ ret = ssl_handshake(&BACKEND->ssl);
switch(ret) {
case 0:
@@ -478,9 +490,9 @@ polarssl_connect_step2(struct connectdata *conn,
}
infof(data, "PolarSSL: Handshake complete, cipher is %s\n",
- ssl_get_ciphersuite(&conn->ssl[sockindex].ssl) );
+ ssl_get_ciphersuite(&BACKEND->ssl) );
- ret = ssl_get_verify_result(&conn->ssl[sockindex].ssl);
+ ret = ssl_get_verify_result(&BACKEND->ssl);
if(ret && SSL_CONN_CONFIG(verifypeer)) {
if(ret & BADCERT_EXPIRED)
@@ -500,12 +512,12 @@ polarssl_connect_step2(struct connectdata *conn,
return CURLE_PEER_FAILED_VERIFICATION;
}
- if(ssl_get_peer_cert(&(connssl->ssl))) {
+ if(ssl_get_peer_cert(&(BACKEND->ssl))) {
/* If the session was resumed, there will be no peer certs */
memset(buffer, 0, sizeof(buffer));
if(x509_crt_info(buffer, sizeof(buffer), (char *)"* ",
- ssl_get_peer_cert(&(connssl->ssl))) != -1)
+ ssl_get_peer_cert(&(BACKEND->ssl))) != -1)
infof(data, "Dumping cert info:\n%s\n", buffer);
}
@@ -517,7 +529,7 @@ polarssl_connect_step2(struct connectdata *conn,
unsigned char pubkey[PUB_DER_MAX_BYTES];
const x509_crt *peercert;
- peercert = ssl_get_peer_cert(&connssl->ssl);
+ peercert = ssl_get_peer_cert(&BACKEND->ssl);
if(!peercert || !peercert->raw.p || !peercert->raw.len) {
failf(data, "Failed due to missing peer certificate");
@@ -566,7 +578,7 @@ polarssl_connect_step2(struct connectdata *conn,
#ifdef HAS_ALPN
if(conn->bits.tls_enable_alpn) {
- const char *next_protocol = ssl_get_alpn_protocol(&connssl->ssl);
+ const char *next_protocol = ssl_get_alpn_protocol(&BACKEND->ssl);
if(next_protocol != NULL) {
infof(data, "ALPN, server accepted to use %s\n", next_protocol);
@@ -614,7 +626,7 @@ polarssl_connect_step3(struct connectdata *conn,
memset(our_ssl_sessionid, 0, sizeof(ssl_session));
- ret = ssl_get_session(&connssl->ssl, our_ssl_sessionid);
+ ret = ssl_get_session(&BACKEND->ssl, our_ssl_sessionid);
if(ret) {
failf(data, "ssl_get_session returned -0x%x", -ret);
return CURLE_SSL_CONNECT_ERROR;
@@ -645,9 +657,10 @@ static ssize_t polarssl_send(struct connectdata *conn,
size_t len,
CURLcode *curlcode)
{
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
int ret = -1;
- ret = ssl_write(&conn->ssl[sockindex].ssl,
+ ret = ssl_write(&BACKEND->ssl,
(unsigned char *)mem, len);
if(ret < 0) {
@@ -659,13 +672,14 @@ static ssize_t polarssl_send(struct connectdata *conn,
return ret;
}
-void Curl_polarssl_close(struct connectdata *conn, int sockindex)
+static void Curl_polarssl_close(struct connectdata *conn, int sockindex)
{
- rsa_free(&conn->ssl[sockindex].rsa);
- x509_crt_free(&conn->ssl[sockindex].clicert);
- x509_crt_free(&conn->ssl[sockindex].cacert);
- x509_crl_free(&conn->ssl[sockindex].crl);
- ssl_free(&conn->ssl[sockindex].ssl);
+ struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ rsa_free(&BACKEND->rsa);
+ x509_crt_free(&BACKEND->clicert);
+ x509_crt_free(&BACKEND->cacert);
+ x509_crl_free(&BACKEND->crl);
+ ssl_free(&BACKEND->ssl);
}
static ssize_t polarssl_recv(struct connectdata *conn,
@@ -674,11 +688,12 @@ static ssize_t polarssl_recv(struct connectdata *conn,
size_t buffersize,
CURLcode *curlcode)
{
+ struct ssl_connect_data *connssl = &conn->ssl[num];
int ret = -1;
ssize_t len = -1;
memset(buf, 0, buffersize);
- ret = ssl_read(&conn->ssl[num].ssl, (unsigned char *)buf, buffersize);
+ ret = ssl_read(&BACKEND->ssl, (unsigned char *)buf, buffersize);
if(ret <= 0) {
if(ret == POLARSSL_ERR_SSL_PEER_CLOSE_NOTIFY)
@@ -694,7 +709,7 @@ static ssize_t polarssl_recv(struct connectdata *conn,
return len;
}
-void Curl_polarssl_session_free(void *ptr)
+static void Curl_polarssl_session_free(void *ptr)
{
ssl_session_free(ptr);
free(ptr);
@@ -703,7 +718,7 @@ void Curl_polarssl_session_free(void *ptr)
/* 1.3.10 was the first rebranded version. All new releases (in 1.3 branch and
higher) will be mbed TLS branded.. */
-size_t Curl_polarssl_version(char *buffer, size_t size)
+static size_t Curl_polarssl_version(char *buffer, size_t size)
{
unsigned int version = version_get_number();
return snprintf(buffer, size, "%s/%d.%d.%d",
@@ -762,9 +777,9 @@ polarssl_connect_common(struct connectdata *conn,
if(connssl->connecting_state == ssl_connect_2_reading ||
connssl->connecting_state == ssl_connect_2_writing) {
- curl_socket_t writefd = ssl_connect_2_writing==
+ curl_socket_t writefd = ssl_connect_2_writing ==
connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
- curl_socket_t readfd = ssl_connect_2_reading==
+ curl_socket_t readfd = ssl_connect_2_reading ==
connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
@@ -825,18 +840,14 @@ polarssl_connect_common(struct connectdata *conn,
return CURLE_OK;
}
-CURLcode
-Curl_polarssl_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done)
+static CURLcode Curl_polarssl_connect_nonblocking(struct connectdata *conn,
+ int sockindex, bool *done)
{
return polarssl_connect_common(conn, sockindex, TRUE, done);
}
-CURLcode
-Curl_polarssl_connect(struct connectdata *conn,
- int sockindex)
+static CURLcode Curl_polarssl_connect(struct connectdata *conn, int sockindex)
{
CURLcode result;
bool done = FALSE;
@@ -854,20 +865,73 @@ Curl_polarssl_connect(struct connectdata *conn,
* return 0 error initializing SSL
* return 1 SSL initialized successfully
*/
-int Curl_polarssl_init(void)
+static int Curl_polarssl_init(void)
{
return Curl_polarsslthreadlock_thread_setup();
}
-void Curl_polarssl_cleanup(void)
+static void Curl_polarssl_cleanup(void)
{
(void)Curl_polarsslthreadlock_thread_cleanup();
}
+static bool Curl_polarssl_data_pending(const struct connectdata *conn,
+ int sockindex)
+{
+ const struct ssl_connect_data *connssl = &conn->ssl[sockindex];
+ return ssl_get_bytes_avail(&BACKEND->ssl) != 0;
+}
+
+static void Curl_polarssl_sha256sum(const unsigned char *input,
+ size_t inputlen,
+ unsigned char *sha256sum,
+ size_t sha256len UNUSED_PARAM)
+{
+ (void)sha256len;
+ sha256(input, inputlen, sha256sum, 0);
+}
-int Curl_polarssl_data_pending(const struct connectdata *conn, int sockindex)
+static void *Curl_polarssl_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info UNUSED_PARAM)
{
- return ssl_get_bytes_avail(&conn->ssl[sockindex].ssl) != 0;
+ (void)info;
+ return &BACKEND->ssl;
}
+const struct Curl_ssl Curl_ssl_polarssl = {
+ { CURLSSLBACKEND_POLARSSL, "polarssl" }, /* info */
+
+ 1, /* have_ca_path */
+ 0, /* have_certinfo */
+ 1, /* have_pinnedpubkey */
+ 0, /* have_ssl_ctx */
+ 0, /* support_https_proxy */
+
+ sizeof(struct ssl_backend_data),
+
+ Curl_polarssl_init, /* init */
+ Curl_polarssl_cleanup, /* cleanup */
+ Curl_polarssl_version, /* version */
+ Curl_none_check_cxn, /* check_cxn */
+ Curl_none_shutdown, /* shutdown */
+ Curl_polarssl_data_pending, /* data_pending */
+ /* This might cause libcurl to use a weeker random!
+ * TODO: use Polarssl's CTR-DRBG or HMAC-DRBG
+ */
+ Curl_none_random, /* random */
+ Curl_none_cert_status_request, /* cert_status_request */
+ Curl_polarssl_connect, /* connect */
+ Curl_polarssl_connect_nonblocking, /* connect_nonblocking */
+ Curl_polarssl_get_internals, /* get_internals */
+ Curl_polarssl_close, /* close */
+ Curl_none_close_all, /* close_all */
+ Curl_polarssl_session_free, /* session_free */
+ Curl_none_set_engine, /* set_engine */
+ Curl_none_set_engine_default, /* set_engine_default */
+ Curl_none_engines_list, /* engines_list */
+ Curl_none_false_start, /* false_start */
+ Curl_none_md5sum, /* md5sum */
+ Curl_polarssl_sha256sum /* sha256sum */
+};
+
#endif /* USE_POLARSSL */
diff --git a/Utilities/cmcurl/lib/vtls/polarssl.h b/Utilities/cmcurl/lib/vtls/polarssl.h
index 47af7b417..23c3636ee 100644
--- a/Utilities/cmcurl/lib/vtls/polarssl.h
+++ b/Utilities/cmcurl/lib/vtls/polarssl.h
@@ -26,57 +26,7 @@
#ifdef USE_POLARSSL
-#include <polarssl/sha256.h>
-
-/* Called on first use PolarSSL, setup threading if supported */
-int Curl_polarssl_init(void);
-void Curl_polarssl_cleanup(void);
-int Curl_polarssl_data_pending(const struct connectdata *conn, int sockindex);
-
-
-CURLcode Curl_polarssl_connect(struct connectdata *conn, int sockindex);
-
-CURLcode Curl_polarssl_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done);
-
- /* close a SSL connection */
-void Curl_polarssl_close(struct connectdata *conn, int sockindex);
-
-void Curl_polarssl_session_free(void *ptr);
-size_t Curl_polarssl_version(char *buffer, size_t size);
-int Curl_polarssl_shutdown(struct connectdata *conn, int sockindex);
-
-/* Set the API backend definition to PolarSSL */
-#define CURL_SSL_BACKEND CURLSSLBACKEND_POLARSSL
-
-/* this backend supports the CAPATH option */
-#define have_curlssl_ca_path 1
-
-/* this backends supports CURLOPT_PINNEDPUBLICKEY */
-#define have_curlssl_pinnedpubkey 1
-
-/* API setup for PolarSSL */
-#define curlssl_init() Curl_polarssl_init()
-#define curlssl_cleanup() Curl_polarssl_cleanup()
-#define curlssl_connect Curl_polarssl_connect
-#define curlssl_connect_nonblocking Curl_polarssl_connect_nonblocking
-#define curlssl_session_free(x) Curl_polarssl_session_free(x)
-#define curlssl_close_all(x) ((void)x)
-#define curlssl_close Curl_polarssl_close
-#define curlssl_shutdown(x,y) 0
-#define curlssl_set_engine(x,y) ((void)x, (void)y, CURLE_NOT_BUILT_IN)
-#define curlssl_set_engine_default(x) ((void)x, CURLE_NOT_BUILT_IN)
-#define curlssl_engines_list(x) ((void)x, (struct curl_slist *)NULL)
-#define curlssl_version Curl_polarssl_version
-#define curlssl_check_cxn(x) ((void)x, -1)
-#define curlssl_data_pending(x,y) Curl_polarssl_data_pending(x, y)
-#define curlssl_sha256sum(a,b,c,d) sha256(a,b,c,0)
-
-/* This might cause libcurl to use a weeker random!
- TODO: implement proper use of Polarssl's CTR-DRBG or HMAC-DRBG and use that
-*/
-#define curlssl_random(x,y,z) ((void)x, (void)y, (void)z, CURLE_NOT_BUILT_IN)
+extern const struct Curl_ssl Curl_ssl_polarssl;
#endif /* USE_POLARSSL */
#endif /* HEADER_CURL_POLARSSL_H */
diff --git a/Utilities/cmcurl/lib/vtls/polarssl_threadlock.c b/Utilities/cmcurl/lib/vtls/polarssl_threadlock.c
index b1eb7b746..dd5fbd7ec 100644
--- a/Utilities/cmcurl/lib/vtls/polarssl_threadlock.c
+++ b/Utilities/cmcurl/lib/vtls/polarssl_threadlock.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 2013-2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 2013-2017, Daniel Stenberg, <daniel@haxx.se>, et al.
* Copyright (C) 2010, 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com>
*
* This software is licensed as described in the file COPYING, which
@@ -114,7 +114,7 @@ int Curl_polarsslthreadlock_lock_function(int n)
}
#elif defined(HAVE_PROCESS_H)
if(n < NUMT) {
- ret = (WaitForSingleObject(mutex_buf[n], INFINITE)==WAIT_FAILED?1:0);
+ ret = (WaitForSingleObject(mutex_buf[n], INFINITE) == WAIT_FAILED?1:0);
if(ret) {
DEBUGF(fprintf(stderr,
"Error: polarsslthreadlock_lock_function failed\n"));
diff --git a/Utilities/cmcurl/lib/vtls/schannel.c b/Utilities/cmcurl/lib/vtls/schannel.c
index 94603018b..9ca1431bd 100644
--- a/Utilities/cmcurl/lib/vtls/schannel.c
+++ b/Utilities/cmcurl/lib/vtls/schannel.c
@@ -46,6 +46,8 @@
# error "Can't compile SCHANNEL support without SSPI."
#endif
+#include <schnlsp.h>
+#include <schannel.h>
#include "curl_sspi.h"
#include "schannel.h"
#include "vtls.h"
@@ -74,11 +76,92 @@
# define HAS_ALPN 1
#endif
+#ifndef UNISP_NAME_A
+#define UNISP_NAME_A "Microsoft Unified Security Protocol Provider"
+#endif
+
+#ifndef UNISP_NAME_W
+#define UNISP_NAME_W L"Microsoft Unified Security Protocol Provider"
+#endif
+
+#ifndef UNISP_NAME
+#ifdef UNICODE
+#define UNISP_NAME UNISP_NAME_W
+#else
+#define UNISP_NAME UNISP_NAME_A
+#endif
+#endif
+
+#ifndef SP_PROT_SSL2_CLIENT
+#define SP_PROT_SSL2_CLIENT 0x00000008
+#endif
+
+#ifndef SP_PROT_SSL3_CLIENT
+#define SP_PROT_SSL3_CLIENT 0x00000008
+#endif
+
+#ifndef SP_PROT_TLS1_CLIENT
+#define SP_PROT_TLS1_CLIENT 0x00000080
+#endif
+
+#ifndef SP_PROT_TLS1_0_CLIENT
+#define SP_PROT_TLS1_0_CLIENT SP_PROT_TLS1_CLIENT
+#endif
+
+#ifndef SP_PROT_TLS1_1_CLIENT
+#define SP_PROT_TLS1_1_CLIENT 0x00000200
+#endif
+
+#ifndef SP_PROT_TLS1_2_CLIENT
+#define SP_PROT_TLS1_2_CLIENT 0x00000800
+#endif
+
+#ifndef SECBUFFER_ALERT
+#define SECBUFFER_ALERT 17
+#endif
+
+/* Both schannel buffer sizes must be > 0 */
+#define CURL_SCHANNEL_BUFFER_INIT_SIZE 4096
+#define CURL_SCHANNEL_BUFFER_FREE_SIZE 1024
+
/* Uncomment to force verbose output
* #define infof(x, y, ...) printf(y, __VA_ARGS__)
* #define failf(x, y, ...) printf(y, __VA_ARGS__)
*/
+/* Structs to store Schannel handles */
+struct curl_schannel_cred {
+ CredHandle cred_handle;
+ TimeStamp time_stamp;
+ int refcount;
+};
+
+struct curl_schannel_ctxt {
+ CtxtHandle ctxt_handle;
+ TimeStamp time_stamp;
+};
+
+struct ssl_backend_data {
+ struct curl_schannel_cred *cred;
+ struct curl_schannel_ctxt *ctxt;
+ SecPkgContext_StreamSizes stream_sizes;
+ size_t encdata_length, decdata_length;
+ size_t encdata_offset, decdata_offset;
+ unsigned char *encdata_buffer, *decdata_buffer;
+ /* encdata_is_incomplete: if encdata contains only a partial record that
+ can't be decrypted without another Curl_read_plain (that is, status is
+ SEC_E_INCOMPLETE_MESSAGE) then set this true. after Curl_read_plain writes
+ more bytes into encdata then set this back to false. */
+ bool encdata_is_incomplete;
+ unsigned long req_flags, ret_flags;
+ CURLcode recv_unrecoverable_err; /* schannel_recv had an unrecoverable err */
+ bool recv_sspi_close_notify; /* true if connection closed by close_notify */
+ bool recv_connection_closed; /* true if connection closed, regardless how */
+ bool use_alpn; /* true if ALPN is used for this connection */
+};
+
+#define BACKEND connssl->backend
+
static Curl_recv schannel_recv;
static Curl_send schannel_send;
@@ -176,33 +259,33 @@ schannel_connect_step1(struct connectdata *conn, int sockindex)
#ifdef HAS_ALPN
/* ALPN is only supported on Windows 8.1 / Server 2012 R2 and above.
Also it doesn't seem to be supported for Wine, see curl bug #983. */
- connssl->use_alpn = conn->bits.tls_enable_alpn &&
+ BACKEND->use_alpn = conn->bits.tls_enable_alpn &&
!GetProcAddress(GetModuleHandleA("ntdll"),
"wine_get_version") &&
Curl_verify_windows_version(6, 3, PLATFORM_WINNT,
VERSION_GREATER_THAN_EQUAL);
#else
- connssl->use_alpn = false;
+ BACKEND->use_alpn = false;
#endif
- connssl->cred = NULL;
+ BACKEND->cred = NULL;
/* check for an existing re-usable credential handle */
if(SSL_SET_OPTION(primary.sessionid)) {
Curl_ssl_sessionid_lock(conn);
if(!Curl_ssl_getsessionid(conn, (void **)&old_cred, NULL, sockindex)) {
- connssl->cred = old_cred;
+ BACKEND->cred = old_cred;
infof(data, "schannel: re-using existing credential handle\n");
/* increment the reference counter of the credential/session handle */
- connssl->cred->refcount++;
+ BACKEND->cred->refcount++;
infof(data, "schannel: incremented credential handle refcount = %d\n",
- connssl->cred->refcount);
+ BACKEND->cred->refcount);
}
Curl_ssl_sessionid_unlock(conn);
}
- if(!connssl->cred) {
+ if(!BACKEND->cred) {
/* setup Schannel API options */
memset(&schannel_cred, 0, sizeof(schannel_cred));
schannel_cred.dwVersion = SCHANNEL_CRED_VERSION;
@@ -272,14 +355,14 @@ schannel_connect_step1(struct connectdata *conn, int sockindex)
}
/* allocate memory for the re-usable credential handle */
- connssl->cred = (struct curl_schannel_cred *)
+ BACKEND->cred = (struct curl_schannel_cred *)
malloc(sizeof(struct curl_schannel_cred));
- if(!connssl->cred) {
+ if(!BACKEND->cred) {
failf(data, "schannel: unable to allocate memory");
return CURLE_OUT_OF_MEMORY;
}
- memset(connssl->cred, 0, sizeof(struct curl_schannel_cred));
- connssl->cred->refcount = 1;
+ memset(BACKEND->cred, 0, sizeof(struct curl_schannel_cred));
+ BACKEND->cred->refcount = 1;
/* https://msdn.microsoft.com/en-us/library/windows/desktop/aa374716.aspx
*/
@@ -287,8 +370,8 @@ schannel_connect_step1(struct connectdata *conn, int sockindex)
s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *)UNISP_NAME,
SECPKG_CRED_OUTBOUND, NULL,
&schannel_cred, NULL, NULL,
- &connssl->cred->cred_handle,
- &connssl->cred->time_stamp);
+ &BACKEND->cred->cred_handle,
+ &BACKEND->cred->time_stamp);
if(sspi_status != SEC_E_OK) {
if(sspi_status == SEC_E_WRONG_PRINCIPAL)
@@ -297,7 +380,7 @@ schannel_connect_step1(struct connectdata *conn, int sockindex)
else
failf(data, "schannel: AcquireCredentialsHandle failed: %s",
Curl_sspi_strerror(conn, sspi_status));
- Curl_safefree(connssl->cred);
+ Curl_safefree(BACKEND->cred);
return CURLE_SSL_CONNECT_ERROR;
}
}
@@ -312,7 +395,7 @@ schannel_connect_step1(struct connectdata *conn, int sockindex)
}
#ifdef HAS_ALPN
- if(connssl->use_alpn) {
+ if(BACKEND->use_alpn) {
int cur = 0;
int list_start_index = 0;
unsigned int *extension_len = NULL;
@@ -370,18 +453,18 @@ schannel_connect_step1(struct connectdata *conn, int sockindex)
InitSecBufferDesc(&outbuf_desc, &outbuf, 1);
/* setup request flags */
- connssl->req_flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT |
+ BACKEND->req_flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT |
ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY |
ISC_REQ_STREAM;
/* allocate memory for the security context handle */
- connssl->ctxt = (struct curl_schannel_ctxt *)
+ BACKEND->ctxt = (struct curl_schannel_ctxt *)
malloc(sizeof(struct curl_schannel_ctxt));
- if(!connssl->ctxt) {
+ if(!BACKEND->ctxt) {
failf(data, "schannel: unable to allocate memory");
return CURLE_OUT_OF_MEMORY;
}
- memset(connssl->ctxt, 0, sizeof(struct curl_schannel_ctxt));
+ memset(BACKEND->ctxt, 0, sizeof(struct curl_schannel_ctxt));
host_name = Curl_convert_UTF8_to_tchar(hostname);
if(!host_name)
@@ -395,10 +478,10 @@ schannel_connect_step1(struct connectdata *conn, int sockindex)
us problems with inbuf regardless. https://github.com/curl/curl/issues/983
*/
sspi_status = s_pSecFn->InitializeSecurityContext(
- &connssl->cred->cred_handle, NULL, host_name, connssl->req_flags, 0, 0,
- (connssl->use_alpn ? &inbuf_desc : NULL),
- 0, &connssl->ctxt->ctxt_handle,
- &outbuf_desc, &connssl->ret_flags, &connssl->ctxt->time_stamp);
+ &BACKEND->cred->cred_handle, NULL, host_name, BACKEND->req_flags, 0, 0,
+ (BACKEND->use_alpn ? &inbuf_desc : NULL),
+ 0, &BACKEND->ctxt->ctxt_handle,
+ &outbuf_desc, &BACKEND->ret_flags, &BACKEND->ctxt->time_stamp);
Curl_unicodefree(host_name);
@@ -409,7 +492,7 @@ schannel_connect_step1(struct connectdata *conn, int sockindex)
else
failf(data, "schannel: initial InitializeSecurityContext failed: %s",
Curl_sspi_strerror(conn, sspi_status));
- Curl_safefree(connssl->ctxt);
+ Curl_safefree(BACKEND->ctxt);
return CURLE_SSL_CONNECT_ERROR;
}
@@ -429,10 +512,10 @@ schannel_connect_step1(struct connectdata *conn, int sockindex)
infof(data, "schannel: sent initial handshake data: "
"sent %zd bytes\n", written);
- connssl->recv_unrecoverable_err = CURLE_OK;
- connssl->recv_sspi_close_notify = false;
- connssl->recv_connection_closed = false;
- connssl->encdata_is_incomplete = false;
+ BACKEND->recv_unrecoverable_err = CURLE_OK;
+ BACKEND->recv_sspi_close_notify = false;
+ BACKEND->recv_connection_closed = false;
+ BACKEND->encdata_is_incomplete = false;
/* continue to second handshake step */
connssl->connecting_state = ssl_connect_2;
@@ -465,39 +548,39 @@ schannel_connect_step2(struct connectdata *conn, int sockindex)
infof(data, "schannel: SSL/TLS connection with %s port %hu (step 2/3)\n",
hostname, conn->remote_port);
- if(!connssl->cred || !connssl->ctxt)
+ if(!BACKEND->cred || !BACKEND->ctxt)
return CURLE_SSL_CONNECT_ERROR;
/* buffer to store previously received and decrypted data */
- if(connssl->decdata_buffer == NULL) {
- connssl->decdata_offset = 0;
- connssl->decdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
- connssl->decdata_buffer = malloc(connssl->decdata_length);
- if(connssl->decdata_buffer == NULL) {
+ if(BACKEND->decdata_buffer == NULL) {
+ BACKEND->decdata_offset = 0;
+ BACKEND->decdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
+ BACKEND->decdata_buffer = malloc(BACKEND->decdata_length);
+ if(BACKEND->decdata_buffer == NULL) {
failf(data, "schannel: unable to allocate memory");
return CURLE_OUT_OF_MEMORY;
}
}
/* buffer to store previously received and encrypted data */
- if(connssl->encdata_buffer == NULL) {
- connssl->encdata_is_incomplete = false;
- connssl->encdata_offset = 0;
- connssl->encdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
- connssl->encdata_buffer = malloc(connssl->encdata_length);
- if(connssl->encdata_buffer == NULL) {
+ if(BACKEND->encdata_buffer == NULL) {
+ BACKEND->encdata_is_incomplete = false;
+ BACKEND->encdata_offset = 0;
+ BACKEND->encdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
+ BACKEND->encdata_buffer = malloc(BACKEND->encdata_length);
+ if(BACKEND->encdata_buffer == NULL) {
failf(data, "schannel: unable to allocate memory");
return CURLE_OUT_OF_MEMORY;
}
}
/* if we need a bigger buffer to read a full message, increase buffer now */
- if(connssl->encdata_length - connssl->encdata_offset <
+ if(BACKEND->encdata_length - BACKEND->encdata_offset <
CURL_SCHANNEL_BUFFER_FREE_SIZE) {
/* increase internal encrypted data buffer */
- reallocated_length = connssl->encdata_offset +
+ reallocated_length = BACKEND->encdata_offset +
CURL_SCHANNEL_BUFFER_FREE_SIZE;
- reallocated_buffer = realloc(connssl->encdata_buffer,
+ reallocated_buffer = realloc(BACKEND->encdata_buffer,
reallocated_length);
if(reallocated_buffer == NULL) {
@@ -505,8 +588,8 @@ schannel_connect_step2(struct connectdata *conn, int sockindex)
return CURLE_OUT_OF_MEMORY;
}
else {
- connssl->encdata_buffer = reallocated_buffer;
- connssl->encdata_length = reallocated_length;
+ BACKEND->encdata_buffer = reallocated_buffer;
+ BACKEND->encdata_length = reallocated_length;
}
}
@@ -514,10 +597,10 @@ schannel_connect_step2(struct connectdata *conn, int sockindex)
if(doread) {
/* read encrypted handshake data from socket */
result = Curl_read_plain(conn->sock[sockindex],
- (char *) (connssl->encdata_buffer +
- connssl->encdata_offset),
- connssl->encdata_length -
- connssl->encdata_offset,
+ (char *) (BACKEND->encdata_buffer +
+ BACKEND->encdata_offset),
+ BACKEND->encdata_length -
+ BACKEND->encdata_offset,
&nread);
if(result == CURLE_AGAIN) {
if(connssl->connecting_state != ssl_connect_2_writing)
@@ -533,17 +616,17 @@ schannel_connect_step2(struct connectdata *conn, int sockindex)
}
/* increase encrypted data buffer offset */
- connssl->encdata_offset += nread;
- connssl->encdata_is_incomplete = false;
+ BACKEND->encdata_offset += nread;
+ BACKEND->encdata_is_incomplete = false;
infof(data, "schannel: encrypted data got %zd\n", nread);
}
infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n",
- connssl->encdata_offset, connssl->encdata_length);
+ BACKEND->encdata_offset, BACKEND->encdata_length);
/* setup input buffers */
- InitSecBuffer(&inbuf[0], SECBUFFER_TOKEN, malloc(connssl->encdata_offset),
- curlx_uztoul(connssl->encdata_offset));
+ InitSecBuffer(&inbuf[0], SECBUFFER_TOKEN, malloc(BACKEND->encdata_offset),
+ curlx_uztoul(BACKEND->encdata_offset));
InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
InitSecBufferDesc(&inbuf_desc, inbuf, 2);
@@ -559,8 +642,8 @@ schannel_connect_step2(struct connectdata *conn, int sockindex)
}
/* copy received handshake data into input buffer */
- memcpy(inbuf[0].pvBuffer, connssl->encdata_buffer,
- connssl->encdata_offset);
+ memcpy(inbuf[0].pvBuffer, BACKEND->encdata_buffer,
+ BACKEND->encdata_offset);
host_name = Curl_convert_UTF8_to_tchar(hostname);
if(!host_name)
@@ -569,9 +652,9 @@ schannel_connect_step2(struct connectdata *conn, int sockindex)
/* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx
*/
sspi_status = s_pSecFn->InitializeSecurityContext(
- &connssl->cred->cred_handle, &connssl->ctxt->ctxt_handle,
- host_name, connssl->req_flags, 0, 0, &inbuf_desc, 0, NULL,
- &outbuf_desc, &connssl->ret_flags, &connssl->ctxt->time_stamp);
+ &BACKEND->cred->cred_handle, &BACKEND->ctxt->ctxt_handle,
+ host_name, BACKEND->req_flags, 0, 0, &inbuf_desc, 0, NULL,
+ &outbuf_desc, &BACKEND->ret_flags, &BACKEND->ctxt->time_stamp);
Curl_unicodefree(host_name);
@@ -580,7 +663,7 @@ schannel_connect_step2(struct connectdata *conn, int sockindex)
/* check if the handshake was incomplete */
if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) {
- connssl->encdata_is_incomplete = true;
+ BACKEND->encdata_is_incomplete = true;
connssl->connecting_state = ssl_connect_2_reading;
infof(data, "schannel: received incomplete message, need more data\n");
return CURLE_OK;
@@ -590,8 +673,8 @@ schannel_connect_step2(struct connectdata *conn, int sockindex)
the handshake without one. This will allow connections to servers which
request a client certificate but do not require it. */
if(sspi_status == SEC_I_INCOMPLETE_CREDENTIALS &&
- !(connssl->req_flags & ISC_REQ_USE_SUPPLIED_CREDS)) {
- connssl->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS;
+ !(BACKEND->req_flags & ISC_REQ_USE_SUPPLIED_CREDS)) {
+ BACKEND->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS;
connssl->connecting_state = ssl_connect_2_writing;
infof(data, "schannel: a client certificate has been requested\n");
return CURLE_OK;
@@ -631,7 +714,7 @@ schannel_connect_step2(struct connectdata *conn, int sockindex)
failf(data, "schannel: next InitializeSecurityContext failed: %s",
Curl_sspi_strerror(conn, sspi_status));
return sspi_status == SEC_E_UNTRUSTED_ROOT ?
- CURLE_SSL_CACERT_BADFILE : CURLE_SSL_CONNECT_ERROR;
+ CURLE_SSL_CACERT : CURLE_SSL_CONNECT_ERROR;
}
/* check if there was additional remaining encrypted data */
@@ -649,11 +732,11 @@ schannel_connect_step2(struct connectdata *conn, int sockindex)
*/
/* check if the remaining data is less than the total amount
and therefore begins after the already processed data */
- if(connssl->encdata_offset > inbuf[1].cbBuffer) {
- memmove(connssl->encdata_buffer,
- (connssl->encdata_buffer + connssl->encdata_offset) -
+ if(BACKEND->encdata_offset > inbuf[1].cbBuffer) {
+ memmove(BACKEND->encdata_buffer,
+ (BACKEND->encdata_buffer + BACKEND->encdata_offset) -
inbuf[1].cbBuffer, inbuf[1].cbBuffer);
- connssl->encdata_offset = inbuf[1].cbBuffer;
+ BACKEND->encdata_offset = inbuf[1].cbBuffer;
if(sspi_status == SEC_I_CONTINUE_NEEDED) {
doread = FALSE;
continue;
@@ -661,7 +744,7 @@ schannel_connect_step2(struct connectdata *conn, int sockindex)
}
}
else {
- connssl->encdata_offset = 0;
+ BACKEND->encdata_offset = 0;
}
break;
}
@@ -709,27 +792,27 @@ schannel_connect_step3(struct connectdata *conn, int sockindex)
infof(data, "schannel: SSL/TLS connection with %s port %hu (step 3/3)\n",
hostname, conn->remote_port);
- if(!connssl->cred)
+ if(!BACKEND->cred)
return CURLE_SSL_CONNECT_ERROR;
/* check if the required context attributes are met */
- if(connssl->ret_flags != connssl->req_flags) {
- if(!(connssl->ret_flags & ISC_RET_SEQUENCE_DETECT))
+ if(BACKEND->ret_flags != BACKEND->req_flags) {
+ if(!(BACKEND->ret_flags & ISC_RET_SEQUENCE_DETECT))
failf(data, "schannel: failed to setup sequence detection");
- if(!(connssl->ret_flags & ISC_RET_REPLAY_DETECT))
+ if(!(BACKEND->ret_flags & ISC_RET_REPLAY_DETECT))
failf(data, "schannel: failed to setup replay detection");
- if(!(connssl->ret_flags & ISC_RET_CONFIDENTIALITY))
+ if(!(BACKEND->ret_flags & ISC_RET_CONFIDENTIALITY))
failf(data, "schannel: failed to setup confidentiality");
- if(!(connssl->ret_flags & ISC_RET_ALLOCATED_MEMORY))
+ if(!(BACKEND->ret_flags & ISC_RET_ALLOCATED_MEMORY))
failf(data, "schannel: failed to setup memory allocation");
- if(!(connssl->ret_flags & ISC_RET_STREAM))
+ if(!(BACKEND->ret_flags & ISC_RET_STREAM))
failf(data, "schannel: failed to setup stream orientation");
return CURLE_SSL_CONNECT_ERROR;
}
#ifdef HAS_ALPN
- if(connssl->use_alpn) {
- sspi_status = s_pSecFn->QueryContextAttributes(&connssl->ctxt->ctxt_handle,
+ if(BACKEND->use_alpn) {
+ sspi_status = s_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle,
SECPKG_ATTR_APPLICATION_PROTOCOL, &alpn_result);
if(sspi_status != SEC_E_OK) {
@@ -771,7 +854,7 @@ schannel_connect_step3(struct connectdata *conn, int sockindex)
incache = !(Curl_ssl_getsessionid(conn, (void **)&old_cred, NULL,
sockindex));
if(incache) {
- if(old_cred != connssl->cred) {
+ if(old_cred != BACKEND->cred) {
infof(data, "schannel: old credential handle is stale, removing\n");
/* we're not taking old_cred ownership here, no refcount++ is needed */
Curl_ssl_delsessionid(conn, (void *)old_cred);
@@ -779,7 +862,7 @@ schannel_connect_step3(struct connectdata *conn, int sockindex)
}
}
if(!incache) {
- result = Curl_ssl_addsessionid(conn, (void *)connssl->cred,
+ result = Curl_ssl_addsessionid(conn, (void *)BACKEND->cred,
sizeof(struct curl_schannel_cred),
sockindex);
if(result) {
@@ -789,7 +872,7 @@ schannel_connect_step3(struct connectdata *conn, int sockindex)
}
else {
/* this cred session is now also referenced by sessionid cache */
- connssl->cred->refcount++;
+ BACKEND->cred->refcount++;
infof(data, "schannel: stored credential handle in session cache\n");
}
}
@@ -797,7 +880,7 @@ schannel_connect_step3(struct connectdata *conn, int sockindex)
}
if(data->set.ssl.certinfo) {
- sspi_status = s_pSecFn->QueryContextAttributes(&connssl->ctxt->ctxt_handle,
+ sspi_status = s_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle,
SECPKG_ATTR_REMOTE_CERT_CONTEXT, &ccert_context);
if((sspi_status != SEC_E_OK) || (ccert_context == NULL)) {
@@ -951,11 +1034,11 @@ schannel_send(struct connectdata *conn, int sockindex,
CURLcode result;
/* check if the maximum stream sizes were queried */
- if(connssl->stream_sizes.cbMaximumMessage == 0) {
+ if(BACKEND->stream_sizes.cbMaximumMessage == 0) {
sspi_status = s_pSecFn->QueryContextAttributes(
- &connssl->ctxt->ctxt_handle,
+ &BACKEND->ctxt->ctxt_handle,
SECPKG_ATTR_STREAM_SIZES,
- &connssl->stream_sizes);
+ &BACKEND->stream_sizes);
if(sspi_status != SEC_E_OK) {
*err = CURLE_SEND_ERROR;
return -1;
@@ -963,14 +1046,13 @@ schannel_send(struct connectdata *conn, int sockindex,
}
/* check if the buffer is longer than the maximum message length */
- if(len > connssl->stream_sizes.cbMaximumMessage) {
- *err = CURLE_SEND_ERROR;
- return -1;
+ if(len > BACKEND->stream_sizes.cbMaximumMessage) {
+ len = BACKEND->stream_sizes.cbMaximumMessage;
}
/* calculate the complete message length and allocate a buffer for it */
- data_len = connssl->stream_sizes.cbHeader + len +
- connssl->stream_sizes.cbTrailer;
+ data_len = BACKEND->stream_sizes.cbHeader + len +
+ BACKEND->stream_sizes.cbTrailer;
data = (unsigned char *) malloc(data_len);
if(data == NULL) {
*err = CURLE_OUT_OF_MEMORY;
@@ -979,12 +1061,12 @@ schannel_send(struct connectdata *conn, int sockindex,
/* setup output buffers (header, data, trailer, empty) */
InitSecBuffer(&outbuf[0], SECBUFFER_STREAM_HEADER,
- data, connssl->stream_sizes.cbHeader);
+ data, BACKEND->stream_sizes.cbHeader);
InitSecBuffer(&outbuf[1], SECBUFFER_DATA,
- data + connssl->stream_sizes.cbHeader, curlx_uztoul(len));
+ data + BACKEND->stream_sizes.cbHeader, curlx_uztoul(len));
InitSecBuffer(&outbuf[2], SECBUFFER_STREAM_TRAILER,
- data + connssl->stream_sizes.cbHeader + len,
- connssl->stream_sizes.cbTrailer);
+ data + BACKEND->stream_sizes.cbHeader + len,
+ BACKEND->stream_sizes.cbTrailer);
InitSecBuffer(&outbuf[3], SECBUFFER_EMPTY, NULL, 0);
InitSecBufferDesc(&outbuf_desc, outbuf, 4);
@@ -992,7 +1074,7 @@ schannel_send(struct connectdata *conn, int sockindex,
memcpy(outbuf[1].pvBuffer, buf, len);
/* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375390.aspx */
- sspi_status = s_pSecFn->EncryptMessage(&connssl->ctxt->ctxt_handle, 0,
+ sspi_status = s_pSecFn->EncryptMessage(&BACKEND->ctxt->ctxt_handle, 0,
&outbuf_desc, 0);
/* check if the message was encrypted */
@@ -1102,7 +1184,7 @@ schannel_recv(struct connectdata *conn, int sockindex,
size_t min_encdata_length = len + CURL_SCHANNEL_BUFFER_FREE_SIZE;
/****************************************************************************
- * Don't return or set connssl->recv_unrecoverable_err unless in the cleanup.
+ * Don't return or set BACKEND->recv_unrecoverable_err unless in the cleanup.
* The pattern for return error is set *err, optional infof, goto cleanup.
*
* Our priority is to always return as much decrypted data to the caller as
@@ -1114,16 +1196,16 @@ schannel_recv(struct connectdata *conn, int sockindex,
infof(data, "schannel: client wants to read %zu bytes\n", len);
*err = CURLE_OK;
- if(len && len <= connssl->decdata_offset) {
+ if(len && len <= BACKEND->decdata_offset) {
infof(data, "schannel: enough decrypted data is already available\n");
goto cleanup;
}
- else if(connssl->recv_unrecoverable_err) {
- *err = connssl->recv_unrecoverable_err;
+ else if(BACKEND->recv_unrecoverable_err) {
+ *err = BACKEND->recv_unrecoverable_err;
infof(data, "schannel: an unrecoverable error occurred in a prior call\n");
goto cleanup;
}
- else if(connssl->recv_sspi_close_notify) {
+ else if(BACKEND->recv_sspi_close_notify) {
/* once a server has indicated shutdown there is no more encrypted data */
infof(data, "schannel: server indicated shutdown in a prior call\n");
goto cleanup;
@@ -1135,17 +1217,17 @@ schannel_recv(struct connectdata *conn, int sockindex,
*/
; /* do nothing */
}
- else if(!connssl->recv_connection_closed) {
+ else if(!BACKEND->recv_connection_closed) {
/* increase enc buffer in order to fit the requested amount of data */
- size = connssl->encdata_length - connssl->encdata_offset;
+ size = BACKEND->encdata_length - BACKEND->encdata_offset;
if(size < CURL_SCHANNEL_BUFFER_FREE_SIZE ||
- connssl->encdata_length < min_encdata_length) {
- reallocated_length = connssl->encdata_offset +
+ BACKEND->encdata_length < min_encdata_length) {
+ reallocated_length = BACKEND->encdata_offset +
CURL_SCHANNEL_BUFFER_FREE_SIZE;
if(reallocated_length < min_encdata_length) {
reallocated_length = min_encdata_length;
}
- reallocated_buffer = realloc(connssl->encdata_buffer,
+ reallocated_buffer = realloc(BACKEND->encdata_buffer,
reallocated_length);
if(reallocated_buffer == NULL) {
*err = CURLE_OUT_OF_MEMORY;
@@ -1153,20 +1235,20 @@ schannel_recv(struct connectdata *conn, int sockindex,
goto cleanup;
}
- connssl->encdata_buffer = reallocated_buffer;
- connssl->encdata_length = reallocated_length;
- size = connssl->encdata_length - connssl->encdata_offset;
+ BACKEND->encdata_buffer = reallocated_buffer;
+ BACKEND->encdata_length = reallocated_length;
+ size = BACKEND->encdata_length - BACKEND->encdata_offset;
infof(data, "schannel: encdata_buffer resized %zu\n",
- connssl->encdata_length);
+ BACKEND->encdata_length);
}
infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n",
- connssl->encdata_offset, connssl->encdata_length);
+ BACKEND->encdata_offset, BACKEND->encdata_length);
/* read encrypted data from socket */
*err = Curl_read_plain(conn->sock[sockindex],
- (char *)(connssl->encdata_buffer +
- connssl->encdata_offset),
+ (char *)(BACKEND->encdata_buffer +
+ BACKEND->encdata_offset),
size, &nread);
if(*err) {
nread = -1;
@@ -1178,26 +1260,26 @@ schannel_recv(struct connectdata *conn, int sockindex,
infof(data, "schannel: Curl_read_plain returned error %d\n", *err);
}
else if(nread == 0) {
- connssl->recv_connection_closed = true;
+ BACKEND->recv_connection_closed = true;
infof(data, "schannel: server closed the connection\n");
}
else if(nread > 0) {
- connssl->encdata_offset += (size_t)nread;
- connssl->encdata_is_incomplete = false;
+ BACKEND->encdata_offset += (size_t)nread;
+ BACKEND->encdata_is_incomplete = false;
infof(data, "schannel: encrypted data got %zd\n", nread);
}
}
infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n",
- connssl->encdata_offset, connssl->encdata_length);
+ BACKEND->encdata_offset, BACKEND->encdata_length);
/* decrypt loop */
- while(connssl->encdata_offset > 0 && sspi_status == SEC_E_OK &&
- (!len || connssl->decdata_offset < len ||
- connssl->recv_connection_closed)) {
+ while(BACKEND->encdata_offset > 0 && sspi_status == SEC_E_OK &&
+ (!len || BACKEND->decdata_offset < len ||
+ BACKEND->recv_connection_closed)) {
/* prepare data buffer for DecryptMessage call */
- InitSecBuffer(&inbuf[0], SECBUFFER_DATA, connssl->encdata_buffer,
- curlx_uztoul(connssl->encdata_offset));
+ InitSecBuffer(&inbuf[0], SECBUFFER_DATA, BACKEND->encdata_buffer,
+ curlx_uztoul(BACKEND->encdata_offset));
/* we need 3 more empty input buffers for possible output */
InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
@@ -1207,7 +1289,7 @@ schannel_recv(struct connectdata *conn, int sockindex,
/* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375348.aspx
*/
- sspi_status = s_pSecFn->DecryptMessage(&connssl->ctxt->ctxt_handle,
+ sspi_status = s_pSecFn->DecryptMessage(&BACKEND->ctxt->ctxt_handle,
&inbuf_desc, 0, NULL);
/* check if everything went fine (server may want to renegotiate
@@ -1223,36 +1305,36 @@ schannel_recv(struct connectdata *conn, int sockindex,
/* increase buffer in order to fit the received amount of data */
size = inbuf[1].cbBuffer > CURL_SCHANNEL_BUFFER_FREE_SIZE ?
inbuf[1].cbBuffer : CURL_SCHANNEL_BUFFER_FREE_SIZE;
- if(connssl->decdata_length - connssl->decdata_offset < size ||
- connssl->decdata_length < len) {
+ if(BACKEND->decdata_length - BACKEND->decdata_offset < size ||
+ BACKEND->decdata_length < len) {
/* increase internal decrypted data buffer */
- reallocated_length = connssl->decdata_offset + size;
+ reallocated_length = BACKEND->decdata_offset + size;
/* make sure that the requested amount of data fits */
if(reallocated_length < len) {
reallocated_length = len;
}
- reallocated_buffer = realloc(connssl->decdata_buffer,
+ reallocated_buffer = realloc(BACKEND->decdata_buffer,
reallocated_length);
if(reallocated_buffer == NULL) {
*err = CURLE_OUT_OF_MEMORY;
failf(data, "schannel: unable to re-allocate memory");
goto cleanup;
}
- connssl->decdata_buffer = reallocated_buffer;
- connssl->decdata_length = reallocated_length;
+ BACKEND->decdata_buffer = reallocated_buffer;
+ BACKEND->decdata_length = reallocated_length;
}
/* copy decrypted data to internal buffer */
size = inbuf[1].cbBuffer;
if(size) {
- memcpy(connssl->decdata_buffer + connssl->decdata_offset,
+ memcpy(BACKEND->decdata_buffer + BACKEND->decdata_offset,
inbuf[1].pvBuffer, size);
- connssl->decdata_offset += size;
+ BACKEND->decdata_offset += size;
}
infof(data, "schannel: decrypted data added: %zu\n", size);
infof(data, "schannel: decrypted data cached: offset %zu length %zu\n",
- connssl->decdata_offset, connssl->decdata_length);
+ BACKEND->decdata_offset, BACKEND->decdata_length);
}
/* check for remaining encrypted data */
@@ -1263,21 +1345,21 @@ schannel_recv(struct connectdata *conn, int sockindex,
/* check if the remaining data is less than the total amount
* and therefore begins after the already processed data
*/
- if(connssl->encdata_offset > inbuf[3].cbBuffer) {
+ if(BACKEND->encdata_offset > inbuf[3].cbBuffer) {
/* move remaining encrypted data forward to the beginning of
buffer */
- memmove(connssl->encdata_buffer,
- (connssl->encdata_buffer + connssl->encdata_offset) -
+ memmove(BACKEND->encdata_buffer,
+ (BACKEND->encdata_buffer + BACKEND->encdata_offset) -
inbuf[3].cbBuffer, inbuf[3].cbBuffer);
- connssl->encdata_offset = inbuf[3].cbBuffer;
+ BACKEND->encdata_offset = inbuf[3].cbBuffer;
}
infof(data, "schannel: encrypted data cached: offset %zu length %zu\n",
- connssl->encdata_offset, connssl->encdata_length);
+ BACKEND->encdata_offset, BACKEND->encdata_length);
}
else {
/* reset encrypted buffer offset, because there is no data remaining */
- connssl->encdata_offset = 0;
+ BACKEND->encdata_offset = 0;
}
/* check if server wants to renegotiate the connection context */
@@ -1287,7 +1369,7 @@ schannel_recv(struct connectdata *conn, int sockindex,
infof(data, "schannel: can't renogotiate, an error is pending\n");
goto cleanup;
}
- if(connssl->encdata_offset) {
+ if(BACKEND->encdata_offset) {
*err = CURLE_RECV_ERROR;
infof(data, "schannel: can't renogotiate, "
"encrypted data available\n");
@@ -1311,16 +1393,16 @@ schannel_recv(struct connectdata *conn, int sockindex,
else if(sspi_status == SEC_I_CONTEXT_EXPIRED) {
/* In Windows 2000 SEC_I_CONTEXT_EXPIRED (close_notify) is not
returned so we have to work around that in cleanup. */
- connssl->recv_sspi_close_notify = true;
- if(!connssl->recv_connection_closed) {
- connssl->recv_connection_closed = true;
+ BACKEND->recv_sspi_close_notify = true;
+ if(!BACKEND->recv_connection_closed) {
+ BACKEND->recv_connection_closed = true;
infof(data, "schannel: server closed the connection\n");
}
goto cleanup;
}
}
else if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) {
- connssl->encdata_is_incomplete = true;
+ BACKEND->encdata_is_incomplete = true;
if(!*err)
*err = CURLE_AGAIN;
infof(data, "schannel: failed to decrypt data, need more data\n");
@@ -1335,10 +1417,10 @@ schannel_recv(struct connectdata *conn, int sockindex,
}
infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n",
- connssl->encdata_offset, connssl->encdata_length);
+ BACKEND->encdata_offset, BACKEND->encdata_length);
infof(data, "schannel: decrypted data buffer: offset %zu length %zu\n",
- connssl->decdata_offset, connssl->decdata_length);
+ BACKEND->decdata_offset, BACKEND->decdata_length);
cleanup:
/* Warning- there is no guarantee the encdata state is valid at this point */
@@ -1352,13 +1434,13 @@ cleanup:
return close_notify. In that case if the connection was closed we assume it
was graceful (close_notify) since there doesn't seem to be a way to tell.
*/
- if(len && !connssl->decdata_offset && connssl->recv_connection_closed &&
- !connssl->recv_sspi_close_notify) {
+ if(len && !BACKEND->decdata_offset && BACKEND->recv_connection_closed &&
+ !BACKEND->recv_sspi_close_notify) {
bool isWin2k = Curl_verify_windows_version(5, 0, PLATFORM_WINNT,
VERSION_EQUAL);
if(isWin2k && sspi_status == SEC_E_OK)
- connssl->recv_sspi_close_notify = true;
+ BACKEND->recv_sspi_close_notify = true;
else {
*err = CURLE_RECV_ERROR;
infof(data, "schannel: server closed abruptly (missing close_notify)\n");
@@ -1367,23 +1449,23 @@ cleanup:
/* Any error other than CURLE_AGAIN is an unrecoverable error. */
if(*err && *err != CURLE_AGAIN)
- connssl->recv_unrecoverable_err = *err;
+ BACKEND->recv_unrecoverable_err = *err;
- size = len < connssl->decdata_offset ? len : connssl->decdata_offset;
+ size = len < BACKEND->decdata_offset ? len : BACKEND->decdata_offset;
if(size) {
- memcpy(buf, connssl->decdata_buffer, size);
- memmove(connssl->decdata_buffer, connssl->decdata_buffer + size,
- connssl->decdata_offset - size);
- connssl->decdata_offset -= size;
+ memcpy(buf, BACKEND->decdata_buffer, size);
+ memmove(BACKEND->decdata_buffer, BACKEND->decdata_buffer + size,
+ BACKEND->decdata_offset - size);
+ BACKEND->decdata_offset -= size;
infof(data, "schannel: decrypted data returned %zu\n", size);
infof(data, "schannel: decrypted data buffer: offset %zu length %zu\n",
- connssl->decdata_offset, connssl->decdata_length);
+ BACKEND->decdata_offset, BACKEND->decdata_length);
*err = CURLE_OK;
return (ssize_t)size;
}
- if(!*err && !connssl->recv_connection_closed)
+ if(!*err && !BACKEND->recv_connection_closed)
*err = CURLE_AGAIN;
/* It's debatable what to return when !len. We could return whatever error we
@@ -1395,15 +1477,13 @@ cleanup:
return *err ? -1 : 0;
}
-CURLcode
-Curl_schannel_connect_nonblocking(struct connectdata *conn, int sockindex,
- bool *done)
+static CURLcode Curl_schannel_connect_nonblocking(struct connectdata *conn,
+ int sockindex, bool *done)
{
return schannel_connect_common(conn, sockindex, TRUE, done);
}
-CURLcode
-Curl_schannel_connect(struct connectdata *conn, int sockindex)
+static CURLcode Curl_schannel_connect(struct connectdata *conn, int sockindex)
{
CURLcode result;
bool done = FALSE;
@@ -1417,25 +1497,38 @@ Curl_schannel_connect(struct connectdata *conn, int sockindex)
return CURLE_OK;
}
-bool Curl_schannel_data_pending(const struct connectdata *conn, int sockindex)
+static bool Curl_schannel_data_pending(const struct connectdata *conn,
+ int sockindex)
{
const struct ssl_connect_data *connssl = &conn->ssl[sockindex];
if(connssl->use) /* SSL/TLS is in use */
- return (connssl->decdata_offset > 0 ||
- (connssl->encdata_offset > 0 && !connssl->encdata_is_incomplete));
+ return (BACKEND->decdata_offset > 0 ||
+ (BACKEND->encdata_offset > 0 && !BACKEND->encdata_is_incomplete));
else
return FALSE;
}
-void Curl_schannel_close(struct connectdata *conn, int sockindex)
+static void Curl_schannel_close(struct connectdata *conn, int sockindex)
{
if(conn->ssl[sockindex].use)
/* if the SSL/TLS channel hasn't been shut down yet, do that now. */
Curl_ssl_shutdown(conn, sockindex);
}
-int Curl_schannel_shutdown(struct connectdata *conn, int sockindex)
+static void Curl_schannel_session_free(void *ptr)
+{
+ /* this is expected to be called under sessionid lock */
+ struct curl_schannel_cred *cred = ptr;
+
+ cred->refcount--;
+ if(cred->refcount == 0) {
+ s_pSecFn->FreeCredentialsHandle(&cred->cred_handle);
+ Curl_safefree(cred);
+ }
+}
+
+static int Curl_schannel_shutdown(struct connectdata *conn, int sockindex)
{
/* See https://msdn.microsoft.com/en-us/library/windows/desktop/aa380138.aspx
* Shutting Down an Schannel Connection
@@ -1448,7 +1541,7 @@ int Curl_schannel_shutdown(struct connectdata *conn, int sockindex)
infof(data, "schannel: shutting down SSL/TLS connection with %s port %hu\n",
hostname, conn->remote_port);
- if(connssl->cred && connssl->ctxt) {
+ if(BACKEND->cred && BACKEND->ctxt) {
SecBufferDesc BuffDesc;
SecBuffer Buffer;
SECURITY_STATUS sspi_status;
@@ -1461,7 +1554,7 @@ int Curl_schannel_shutdown(struct connectdata *conn, int sockindex)
InitSecBuffer(&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof(dwshut));
InitSecBufferDesc(&BuffDesc, &Buffer, 1);
- sspi_status = s_pSecFn->ApplyControlToken(&connssl->ctxt->ctxt_handle,
+ sspi_status = s_pSecFn->ApplyControlToken(&BACKEND->ctxt->ctxt_handle,
&BuffDesc);
if(sspi_status != SEC_E_OK)
@@ -1477,18 +1570,18 @@ int Curl_schannel_shutdown(struct connectdata *conn, int sockindex)
InitSecBufferDesc(&outbuf_desc, &outbuf, 1);
sspi_status = s_pSecFn->InitializeSecurityContext(
- &connssl->cred->cred_handle,
- &connssl->ctxt->ctxt_handle,
+ &BACKEND->cred->cred_handle,
+ &BACKEND->ctxt->ctxt_handle,
host_name,
- connssl->req_flags,
+ BACKEND->req_flags,
0,
0,
NULL,
0,
- &connssl->ctxt->ctxt_handle,
+ &BACKEND->ctxt->ctxt_handle,
&outbuf_desc,
- &connssl->ret_flags,
- &connssl->ctxt->time_stamp);
+ &BACKEND->ret_flags,
+ &BACKEND->ctxt->time_stamp);
Curl_unicodefree(host_name);
@@ -1507,71 +1600,62 @@ int Curl_schannel_shutdown(struct connectdata *conn, int sockindex)
}
/* free SSPI Schannel API security context handle */
- if(connssl->ctxt) {
+ if(BACKEND->ctxt) {
infof(data, "schannel: clear security context handle\n");
- s_pSecFn->DeleteSecurityContext(&connssl->ctxt->ctxt_handle);
- Curl_safefree(connssl->ctxt);
+ s_pSecFn->DeleteSecurityContext(&BACKEND->ctxt->ctxt_handle);
+ Curl_safefree(BACKEND->ctxt);
}
/* free SSPI Schannel API credential handle */
- if(connssl->cred) {
+ if(BACKEND->cred) {
Curl_ssl_sessionid_lock(conn);
- Curl_schannel_session_free(connssl->cred);
+ Curl_schannel_session_free(BACKEND->cred);
Curl_ssl_sessionid_unlock(conn);
- connssl->cred = NULL;
+ BACKEND->cred = NULL;
}
/* free internal buffer for received encrypted data */
- if(connssl->encdata_buffer != NULL) {
- Curl_safefree(connssl->encdata_buffer);
- connssl->encdata_length = 0;
- connssl->encdata_offset = 0;
- connssl->encdata_is_incomplete = false;
+ if(BACKEND->encdata_buffer != NULL) {
+ Curl_safefree(BACKEND->encdata_buffer);
+ BACKEND->encdata_length = 0;
+ BACKEND->encdata_offset = 0;
+ BACKEND->encdata_is_incomplete = false;
}
/* free internal buffer for received decrypted data */
- if(connssl->decdata_buffer != NULL) {
- Curl_safefree(connssl->decdata_buffer);
- connssl->decdata_length = 0;
- connssl->decdata_offset = 0;
+ if(BACKEND->decdata_buffer != NULL) {
+ Curl_safefree(BACKEND->decdata_buffer);
+ BACKEND->decdata_length = 0;
+ BACKEND->decdata_offset = 0;
}
return CURLE_OK;
}
-void Curl_schannel_session_free(void *ptr)
-{
- /* this is expected to be called under sessionid lock */
- struct curl_schannel_cred *cred = ptr;
-
- cred->refcount--;
- if(cred->refcount == 0) {
- s_pSecFn->FreeCredentialsHandle(&cred->cred_handle);
- Curl_safefree(cred);
- }
-}
-
-int Curl_schannel_init(void)
+static int Curl_schannel_init(void)
{
return (Curl_sspi_global_init() == CURLE_OK ? 1 : 0);
}
-void Curl_schannel_cleanup(void)
+static void Curl_schannel_cleanup(void)
{
Curl_sspi_global_cleanup();
}
-size_t Curl_schannel_version(char *buffer, size_t size)
+static size_t Curl_schannel_version(char *buffer, size_t size)
{
size = snprintf(buffer, size, "WinSSL");
return size;
}
-CURLcode Curl_schannel_random(unsigned char *entropy, size_t length)
+static CURLcode Curl_schannel_random(struct Curl_easy *data UNUSED_PARAM,
+ unsigned char *entropy, size_t length)
{
HCRYPTPROV hCryptProv = 0;
+ (void)data;
+
if(!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
return CURLE_FAILED_INIT;
@@ -1598,7 +1682,7 @@ static CURLcode verify_certificate(struct connectdata *conn, int sockindex)
conn->http_proxy.host.name :
conn->host.name;
- status = s_pSecFn->QueryContextAttributes(&connssl->ctxt->ctxt_handle,
+ status = s_pSecFn->QueryContextAttributes(&BACKEND->ctxt->ctxt_handle,
SECPKG_ATTR_REMOTE_CERT_CONTEXT,
&pCertContextServer);
@@ -1725,4 +1809,44 @@ static CURLcode verify_certificate(struct connectdata *conn, int sockindex)
}
#endif /* _WIN32_WCE */
+static void *Curl_schannel_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info UNUSED_PARAM)
+{
+ (void)info;
+ return &BACKEND->ctxt->ctxt_handle;
+}
+
+const struct Curl_ssl Curl_ssl_schannel = {
+ { CURLSSLBACKEND_SCHANNEL, "schannel" }, /* info */
+
+ 0, /* have_ca_path */
+ 1, /* have_certinfo */
+ 0, /* have_pinnedpubkey */
+ 0, /* have_ssl_ctx */
+ 0, /* support_https_proxy */
+
+ sizeof(struct ssl_backend_data),
+
+ Curl_schannel_init, /* init */
+ Curl_schannel_cleanup, /* cleanup */
+ Curl_schannel_version, /* version */
+ Curl_none_check_cxn, /* check_cxn */
+ Curl_schannel_shutdown, /* shutdown */
+ Curl_schannel_data_pending, /* data_pending */
+ Curl_schannel_random, /* random */
+ Curl_none_cert_status_request, /* cert_status_request */
+ Curl_schannel_connect, /* connect */
+ Curl_schannel_connect_nonblocking, /* connect_nonblocking */
+ Curl_schannel_get_internals, /* get_internals */
+ Curl_schannel_close, /* close */
+ Curl_none_close_all, /* close_all */
+ Curl_schannel_session_free, /* session_free */
+ Curl_none_set_engine, /* set_engine */
+ Curl_none_set_engine_default, /* set_engine_default */
+ Curl_none_engines_list, /* engines_list */
+ Curl_none_false_start, /* false_start */
+ Curl_none_md5sum, /* md5sum */
+ NULL /* sha256sum */
+};
+
#endif /* USE_SCHANNEL */
diff --git a/Utilities/cmcurl/lib/vtls/schannel.h b/Utilities/cmcurl/lib/vtls/schannel.h
index 8627c63c9..932103da4 100644
--- a/Utilities/cmcurl/lib/vtls/schannel.h
+++ b/Utilities/cmcurl/lib/vtls/schannel.h
@@ -28,94 +28,7 @@
#include "urldata.h"
-#ifndef UNISP_NAME_A
-#define UNISP_NAME_A "Microsoft Unified Security Protocol Provider"
-#endif
-
-#ifndef UNISP_NAME_W
-#define UNISP_NAME_W L"Microsoft Unified Security Protocol Provider"
-#endif
-
-#ifndef UNISP_NAME
-#ifdef UNICODE
-#define UNISP_NAME UNISP_NAME_W
-#else
-#define UNISP_NAME UNISP_NAME_A
-#endif
-#endif
-
-#ifndef SP_PROT_SSL2_CLIENT
-#define SP_PROT_SSL2_CLIENT 0x00000008
-#endif
-
-#ifndef SP_PROT_SSL3_CLIENT
-#define SP_PROT_SSL3_CLIENT 0x00000008
-#endif
-
-#ifndef SP_PROT_TLS1_CLIENT
-#define SP_PROT_TLS1_CLIENT 0x00000080
-#endif
-
-#ifndef SP_PROT_TLS1_0_CLIENT
-#define SP_PROT_TLS1_0_CLIENT SP_PROT_TLS1_CLIENT
-#endif
-
-#ifndef SP_PROT_TLS1_1_CLIENT
-#define SP_PROT_TLS1_1_CLIENT 0x00000200
-#endif
-
-#ifndef SP_PROT_TLS1_2_CLIENT
-#define SP_PROT_TLS1_2_CLIENT 0x00000800
-#endif
-
-#ifndef SECBUFFER_ALERT
-#define SECBUFFER_ALERT 17
-#endif
-
-/* Both schannel buffer sizes must be > 0 */
-#define CURL_SCHANNEL_BUFFER_INIT_SIZE 4096
-#define CURL_SCHANNEL_BUFFER_FREE_SIZE 1024
-
-
-CURLcode Curl_schannel_connect(struct connectdata *conn, int sockindex);
-
-CURLcode Curl_schannel_connect_nonblocking(struct connectdata *conn,
- int sockindex,
- bool *done);
-
-bool Curl_schannel_data_pending(const struct connectdata *conn, int sockindex);
-void Curl_schannel_close(struct connectdata *conn, int sockindex);
-int Curl_schannel_shutdown(struct connectdata *conn, int sockindex);
-void Curl_schannel_session_free(void *ptr);
-
-int Curl_schannel_init(void);
-void Curl_schannel_cleanup(void);
-size_t Curl_schannel_version(char *buffer, size_t size);
-
-CURLcode Curl_schannel_random(unsigned char *entropy, size_t length);
-
-/* Set the API backend definition to Schannel */
-#define CURL_SSL_BACKEND CURLSSLBACKEND_SCHANNEL
-
-/* this backend supports CURLOPT_CERTINFO */
-#define have_curlssl_certinfo 1
-
-/* API setup for Schannel */
-#define curlssl_init Curl_schannel_init
-#define curlssl_cleanup Curl_schannel_cleanup
-#define curlssl_connect Curl_schannel_connect
-#define curlssl_connect_nonblocking Curl_schannel_connect_nonblocking
-#define curlssl_session_free Curl_schannel_session_free
-#define curlssl_close_all(x) ((void)x)
-#define curlssl_close Curl_schannel_close
-#define curlssl_shutdown Curl_schannel_shutdown
-#define curlssl_set_engine(x,y) ((void)x, (void)y, CURLE_NOT_BUILT_IN)
-#define curlssl_set_engine_default(x) ((void)x, CURLE_NOT_BUILT_IN)
-#define curlssl_engines_list(x) ((void)x, (struct curl_slist *)NULL)
-#define curlssl_version Curl_schannel_version
-#define curlssl_check_cxn(x) ((void)x, -1)
-#define curlssl_data_pending Curl_schannel_data_pending
-#define curlssl_random(x,y,z) ((void)x, Curl_schannel_random(y,z))
+extern const struct Curl_ssl Curl_ssl_schannel;
#endif /* USE_SCHANNEL */
#endif /* HEADER_CURL_SCHANNEL_H */
diff --git a/Utilities/cmcurl/lib/vtls/vtls.c b/Utilities/cmcurl/lib/vtls/vtls.c
index d5d0971c4..bb8fda419 100644
--- a/Utilities/cmcurl/lib/vtls/vtls.c
+++ b/Utilities/cmcurl/lib/vtls/vtls.c
@@ -28,17 +28,9 @@
to any specific SSL-layer.
Curl_ssl_ - prefix for generic ones
- Curl_ossl_ - prefix for OpenSSL ones
- Curl_gtls_ - prefix for GnuTLS ones
- Curl_nss_ - prefix for NSS ones
- Curl_gskit_ - prefix for GSKit ones
- Curl_polarssl_ - prefix for PolarSSL ones
- Curl_cyassl_ - prefix for CyaSSL ones
- Curl_schannel_ - prefix for Schannel SSPI ones
- Curl_darwinssl_ - prefix for SecureTransport (Darwin) ones
-
- Note that this source code uses curlssl_* functions, and they are all
- defines/macros #defined by the lib-specific header files.
+
+ Note that this source code uses the functions of the configured SSL
+ backend via the global Curl_ssl instance.
"SSL/TLS Strong Encryption: An Introduction"
https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html
@@ -98,9 +90,12 @@ Curl_ssl_config_matches(struct ssl_primary_config* data,
(data->version_max == needle->version_max) &&
(data->verifypeer == needle->verifypeer) &&
(data->verifyhost == needle->verifyhost) &&
+ (data->verifystatus == needle->verifystatus) &&
Curl_safe_strcasecompare(data->CApath, needle->CApath) &&
Curl_safe_strcasecompare(data->CAfile, needle->CAfile) &&
Curl_safe_strcasecompare(data->clientcert, needle->clientcert) &&
+ Curl_safe_strcasecompare(data->random_file, needle->random_file) &&
+ Curl_safe_strcasecompare(data->egdsocket, needle->egdsocket) &&
Curl_safe_strcasecompare(data->cipher_list, needle->cipher_list))
return TRUE;
@@ -111,42 +106,51 @@ bool
Curl_clone_primary_ssl_config(struct ssl_primary_config *source,
struct ssl_primary_config *dest)
{
- dest->verifyhost = source->verifyhost;
- dest->verifypeer = source->verifypeer;
dest->version = source->version;
dest->version_max = source->version_max;
+ dest->verifypeer = source->verifypeer;
+ dest->verifyhost = source->verifyhost;
+ dest->verifystatus = source->verifystatus;
+ dest->sessionid = source->sessionid;
- CLONE_STRING(CAfile);
CLONE_STRING(CApath);
- CLONE_STRING(cipher_list);
- CLONE_STRING(egdsocket);
- CLONE_STRING(random_file);
+ CLONE_STRING(CAfile);
CLONE_STRING(clientcert);
+ CLONE_STRING(random_file);
+ CLONE_STRING(egdsocket);
+ CLONE_STRING(cipher_list);
- /* Disable dest sessionid cache if a client cert is used, CVE-2016-5419. */
- dest->sessionid = (dest->clientcert ? false : source->sessionid);
return TRUE;
}
void Curl_free_primary_ssl_config(struct ssl_primary_config* sslc)
{
- Curl_safefree(sslc->CAfile);
Curl_safefree(sslc->CApath);
- Curl_safefree(sslc->cipher_list);
- Curl_safefree(sslc->egdsocket);
- Curl_safefree(sslc->random_file);
+ Curl_safefree(sslc->CAfile);
Curl_safefree(sslc->clientcert);
+ Curl_safefree(sslc->random_file);
+ Curl_safefree(sslc->egdsocket);
+ Curl_safefree(sslc->cipher_list);
}
+#ifdef USE_SSL
+static int multissl_init(const struct Curl_ssl *backend);
+#endif
+
int Curl_ssl_backend(void)
{
- return (int)CURL_SSL_BACKEND;
+#ifdef USE_SSL
+ multissl_init(NULL);
+ return Curl_ssl->info.id;
+#else
+ return (int)CURLSSLBACKEND_NONE;
+#endif
}
#ifdef USE_SSL
/* "global" init done? */
-static bool init_ssl=FALSE;
+static bool init_ssl = FALSE;
/**
* Global SSL init
@@ -161,7 +165,7 @@ int Curl_ssl_init(void)
return 1;
init_ssl = TRUE; /* never again */
- return curlssl_init();
+ return Curl_ssl->init();
}
@@ -170,7 +174,7 @@ void Curl_ssl_cleanup(void)
{
if(init_ssl) {
/* only cleanup if we did a previous init */
- curlssl_cleanup();
+ Curl_ssl->cleanup();
init_ssl = FALSE;
}
}
@@ -205,12 +209,20 @@ ssl_connect_init_proxy(struct connectdata *conn, int sockindex)
DEBUGASSERT(conn->bits.proxy_ssl_connected[sockindex]);
if(ssl_connection_complete == conn->ssl[sockindex].state &&
!conn->proxy_ssl[sockindex].use) {
-#if defined(HTTPS_PROXY_SUPPORT)
+ struct ssl_backend_data *pbdata;
+
+ if(!Curl_ssl->support_https_proxy)
+ return CURLE_NOT_BUILT_IN;
+
+ /* The pointers to the ssl backend data, which is opaque here, are swapped
+ rather than move the contents. */
+ pbdata = conn->proxy_ssl[sockindex].backend;
conn->proxy_ssl[sockindex] = conn->ssl[sockindex];
+
memset(&conn->ssl[sockindex], 0, sizeof(conn->ssl[sockindex]));
-#else
- return CURLE_NOT_BUILT_IN;
-#endif
+ memset(pbdata, 0, Curl_ssl->sizeof_ssl_backend_data);
+
+ conn->ssl[sockindex].backend = pbdata;
}
return CURLE_OK;
}
@@ -233,7 +245,7 @@ Curl_ssl_connect(struct connectdata *conn, int sockindex)
conn->ssl[sockindex].use = TRUE;
conn->ssl[sockindex].state = ssl_connection_negotiating;
- result = curlssl_connect(conn, sockindex);
+ result = Curl_ssl->connect(conn, sockindex);
if(!result)
Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
@@ -257,12 +269,7 @@ Curl_ssl_connect_nonblocking(struct connectdata *conn, int sockindex,
/* mark this is being ssl requested from here on. */
conn->ssl[sockindex].use = TRUE;
-#ifdef curlssl_connect_nonblocking
- result = curlssl_connect_nonblocking(conn, sockindex, done);
-#else
- *done = TRUE; /* fallback to BLOCKING */
- result = curlssl_connect(conn, sockindex);
-#endif /* non-blocking connect support */
+ result = Curl_ssl->connect_nonblocking(conn, sockindex, done);
if(!result && *done)
Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
return result;
@@ -361,7 +368,7 @@ void Curl_ssl_kill_session(struct curl_ssl_session *session)
/* defensive check */
/* free the ID the SSL-layer specific way */
- curlssl_session_free(session->sessionid);
+ Curl_ssl->session_free(session->sessionid);
session->sessionid = NULL;
session->age = 0; /* fresh */
@@ -379,7 +386,7 @@ void Curl_ssl_kill_session(struct curl_ssl_session *session)
void Curl_ssl_delsessionid(struct connectdata *conn, void *ssl_sessionid)
{
size_t i;
- struct Curl_easy *data=conn->data;
+ struct Curl_easy *data = conn->data;
for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) {
struct curl_ssl_session *check = &data->state.session[i];
@@ -403,9 +410,9 @@ CURLcode Curl_ssl_addsessionid(struct connectdata *conn,
int sockindex)
{
size_t i;
- struct Curl_easy *data=conn->data; /* the mother of all structs */
+ struct Curl_easy *data = conn->data; /* the mother of all structs */
struct curl_ssl_session *store = &data->state.session[0];
- long oldest_age=data->state.session[0].age; /* zero if unused */
+ long oldest_age = data->state.session[0].age; /* zero if unused */
char *clone_host;
char *clone_conn_to_host;
int conn_to_port;
@@ -499,7 +506,7 @@ void Curl_ssl_close_all(struct Curl_easy *data)
Curl_safefree(data->state.session);
}
- curlssl_close_all(data);
+ Curl_ssl->close_all(data);
}
#if defined(USE_OPENSSL) || defined(USE_GNUTLS) || defined(USE_SCHANNEL) || \
@@ -542,12 +549,12 @@ int Curl_ssl_getsock(struct connectdata *conn,
void Curl_ssl_close(struct connectdata *conn, int sockindex)
{
DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
- curlssl_close(conn, sockindex);
+ Curl_ssl->close(conn, sockindex);
}
CURLcode Curl_ssl_shutdown(struct connectdata *conn, int sockindex)
{
- if(curlssl_shutdown(conn, sockindex))
+ if(Curl_ssl->shutdown(conn, sockindex))
return CURLE_SSL_SHUTDOWN_FAILED;
conn->ssl[sockindex].use = FALSE; /* get back to ordinary socket usage */
@@ -563,20 +570,20 @@ CURLcode Curl_ssl_shutdown(struct connectdata *conn, int sockindex)
*/
CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine)
{
- return curlssl_set_engine(data, engine);
+ return Curl_ssl->set_engine(data, engine);
}
/* Selects the default SSL crypto engine
*/
CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data)
{
- return curlssl_set_engine_default(data);
+ return Curl_ssl->set_engine_default(data);
}
/* Return list of OpenSSL crypto engine names. */
struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data)
{
- return curlssl_engines_list(data);
+ return Curl_ssl->engines_list(data);
}
/*
@@ -602,9 +609,15 @@ CURLcode Curl_ssl_initsessions(struct Curl_easy *data, size_t amount)
return CURLE_OK;
}
+static size_t Curl_multissl_version(char *buffer, size_t size);
+
size_t Curl_ssl_version(char *buffer, size_t size)
{
- return curlssl_version(buffer, size);
+#ifdef CURL_WITH_MULTI_SSL
+ return Curl_multissl_version(buffer, size);
+#else
+ return Curl_ssl->version(buffer, size);
+#endif
}
/*
@@ -617,13 +630,13 @@ size_t Curl_ssl_version(char *buffer, size_t size)
*/
int Curl_ssl_check_cxn(struct connectdata *conn)
{
- return curlssl_check_cxn(conn);
+ return Curl_ssl->check_cxn(conn);
}
bool Curl_ssl_data_pending(const struct connectdata *conn,
int connindex)
{
- return curlssl_data_pending(conn, connindex);
+ return Curl_ssl->data_pending(conn, connindex);
}
void Curl_ssl_free_certinfo(struct Curl_easy *data)
@@ -633,7 +646,7 @@ void Curl_ssl_free_certinfo(struct Curl_easy *data)
if(ci->num_of_certs) {
/* free all individual lists used */
- for(i=0; i<ci->num_of_certs; i++) {
+ for(i = 0; i<ci->num_of_certs; i++) {
curl_slist_free_all(ci->certinfo[i]);
ci->certinfo[i] = NULL;
}
@@ -687,7 +700,7 @@ CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data,
snprintf(output, outlen, "%s:", label);
/* memcpy the value (it might not be zero terminated) */
- memcpy(&output[labellen+1], value, valuelen);
+ memcpy(&output[labellen + 1], value, valuelen);
/* zero terminate the output */
output[labellen + 1 + valuelen] = 0;
@@ -721,7 +734,7 @@ CURLcode Curl_ssl_random(struct Curl_easy *data,
unsigned char *entropy,
size_t length)
{
- return curlssl_random(data, entropy, length);
+ return Curl_ssl->random(data, entropy, length);
}
/*
@@ -796,12 +809,10 @@ CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data,
size_t size, pem_len;
CURLcode pem_read;
CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
-#ifdef curlssl_sha256sum
CURLcode encode;
size_t encodedlen, pinkeylen;
char *encoded, *pinkeycopy, *begin_pos, *end_pos;
unsigned char *sha256sumdigest = NULL;
-#endif
/* if a path wasn't specified, don't pin */
if(!pinnedpubkey)
@@ -811,15 +822,20 @@ CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data,
/* only do this if pinnedpubkey starts with "sha256//", length 8 */
if(strncmp(pinnedpubkey, "sha256//", 8) == 0) {
-#ifdef curlssl_sha256sum
+ if(!Curl_ssl->sha256sum) {
+ /* without sha256 support, this cannot match */
+ return result;
+ }
+
/* compute sha256sum of public key */
- sha256sumdigest = malloc(SHA256_DIGEST_LENGTH);
+ sha256sumdigest = malloc(CURL_SHA256_DIGEST_LENGTH);
if(!sha256sumdigest)
return CURLE_OUT_OF_MEMORY;
- curlssl_sha256sum(pubkey, pubkeylen,
- sha256sumdigest, SHA256_DIGEST_LENGTH);
+ Curl_ssl->sha256sum(pubkey, pubkeylen,
+ sha256sumdigest, CURL_SHA256_DIGEST_LENGTH);
encode = Curl_base64_encode(data, (char *)sha256sumdigest,
- SHA256_DIGEST_LENGTH, &encoded, &encodedlen);
+ CURL_SHA256_DIGEST_LENGTH, &encoded,
+ &encodedlen);
Curl_safefree(sha256sumdigest);
if(encode)
@@ -864,10 +880,6 @@ CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data,
} while(end_pos && begin_pos);
Curl_safefree(encoded);
Curl_safefree(pinkeycopy);
-#else
- /* without sha256 support, this cannot match */
- (void)data;
-#endif
return result;
}
@@ -943,20 +955,7 @@ CURLcode Curl_ssl_md5sum(unsigned char *tmp, /* input */
unsigned char *md5sum, /* output */
size_t md5len)
{
-#ifdef curlssl_md5sum
- curlssl_md5sum(tmp, tmplen, md5sum, md5len);
-#else
- MD5_context *MD5pw;
-
- (void) md5len;
-
- MD5pw = Curl_MD5_init(Curl_DIGEST_MD5);
- if(!MD5pw)
- return CURLE_OUT_OF_MEMORY;
- Curl_MD5_update(MD5pw, tmp, curlx_uztoui(tmplen));
- Curl_MD5_final(MD5pw, md5sum);
-#endif
- return CURLE_OK;
+ return Curl_ssl->md5sum(tmp, tmplen, md5sum, md5len);
}
#endif
@@ -965,11 +964,7 @@ CURLcode Curl_ssl_md5sum(unsigned char *tmp, /* input */
*/
bool Curl_ssl_cert_status_request(void)
{
-#ifdef curlssl_cert_status_request
- return curlssl_cert_status_request();
-#else
- return FALSE;
-#endif
+ return Curl_ssl->cert_status_request();
}
/*
@@ -977,11 +972,341 @@ bool Curl_ssl_cert_status_request(void)
*/
bool Curl_ssl_false_start(void)
{
-#ifdef curlssl_false_start
- return curlssl_false_start();
-#else
+ return Curl_ssl->false_start();
+}
+
+/*
+ * Default implementations for unsupported functions.
+ */
+
+int Curl_none_init(void)
+{
+ return 1;
+}
+
+void Curl_none_cleanup(void)
+{ }
+
+int Curl_none_shutdown(struct connectdata *conn UNUSED_PARAM,
+ int sockindex UNUSED_PARAM)
+{
+ (void)conn;
+ (void)sockindex;
+ return 0;
+}
+
+int Curl_none_check_cxn(struct connectdata *conn UNUSED_PARAM)
+{
+ (void)conn;
+ return -1;
+}
+
+CURLcode Curl_none_random(struct Curl_easy *data UNUSED_PARAM,
+ unsigned char *entropy UNUSED_PARAM,
+ size_t length UNUSED_PARAM)
+{
+ (void)data;
+ (void)entropy;
+ (void)length;
+ return CURLE_NOT_BUILT_IN;
+}
+
+void Curl_none_close_all(struct Curl_easy *data UNUSED_PARAM)
+{
+ (void)data;
+}
+
+void Curl_none_session_free(void *ptr UNUSED_PARAM)
+{
+ (void)ptr;
+}
+
+bool Curl_none_data_pending(const struct connectdata *conn UNUSED_PARAM,
+ int connindex UNUSED_PARAM)
+{
+ (void)conn;
+ (void)connindex;
+ return 0;
+}
+
+bool Curl_none_cert_status_request(void)
+{
return FALSE;
+}
+
+CURLcode Curl_none_set_engine(struct Curl_easy *data UNUSED_PARAM,
+ const char *engine UNUSED_PARAM)
+{
+ (void)data;
+ (void)engine;
+ return CURLE_NOT_BUILT_IN;
+}
+
+CURLcode Curl_none_set_engine_default(struct Curl_easy *data UNUSED_PARAM)
+{
+ (void)data;
+ return CURLE_NOT_BUILT_IN;
+}
+
+struct curl_slist *Curl_none_engines_list(struct Curl_easy *data UNUSED_PARAM)
+{
+ (void)data;
+ return (struct curl_slist *)NULL;
+}
+
+bool Curl_none_false_start(void)
+{
+ return FALSE;
+}
+
+CURLcode Curl_none_md5sum(unsigned char *input, size_t inputlen,
+ unsigned char *md5sum, size_t md5len UNUSED_PARAM)
+{
+ MD5_context *MD5pw;
+
+ (void)md5len;
+
+ MD5pw = Curl_MD5_init(Curl_DIGEST_MD5);
+ if(!MD5pw)
+ return CURLE_OUT_OF_MEMORY;
+ Curl_MD5_update(MD5pw, input, curlx_uztoui(inputlen));
+ Curl_MD5_final(MD5pw, md5sum);
+ return CURLE_OK;
+}
+
+static int Curl_multissl_init(void)
+{
+ if(multissl_init(NULL))
+ return 1;
+ return Curl_ssl->init();
+}
+
+static CURLcode Curl_multissl_connect(struct connectdata *conn, int sockindex)
+{
+ if(multissl_init(NULL))
+ return CURLE_FAILED_INIT;
+ return Curl_ssl->connect(conn, sockindex);
+}
+
+static CURLcode Curl_multissl_connect_nonblocking(struct connectdata *conn,
+ int sockindex, bool *done)
+{
+ if(multissl_init(NULL))
+ return CURLE_FAILED_INIT;
+ return Curl_ssl->connect_nonblocking(conn, sockindex, done);
+}
+
+static void *Curl_multissl_get_internals(struct ssl_connect_data *connssl,
+ CURLINFO info)
+{
+ if(multissl_init(NULL))
+ return NULL;
+ return Curl_ssl->get_internals(connssl, info);
+}
+
+static void Curl_multissl_close(struct connectdata *conn, int sockindex)
+{
+ if(multissl_init(NULL))
+ return;
+ Curl_ssl->close(conn, sockindex);
+}
+
+static const struct Curl_ssl Curl_ssl_multi = {
+ { CURLSSLBACKEND_NONE, "multi" }, /* info */
+
+ 0, /* have_ca_path */
+ 0, /* have_certinfo */
+ 0, /* have_pinnedpubkey */
+ 0, /* have_ssl_ctx */
+ 0, /* support_https_proxy */
+
+ (size_t)-1, /* something insanely large to be on the safe side */
+
+ Curl_multissl_init, /* init */
+ Curl_none_cleanup, /* cleanup */
+ Curl_multissl_version, /* version */
+ Curl_none_check_cxn, /* check_cxn */
+ Curl_none_shutdown, /* shutdown */
+ Curl_none_data_pending, /* data_pending */
+ Curl_none_random, /* random */
+ Curl_none_cert_status_request, /* cert_status_request */
+ Curl_multissl_connect, /* connect */
+ Curl_multissl_connect_nonblocking, /* connect_nonblocking */
+ Curl_multissl_get_internals, /* get_internals */
+ Curl_multissl_close, /* close */
+ Curl_none_close_all, /* close_all */
+ Curl_none_session_free, /* session_free */
+ Curl_none_set_engine, /* set_engine */
+ Curl_none_set_engine_default, /* set_engine_default */
+ Curl_none_engines_list, /* engines_list */
+ Curl_none_false_start, /* false_start */
+ Curl_none_md5sum, /* md5sum */
+ NULL /* sha256sum */
+};
+
+const struct Curl_ssl *Curl_ssl =
+#if defined(CURL_WITH_MULTI_SSL)
+ &Curl_ssl_multi;
+#elif defined(USE_AXTLS)
+ &Curl_ssl_axtls;
+#elif defined(USE_CYASSL)
+ &Curl_ssl_cyassl;
+#elif defined(USE_DARWINSSL)
+ &Curl_ssl_darwinssl;
+#elif defined(USE_GNUTLS)
+ &Curl_ssl_gnutls;
+#elif defined(USE_GSKIT)
+ &Curl_ssl_gskit;
+#elif defined(USE_MBEDTLS)
+ &Curl_ssl_mbedtls;
+#elif defined(USE_NSS)
+ &Curl_ssl_nss;
+#elif defined(USE_OPENSSL)
+ &Curl_ssl_openssl;
+#elif defined(USE_POLARSSL)
+ &Curl_ssl_polarssl;
+#elif defined(USE_SCHANNEL)
+ &Curl_ssl_schannel;
+#else
+#error "Missing struct Curl_ssl for selected SSL backend"
+#endif
+
+static const struct Curl_ssl *available_backends[] = {
+#if defined(USE_AXTLS)
+ &Curl_ssl_axtls,
+#endif
+#if defined(USE_CYASSL)
+ &Curl_ssl_cyassl,
#endif
+#if defined(USE_DARWINSSL)
+ &Curl_ssl_darwinssl,
+#endif
+#if defined(USE_GNUTLS)
+ &Curl_ssl_gnutls,
+#endif
+#if defined(USE_GSKIT)
+ &Curl_ssl_gskit,
+#endif
+#if defined(USE_MBEDTLS)
+ &Curl_ssl_mbedtls,
+#endif
+#if defined(USE_NSS)
+ &Curl_ssl_nss,
+#endif
+#if defined(USE_OPENSSL)
+ &Curl_ssl_openssl,
+#endif
+#if defined(USE_POLARSSL)
+ &Curl_ssl_polarssl,
+#endif
+#if defined(USE_SCHANNEL)
+ &Curl_ssl_schannel,
+#endif
+ NULL
+};
+
+static size_t Curl_multissl_version(char *buffer, size_t size)
+{
+ static const struct Curl_ssl *selected;
+ static char backends[200];
+ static size_t total;
+ const struct Curl_ssl *current;
+
+ current = Curl_ssl == &Curl_ssl_multi ? available_backends[0] : Curl_ssl;
+
+ if(current != selected) {
+ char *p = backends;
+ int i;
+
+ selected = current;
+
+ for(i = 0; available_backends[i]; i++) {
+ if(i)
+ *(p++) = ' ';
+ if(selected != available_backends[i])
+ *(p++) = '(';
+ p += available_backends[i]->version(p, backends + sizeof(backends) - p);
+ if(selected != available_backends[i])
+ *(p++) = ')';
+ }
+ *p = '\0';
+ total = p - backends;
+ }
+
+ if(size < total)
+ memcpy(buffer, backends, total + 1);
+ else {
+ memcpy(buffer, backends, size - 1);
+ buffer[size - 1] = '\0';
+ }
+
+ return total;
+}
+
+static int multissl_init(const struct Curl_ssl *backend)
+{
+ const char *env;
+ int i;
+
+ if(Curl_ssl != &Curl_ssl_multi)
+ return 1;
+
+ if(backend) {
+ Curl_ssl = backend;
+ return 0;
+ }
+
+ if(!available_backends[0])
+ return 1;
+
+ env = getenv("CURL_SSL_BACKEND");
+#ifdef CURL_DEFAULT_SSL_BACKEND
+ if(!env)
+ env = CURL_DEFAULT_SSL_BACKEND;
+#endif
+ if(env) {
+ for(i = 0; available_backends[i]; i++) {
+ if(strcasecompare(env, available_backends[i]->info.name)) {
+ Curl_ssl = available_backends[i];
+ return 0;
+ }
+ }
+ }
+
+ /* Fall back to first available backend */
+ Curl_ssl = available_backends[0];
+ return 0;
+}
+
+CURLsslset curl_global_sslset(curl_sslbackend id, const char *name,
+ const curl_ssl_backend ***avail)
+{
+ int i;
+
+ if(Curl_ssl != &Curl_ssl_multi)
+ return id == Curl_ssl->info.id ? CURLSSLSET_OK : CURLSSLSET_TOO_LATE;
+
+ for(i = 0; available_backends[i]; i++) {
+ if(available_backends[i]->info.id == id ||
+ (name && strcasecompare(available_backends[i]->info.name, name))) {
+ multissl_init(available_backends[i]);
+ return CURLSSLSET_OK;
+ }
+ }
+
+ if(avail)
+ *avail = (const curl_ssl_backend **)&available_backends;
+ return CURLSSLSET_UNKNOWN_BACKEND;
+}
+
+#else /* USE_SSL */
+CURLsslset curl_global_sslset(curl_sslbackend id, const char *name,
+ const curl_ssl_backend ***avail)
+{
+ (void)id;
+ (void)name;
+ (void)avail;
+ return CURLSSLSET_NO_BACKENDS;
}
-#endif /* USE_SSL */
+#endif /* !USE_SSL */
diff --git a/Utilities/cmcurl/lib/vtls/vtls.h b/Utilities/cmcurl/lib/vtls/vtls.h
index 2aabeda20..f1a11ea58 100644
--- a/Utilities/cmcurl/lib/vtls/vtls.h
+++ b/Utilities/cmcurl/lib/vtls/vtls.h
@@ -7,7 +7,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -23,6 +23,80 @@
***************************************************************************/
#include "curl_setup.h"
+struct connectdata;
+struct ssl_connect_data;
+
+struct Curl_ssl {
+ /*
+ * This *must* be the first entry to allow returning the list of available
+ * backends in curl_global_sslset().
+ */
+ curl_ssl_backend info;
+
+ unsigned have_ca_path:1; /* supports CAPATH */
+ unsigned have_certinfo:1; /* supports CURLOPT_CERTINFO */
+ unsigned have_pinnedpubkey:1; /* supports CURLOPT_PINNEDPUBLICKEY */
+ unsigned have_ssl_ctx:1; /* supports CURLOPT_SSL_CTX_* */
+
+ unsigned support_https_proxy:1; /* supports access via HTTPS proxies */
+
+ size_t sizeof_ssl_backend_data;
+
+ int (*init)(void);
+ void (*cleanup)(void);
+
+ size_t (*version)(char *buffer, size_t size);
+ int (*check_cxn)(struct connectdata *cxn);
+ int (*shutdown)(struct connectdata *conn, int sockindex);
+ bool (*data_pending)(const struct connectdata *conn,
+ int connindex);
+
+ /* return 0 if a find random is filled in */
+ CURLcode (*random)(struct Curl_easy *data, unsigned char *entropy,
+ size_t length);
+ bool (*cert_status_request)(void);
+
+ CURLcode (*connect)(struct connectdata *conn, int sockindex);
+ CURLcode (*connect_nonblocking)(struct connectdata *conn, int sockindex,
+ bool *done);
+ void *(*get_internals)(struct ssl_connect_data *connssl, CURLINFO info);
+ void (*close)(struct connectdata *conn, int sockindex);
+ void (*close_all)(struct Curl_easy *data);
+ void (*session_free)(void *ptr);
+
+ CURLcode (*set_engine)(struct Curl_easy *data, const char *engine);
+ CURLcode (*set_engine_default)(struct Curl_easy *data);
+ struct curl_slist *(*engines_list)(struct Curl_easy *data);
+
+ bool (*false_start)(void);
+
+ CURLcode (*md5sum)(unsigned char *input, size_t inputlen,
+ unsigned char *md5sum, size_t md5sumlen);
+ void (*sha256sum)(const unsigned char *input, size_t inputlen,
+ unsigned char *sha256sum, size_t sha256sumlen);
+};
+
+#ifdef USE_SSL
+extern const struct Curl_ssl *Curl_ssl;
+#endif
+
+int Curl_none_init(void);
+void Curl_none_cleanup(void);
+int Curl_none_shutdown(struct connectdata *conn, int sockindex);
+int Curl_none_check_cxn(struct connectdata *conn);
+CURLcode Curl_none_random(struct Curl_easy *data, unsigned char *entropy,
+ size_t length);
+void Curl_none_close_all(struct Curl_easy *data);
+void Curl_none_session_free(void *ptr);
+bool Curl_none_data_pending(const struct connectdata *conn, int connindex);
+bool Curl_none_cert_status_request(void);
+CURLcode Curl_none_set_engine(struct Curl_easy *data, const char *engine);
+CURLcode Curl_none_set_engine_default(struct Curl_easy *data);
+struct curl_slist *Curl_none_engines_list(struct Curl_easy *data);
+bool Curl_none_false_start(void);
+CURLcode Curl_none_md5sum(unsigned char *input, size_t inputlen,
+ unsigned char *md5sum, size_t md5len);
+
#include "openssl.h" /* OpenSSL versions */
#include "gtls.h" /* GnuTLS versions */
#include "nssg.h" /* NSS versions */
@@ -42,8 +116,8 @@
#define MD5_DIGEST_LENGTH 16 /* fixed size */
#endif
-#ifndef SHA256_DIGEST_LENGTH
-#define SHA256_DIGEST_LENGTH 32 /* fixed size */
+#ifndef CURL_SHA256_DIGEST_LENGTH
+#define CURL_SHA256_DIGEST_LENGTH 32 /* fixed size */
#endif
/* see https://tools.ietf.org/html/draft-ietf-tls-applayerprotoneg-04 */
@@ -172,8 +246,6 @@ bool Curl_ssl_false_start(void);
#define SSL_SHUTDOWN_TIMEOUT 10000 /* ms */
#else
-/* Set the API backend definition to none */
-#define CURL_SSL_BACKEND CURLSSLBACKEND_NONE
/* When SSL support is not present, just define away these function calls */
#define Curl_ssl_init() 1
diff --git a/Utilities/cmcurl/lib/warnless.c b/Utilities/cmcurl/lib/warnless.c
index fb085c86d..05d9038dc 100644
--- a/Utilities/cmcurl/lib/warnless.c
+++ b/Utilities/cmcurl/lib/warnless.c
@@ -5,7 +5,7 @@
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
- * Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
+ * Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
@@ -69,36 +69,36 @@
# error "SIZEOF_INT not defined"
#endif
-#if (CURL_SIZEOF_LONG == 2)
+#if (SIZEOF_LONG == 2)
# define CURL_MASK_SLONG 0x7FFFL
# define CURL_MASK_ULONG 0xFFFFUL
-#elif (CURL_SIZEOF_LONG == 4)
+#elif (SIZEOF_LONG == 4)
# define CURL_MASK_SLONG 0x7FFFFFFFL
# define CURL_MASK_ULONG 0xFFFFFFFFUL
-#elif (CURL_SIZEOF_LONG == 8)
+#elif (SIZEOF_LONG == 8)
# define CURL_MASK_SLONG 0x7FFFFFFFFFFFFFFFL
# define CURL_MASK_ULONG 0xFFFFFFFFFFFFFFFFUL
-#elif (CURL_SIZEOF_LONG == 16)
+#elif (SIZEOF_LONG == 16)
# define CURL_MASK_SLONG 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFL
# define CURL_MASK_ULONG 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFUL
#else
-# error "CURL_SIZEOF_LONG not defined"
+# error "SIZEOF_LONG not defined"
#endif
-#if (CURL_SIZEOF_CURL_OFF_T == 2)
+#if (SIZEOF_CURL_OFF_T == 2)
# define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFF)
# define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFF)
-#elif (CURL_SIZEOF_CURL_OFF_T == 4)
+#elif (SIZEOF_CURL_OFF_T == 4)
# define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFFFFFF)
# define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFFFFFF)
-#elif (CURL_SIZEOF_CURL_OFF_T == 8)
+#elif (SIZEOF_CURL_OFF_T == 8)
# define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFFFFFFFFFFFFFF)
# define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFFFFFFFFFFFFFF)
-#elif (CURL_SIZEOF_CURL_OFF_T == 16)
+#elif (SIZEOF_CURL_OFF_T == 16)
# define CURL_MASK_SCOFFT CURL_OFF_T_C(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
# define CURL_MASK_UCOFFT CURL_OFF_TU_C(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
#else
-# error "CURL_SIZEOF_CURL_OFF_T not defined"
+# error "SIZEOF_CURL_OFF_T not defined"
#endif
#if (SIZEOF_SIZE_T == SIZEOF_SHORT)
@@ -107,10 +107,10 @@
#elif (SIZEOF_SIZE_T == SIZEOF_INT)
# define CURL_MASK_SSIZE_T CURL_MASK_SINT
# define CURL_MASK_USIZE_T CURL_MASK_UINT
-#elif (SIZEOF_SIZE_T == CURL_SIZEOF_LONG)
+#elif (SIZEOF_SIZE_T == SIZEOF_LONG)
# define CURL_MASK_SSIZE_T CURL_MASK_SLONG
# define CURL_MASK_USIZE_T CURL_MASK_ULONG
-#elif (SIZEOF_SIZE_T == CURL_SIZEOF_CURL_OFF_T)
+#elif (SIZEOF_SIZE_T == SIZEOF_CURL_OFF_T)
# define CURL_MASK_SSIZE_T CURL_MASK_SCOFFT
# define CURL_MASK_USIZE_T CURL_MASK_UCOFFT
#else
@@ -226,7 +226,7 @@ unsigned long curlx_uztoul(size_t uznum)
# pragma warning(disable:810) /* conversion may lose significant bits */
#endif
-#if (CURL_SIZEOF_LONG < SIZEOF_SIZE_T)
+#if (SIZEOF_LONG < SIZEOF_SIZE_T)
DEBUGASSERT(uznum <= (size_t) CURL_MASK_ULONG);
#endif
return (unsigned long)(uznum & (size_t) CURL_MASK_ULONG);
@@ -269,7 +269,7 @@ int curlx_sltosi(long slnum)
#endif
DEBUGASSERT(slnum >= 0);
-#if (SIZEOF_INT < CURL_SIZEOF_LONG)
+#if (SIZEOF_INT < SIZEOF_LONG)
DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_SINT);
#endif
return (int)(slnum & (long) CURL_MASK_SINT);
@@ -291,7 +291,7 @@ unsigned int curlx_sltoui(long slnum)
#endif
DEBUGASSERT(slnum >= 0);
-#if (SIZEOF_INT < CURL_SIZEOF_LONG)
+#if (SIZEOF_INT < SIZEOF_LONG)
DEBUGASSERT((unsigned long) slnum <= (unsigned long) CURL_MASK_UINT);
#endif
return (unsigned int)(slnum & (long) CURL_MASK_UINT);
diff --git a/Utilities/cmexpat/.gitattributes b/Utilities/cmexpat/.gitattributes
deleted file mode 100644
index 562b12e16..000000000
--- a/Utilities/cmexpat/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -whitespace
diff --git a/Utilities/cmjsoncpp/.gitattributes b/Utilities/cmjsoncpp/.gitattributes
deleted file mode 100644
index 562b12e16..000000000
--- a/Utilities/cmjsoncpp/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -whitespace
diff --git a/Utilities/cmjsoncpp/CMakeLists.txt b/Utilities/cmjsoncpp/CMakeLists.txt
index bc9076e8e..ef370cc2c 100644
--- a/Utilities/cmjsoncpp/CMakeLists.txt
+++ b/Utilities/cmjsoncpp/CMakeLists.txt
@@ -9,11 +9,9 @@ elseif(CMAKE_CXX_COMPILER_ID STREQUAL "PathScale")
endif()
set(JSONCPP_SOURCES
- src/lib_json/json_batchallocator.h
src/lib_json/json_reader.cpp
src/lib_json/json_tool.h
src/lib_json/json_value.cpp
- src/lib_json/json_valueiterator.inl
src/lib_json/json_writer.cpp
)
diff --git a/Utilities/cmjsoncpp/LICENSE b/Utilities/cmjsoncpp/LICENSE
index ca2bfe1a0..89280a6c4 100644
--- a/Utilities/cmjsoncpp/LICENSE
+++ b/Utilities/cmjsoncpp/LICENSE
@@ -2,13 +2,13 @@ The JsonCpp library's source code, including accompanying documentation,
tests and demonstration applications, are licensed under the following
conditions...
-The author (Baptiste Lepilleur) explicitly disclaims copyright in all
+Baptiste Lepilleur and The JsonCpp Authors explicitly disclaim copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
this software is released into the Public Domain.
In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
-2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
-released under the terms of the MIT License (see below).
+2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur and
+The JsonCpp Authors, and is released under the terms of the MIT License (see below).
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
@@ -23,7 +23,7 @@ described in clear, concise terms at:
The full text of the MIT License follows:
========================================================================
-Copyright (c) 2007-2010 Baptiste Lepilleur
+Copyright (c) 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
diff --git a/Utilities/cmjsoncpp/include/json/allocator.h b/Utilities/cmjsoncpp/include/json/allocator.h
new file mode 100644
index 000000000..9562436c6
--- /dev/null
+++ b/Utilities/cmjsoncpp/include/json/allocator.h
@@ -0,0 +1,102 @@
+// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
+// Distributed under MIT license, or public domain if desired and
+// 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
+
+#include <cstring>
+#include <memory>
+
+#if !defined(__SUNPRO_CC)
+#pragma pack(push, 8)
+#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, typename U>
+bool operator==(const SecureAllocator<T>&, const SecureAllocator<U>&) {
+ return true;
+}
+
+template<typename T, typename U>
+bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) {
+ return false;
+}
+
+} //namespace Json
+
+#if !defined(__SUNPRO_CC)
+#pragma pack(pop)
+#endif
+
+#endif // CPPTL_JSON_ALLOCATOR_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/include/json/assertions.h b/Utilities/cmjsoncpp/include/json/assertions.h
index 37a3ff553..f64913fbe 100644
--- a/Utilities/cmjsoncpp/include/json/assertions.h
+++ b/Utilities/cmjsoncpp/include/json/assertions.h
@@ -1,4 +1,4 @@
-// Copyright 2007-2010 Baptiste Lepilleur
+// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
@@ -11,31 +11,44 @@
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <stdlib.h>
+#include <sstream>
+/** It should not be possible for a maliciously designed file to
+ * cause an abort() or seg-fault, so these macros are used only
+ * for pre-condition violations and internal logic errors.
+ */
#if JSON_USE_EXCEPTION
-#include <stdexcept>
-#define JSON_ASSERT(condition) \
- assert(condition); // @todo <= change this into an exception throw
-#define JSON_FAIL_MESSAGE(message) throw std::runtime_error(message);
+
+// @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; \
+ Json::throwLogicError(oss.str()); \
+ abort(); \
+ }
+
#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 bugs we write to invalid memory in order to crash hard, so that a
-// debugger or crash reporter gets the chance to take over. We still call exit()
-// afterward in order to tell the compiler that this macro doesn't return.
-#define JSON_FAIL_MESSAGE(message) \
+// release builds we abort, for a core-dump or debugger.
+# define JSON_FAIL_MESSAGE(message) \
{ \
- assert(false&& message); \
- strcpy(reinterpret_cast<char*>(666), message); \
- exit(123); \
+ JSONCPP_OSTRINGSTREAM oss; oss << message; \
+ assert(false && oss.str().c_str()); \
+ abort(); \
}
+
#endif
#define JSON_ASSERT_MESSAGE(condition, message) \
if (!(condition)) { \
- JSON_FAIL_MESSAGE(message) \
+ JSON_FAIL_MESSAGE(message); \
}
#endif // CPPTL_JSON_ASSERTIONS_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/include/json/config.h b/Utilities/cmjsoncpp/include/json/config.h
index 6847ceba8..eb52e71e4 100644
--- a/Utilities/cmjsoncpp/include/json/config.h
+++ b/Utilities/cmjsoncpp/include/json/config.h
@@ -1,10 +1,13 @@
-// Copyright 2007-2010 Baptiste Lepilleur
+// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef JSON_CONFIG_H_INCLUDED
#define JSON_CONFIG_H_INCLUDED
+#include <stddef.h>
+#include <string> //typedef String
+#include <stdint.h> //typedef int64_t, uint64_t
// Include KWSys Large File Support configuration.
#include <cmsys/Configure.h>
@@ -22,17 +25,6 @@
/// std::map
/// as Value container.
//# define JSON_USE_CPPTL_SMALLMAP 1
-/// If defined, indicates that Json specific container should be used
-/// (hash table & simple deque container with customizable allocator).
-/// THIS FEATURE IS STILL EXPERIMENTAL! There is know bugs: See #3177332
-//# define JSON_VALUE_USE_INTERNAL_MAP 1
-/// Force usage of standard new/malloc based allocator instead of memory pool
-/// based allocator.
-/// The memory pools allocator used optimization (initializing Value and
-/// ValueInternalLink
-/// as if it was a POD) that may cause some validation tool to report errors.
-/// Only has effects if JSON_VALUE_USE_INTERNAL_MAP is defined.
-//# define JSON_USE_SIMPLE_INTERNAL_ALLOCATOR 1
// If non-zero, the library uses exceptions to report bad input instead of C
// assertion macros. The default is to use exceptions.
@@ -55,12 +47,12 @@
#ifdef JSON_IN_CPPTL
#define JSON_API CPPTL_API
#elif defined(JSON_DLL_BUILD)
-#if defined(_MSC_VER)
+#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllexport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#endif // if defined(_MSC_VER)
#elif defined(JSON_DLL)
-#if defined(_MSC_VER)
+#if defined(_MSC_VER) || defined(__MINGW32__)
#define JSON_API __declspec(dllimport)
#define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
#endif // if defined(_MSC_VER)
@@ -74,26 +66,97 @@
// Storages, and 64 bits integer support is disabled.
// #define JSON_NO_INT64 1
-#if defined(_MSC_VER) && _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 // if defined(_MSC_VER) && _MSC_VER < 1200 // MSVC 6
-
-#if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008
-/// Indicates that the following function is deprecated.
-#define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
+#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
+
+# if _MSC_VER >= 1500 // MSVC 2008
+ /// Indicates that the following function is deprecated.
+# define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
+# endif
+
+#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
+#else
+# define JSONCPP_OVERRIDE
+# define JSONCPP_NOEXCEPT throw()
+#endif
+
+#ifndef JSON_HAS_RVALUE_REFERENCES
+
+#if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
+#define JSON_HAS_RVALUE_REFERENCES 1
+#endif // MSVC >= 2010
+
+#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
#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
+#endif // __clang__ || __GNUC__
+
+#undef JSONCPP_DEPRECATED // no deprecations in CMake copy
#if !defined(JSONCPP_DEPRECATED)
#define JSONCPP_DEPRECATED(message)
#endif // if !defined(JSONCPP_DEPRECATED)
+#if __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
+
+#endif // if !defined(JSON_IS_AMALGAMATION)
+
namespace Json {
typedef int Int;
typedef unsigned int UInt;
@@ -107,13 +170,26 @@ typedef unsigned int LargestUInt;
typedef __int64 Int64;
typedef unsigned __int64 UInt64;
#else // if defined(_MSC_VER) // Other platforms, use long long
-typedef long long int Int64;
-typedef unsigned long long int UInt64;
+typedef int64_t Int64;
+typedef uint64_t UInt64;
#endif // if defined(_MSC_VER)
typedef Int64 LargestInt;
typedef UInt64 LargestUInt;
#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
#endif // JSON_CONFIG_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/include/json/features.h b/Utilities/cmjsoncpp/include/json/features.h
index 1bb7bb614..365abb356 100644
--- a/Utilities/cmjsoncpp/include/json/features.h
+++ b/Utilities/cmjsoncpp/include/json/features.h
@@ -1,4 +1,4 @@
-// Copyright 2007-2010 Baptiste Lepilleur
+// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
@@ -10,6 +10,10 @@
#include "forwards.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
+#if !defined(__SUNPRO_CC)
+#pragma pack(push, 8)
+#endif
+
namespace Json {
/** \brief Configuration passed to reader and writer.
@@ -54,4 +58,8 @@ public:
} // namespace Json
+#if !defined(__SUNPRO_CC)
+#pragma pack(pop)
+#endif
+
#endif // CPPTL_JSON_FEATURES_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/include/json/forwards.h b/Utilities/cmjsoncpp/include/json/forwards.h
index 84a26cd2f..70bbe191c 100644
--- a/Utilities/cmjsoncpp/include/json/forwards.h
+++ b/Utilities/cmjsoncpp/include/json/forwards.h
@@ -1,4 +1,4 @@
-// Copyright 2007-2010 Baptiste Lepilleur
+// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
@@ -31,12 +31,6 @@ class Value;
class ValueIteratorBase;
class ValueIterator;
class ValueConstIterator;
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
-class ValueMapAllocator;
-class ValueInternalLink;
-class ValueInternalArray;
-class ValueInternalMap;
-#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
} // namespace Json
diff --git a/Utilities/cmjsoncpp/include/json/json.h b/Utilities/cmjsoncpp/include/json/json.h
index f89bc6270..59646723b 100644
--- a/Utilities/cmjsoncpp/include/json/json.h
+++ b/Utilities/cmjsoncpp/include/json/json.h
@@ -1,4 +1,4 @@
-// Copyright 2007-2010 Baptiste Lepilleur
+// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
diff --git a/Utilities/cmjsoncpp/include/json/reader.h b/Utilities/cmjsoncpp/include/json/reader.h
index 95237d168..667246a0b 100644
--- a/Utilities/cmjsoncpp/include/json/reader.h
+++ b/Utilities/cmjsoncpp/include/json/reader.h
@@ -1,4 +1,4 @@
-// Copyright 2007-2010 Baptiste Lepilleur
+// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
@@ -14,6 +14,7 @@
#include <iosfwd>
#include <stack>
#include <string>
+#include <istream>
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
@@ -22,13 +23,18 @@
#pragma warning(disable : 4251)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#if !defined(__SUNPRO_CC)
+#pragma pack(push, 8)
+#endif
+
namespace Json {
/** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a
*Value.
*
+ * deprecated Use CharReader and CharReaderBuilder.
*/
-class JSON_API Reader {
+class JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead") JSON_API Reader {
public:
typedef char Char;
typedef const Char* Location;
@@ -40,9 +46,9 @@ public:
*
*/
struct StructuredError {
- size_t offset_start;
- size_t offset_limit;
- std::string message;
+ ptrdiff_t offset_start;
+ ptrdiff_t offset_limit;
+ JSONCPP_STRING message;
};
/** \brief Constructs a Reader allowing all features
@@ -78,7 +84,7 @@ public:
document to read.
* \param endDoc Pointer on the end of the UTF-8 encoded string of the
document to read.
- \ Must be >= beginDoc.
+ * 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
@@ -97,7 +103,7 @@ public:
/// \brief Parse from input stream.
/// \see Json::operator>>(std::istream&, Json::Value&).
- bool parse(std::istream& is, Value& root, bool collectComments = true);
+ bool parse(JSONCPP_ISTREAM& is, Value& root, bool collectComments = true);
/** \brief Returns a user friendly string that list errors in the parsed
* document.
@@ -106,8 +112,10 @@ public:
* the parsed document. An empty string is returned if no error
* occurred
* during parsing.
+ * deprecated Use getFormattedErrorMessages() instead (typo fix).
*/
- std::string getFormatedErrorMessages() const;
+ JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.")
+ JSONCPP_STRING getFormatedErrorMessages() const;
/** \brief Returns a user friendly string that list errors in the parsed
* document.
@@ -117,7 +125,7 @@ public:
* occurred
* during parsing.
*/
- std::string getFormattedErrorMessages() const;
+ JSONCPP_STRING getFormattedErrorMessages() const;
/** \brief Returns a vector of structured erros encounted while parsing.
* \return A (possibly empty) vector of StructuredError objects. Currently
@@ -134,7 +142,7 @@ public:
* \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 std::string& message);
+ bool pushError(const Value& value, const JSONCPP_STRING& message);
/** \brief Add a semantic error message with extra context.
* \param value JSON Value location associated with the error
@@ -143,7 +151,7 @@ public:
* \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 std::string& message, const Value& extra);
+ bool pushError(const Value& value, const JSONCPP_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
@@ -179,13 +187,12 @@ private:
class ErrorInfo {
public:
Token token_;
- std::string message_;
+ JSONCPP_STRING message_;
Location extra_;
};
typedef std::deque<ErrorInfo> Errors;
- bool expectToken(TokenType type, Token& token, const char* message);
bool readToken(Token& token);
void skipSpaces();
bool match(Location pattern, int patternLength);
@@ -200,7 +207,7 @@ private:
bool decodeNumber(Token& token);
bool decodeNumber(Token& token, Value& decoded);
bool decodeString(Token& token);
- bool decodeString(Token& token, std::string& decoded);
+ bool decodeString(Token& token, JSONCPP_STRING& decoded);
bool decodeDouble(Token& token);
bool decodeDouble(Token& token, Value& decoded);
bool decodeUnicodeCodePoint(Token& token,
@@ -211,9 +218,9 @@ private:
Location& current,
Location end,
unsigned int& unicode);
- bool addError(const std::string& message, Token& token, Location extra = 0);
+ bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0);
bool recoverFromError(TokenType skipUntilToken);
- bool addErrorAndRecover(const std::string& message,
+ bool addErrorAndRecover(const JSONCPP_STRING& message,
Token& token,
TokenType skipUntilToken);
void skipUntilSpace();
@@ -221,24 +228,154 @@ private:
Char getNextChar();
void
getLocationLineAndColumn(Location location, int& line, int& column) const;
- std::string getLocationLineAndColumn(Location location) const;
+ JSONCPP_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);
+
typedef std::stack<Value*> Nodes;
Nodes nodes_;
Errors errors_;
- std::string document_;
+ JSONCPP_STRING document_;
Location begin_;
Location end_;
Location current_;
Location lastValueEnd_;
Value* lastValue_;
- std::string commentsBefore_;
+ JSONCPP_STRING commentsBefore_;
Features features_;
bool collectComments_;
+}; // Reader
+
+/** Interface for reading JSON from a char array.
+ */
+class JSON_API CharReader {
+public:
+ virtual ~CharReader() {}
+ /** \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.
+ *
+ * \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.
+ * \return \c true if the document was successfully parsed, \c false if an
+ error occurred.
+ */
+ virtual bool parse(
+ char const* beginDoc, char const* endDoc,
+ Value* root, JSONCPP_STRING* errs) = 0;
+
+ class JSON_API Factory {
+ public:
+ virtual ~Factory() {}
+ /** \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
+
+/** \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
+*/
+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()
+ */
+ Json::Value settings_;
+
+ CharReaderBuilder();
+ ~CharReaderBuilder() JSONCPP_OVERRIDE;
+
+ CharReader* newCharReader() const JSONCPP_OVERRIDE;
+
+ /** \return true if 'settings' are legal and consistent;
+ * otherwise, indicate bad settings via 'invalid'.
+ */
+ bool validate(Json::Value* invalid) const;
+
+ /** A simple way to update a specific setting.
+ */
+ Value& operator[](JSONCPP_STRING key);
+
+ /** Called by ctor, but you can use this to reset settings_.
+ * \pre 'settings' != NULL (but Json::null is fine)
+ * \remark Defaults:
+ * snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults
+ */
+ static void setDefaults(Json::Value* settings);
+ /** Same as old Features::strictMode().
+ * \pre 'settings' != NULL (but Json::null is fine)
+ * \remark Defaults:
+ * snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode
+ */
+ static void strictMode(Json::Value* settings);
};
+/** 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);
+
/** \brief Read from 'sin' into 'root'.
Always keep comments from the input JSON.
@@ -263,10 +400,14 @@ private:
\throw std::exception on parse error.
\see Json::operator<<()
*/
-JSON_API std::istream& operator>>(std::istream&, Value&);
+JSON_API JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM&, Value&);
} // namespace Json
+#if !defined(__SUNPRO_CC)
+#pragma pack(pop)
+#endif
+
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
diff --git a/Utilities/cmjsoncpp/include/json/value.h b/Utilities/cmjsoncpp/include/json/value.h
index 197a85614..7b90c5a1a 100644
--- a/Utilities/cmjsoncpp/include/json/value.h
+++ b/Utilities/cmjsoncpp/include/json/value.h
@@ -1,4 +1,4 @@
-// Copyright 2007-2010 Baptiste Lepilleur
+// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
@@ -11,6 +11,7 @@
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <string>
#include <vector>
+#include <exception>
#ifndef JSON_USE_CPPTL_SMALLMAP
#include <map>
@@ -21,6 +22,19 @@
#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
+#endif
+
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
@@ -28,10 +42,54 @@
#pragma warning(disable : 4251)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#if !defined(__SUNPRO_CC)
+#pragma pack(push, 8)
+#endif
+
/** \brief JSON (JavaScript Object Notation).
*/
namespace Json {
+/** 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;
+protected:
+ JSONCPP_STRING msg_;
+};
+
+/** Exceptions which the user cannot easily avoid.
+ *
+ * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
+ *
+ * \remark derived from Json::Exception
+ */
+class JSON_API RuntimeError : public Exception {
+public:
+ RuntimeError(JSONCPP_STRING const& msg);
+};
+
+/** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
+ *
+ * These are precondition-violations (user bugs) and internal errors (our bugs).
+ *
+ * \remark derived from Json::Exception
+ */
+class JSON_API LogicError : public Exception {
+public:
+ LogicError(JSONCPP_STRING const& msg);
+};
+
+/// used internally
+JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg);
+/// used internally
+JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg);
+
/** \brief Type of the value held by a Value object.
*/
enum ValueType {
@@ -74,14 +132,14 @@ enum CommentPlacement {
*/
class JSON_API StaticString {
public:
- explicit StaticString(const char* czstring) : str_(czstring) {}
+ explicit StaticString(const char* czstring) : c_str_(czstring) {}
- operator const char*() const { return str_; }
+ operator const char*() const { return c_str_; }
- const char* c_str() const { return str_; }
+ const char* c_str() const { return c_str_; }
private:
- const char* str_;
+ const char* c_str_;
};
/** \brief Represents a <a HREF="http://www.json.org">JSON</a> value.
@@ -99,28 +157,29 @@ private:
* The type of the held value is represented by a #ValueType and
* can be obtained using type().
*
- * values of an #objectValue or #arrayValue can be accessed using operator[]()
- *methods.
- * Non const methods will automatically create the a #nullValue element
+ * Values of an #objectValue or #arrayValue can be accessed using operator[]()
+ * methods.
+ * Non-const methods will automatically create the a #nullValue element
* if it does not exist.
- * The sequence of an #arrayValue will be automatically resize and initialized
+ * The sequence of an #arrayValue will be automatically resized and initialized
* with #nullValue. resize() can be used to enlarge or truncate an #arrayValue.
*
- * The get() methods can be used to obtanis default value in the case the
- *required element
- * does not exist.
+ * 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
* the getMemberNames() method.
+ *
+ * \note #Value string-length fit in size_t, but keys must be < 2^30.
+ * (The reason is an implementation detail.) A #CharReader will raise an
+ * exception if a bound is exceeded to avoid security holes in your app,
+ * but the Value API does *not* check bounds. That is the responsibility
+ * of the caller.
*/
class JSON_API Value {
friend class ValueIteratorBase;
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
- friend class ValueInternalLink;
- friend class ValueInternalMap;
-#endif
public:
- typedef std::vector<std::string> Members;
+ typedef std::vector<JSONCPP_STRING> Members;
typedef ValueIterator iterator;
typedef ValueConstIterator const_iterator;
typedef Json::UInt UInt;
@@ -133,7 +192,10 @@ public:
typedef Json::LargestUInt LargestUInt;
typedef Json::ArrayIndex ArrayIndex;
- static const Value& null;
+ 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.
+
/// Minimum signed integer value that can be stored in a Json::Value.
static const LargestInt minLargestInt;
/// Maximum signed integer value that can be stored in a Json::Value.
@@ -159,7 +221,6 @@ public:
private:
#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
class CZString {
public:
enum DuplicationPolicy {
@@ -168,20 +229,39 @@ private:
duplicateOnCopy
};
CZString(ArrayIndex index);
- CZString(const char* cstr, DuplicationPolicy allocate);
- CZString(const CZString& other);
+ CZString(char const* str, unsigned length, DuplicationPolicy allocate);
+ CZString(CZString const& other);
+#if JSON_HAS_RVALUE_REFERENCES
+ CZString(CZString&& other);
+#endif
~CZString();
- CZString& operator=(CZString other);
- bool operator<(const CZString& other) const;
- bool operator==(const CZString& other) const;
+ 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;
+ //const char* c_str() const; ///< deprecated
+ char const* data() const;
+ unsigned length() const;
bool isStaticString() const;
private:
void swap(CZString& other);
- const char* cstr_;
- ArrayIndex index_;
+
+ struct StringStorage {
+ unsigned policy_: 2;
+ unsigned length_: 30; // 1GB max
+ };
+
+ char const* cstr_; // actually, a prefixed string, unless policy is noDup
+ union {
+ ArrayIndex index_;
+ StringStorage storage_;
+ };
};
public:
@@ -190,7 +270,6 @@ public:
#else
typedef CppTL::SmallMap<CZString, Value> ObjectValues;
#endif // ifndef JSON_USE_CPPTL_SMALLMAP
-#endif // ifndef JSON_VALUE_USE_INTERNAL_MAP
#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
public:
@@ -217,47 +296,72 @@ Json::Value obj_value(Json::objectValue); // {}
Value(UInt64 value);
#endif // if defined(JSON_HAS_INT64)
Value(double value);
- Value(const char* value);
- Value(const char* beginValue, const char* endValue);
+ 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.
* 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.
+ * \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.)
+ *
* Example of usage:
* \code
- * Json::Value aValue( StaticString("some text") );
+ * static StaticString foo("some text");
+ * Json::Value aValue(foo);
* \endcode
*/
Value(const StaticString& value);
- Value(const std::string& value);
+ Value(const JSONCPP_STRING& value); ///< Copy data() til size(). Embedded zeroes too.
#ifdef JSON_USE_CPPTL
Value(const CppTL::ConstString& value);
#endif
Value(bool value);
+ /// Deep copy.
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);
- /// Swap values.
- /// \note Currently, comments are intentionally not swapped, for
- /// both logic and efficiency.
+
+ /// Swap everything.
void swap(Value& other);
+ /// Swap values but leave comments and source offsets in place.
+ void swapPayload(Value& other);
+
+ /// copy everything.
+ void copy(const Value& other);
+ /// copy values but leave comments and source offsets in place.
+ void copyPayload(const Value& other);
ValueType type() const;
+ /// Compare payload only, not comments etc.
bool operator<(const Value& other) const;
bool operator<=(const Value& other) const;
bool operator>=(const Value& other) const;
bool operator>(const Value& other) const;
-
bool operator==(const Value& other) const;
bool operator!=(const Value& other) const;
-
int compare(const Value& other) const;
- const char* asCString() const;
- std::string asString() const;
+ 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
+#endif
+ JSONCPP_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
@@ -347,20 +451,28 @@ 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
+
/// 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.
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.
- Value& operator[](const std::string& key);
+ /// \param key may contain embedded nulls.
+ Value& operator[](const JSONCPP_STRING& key);
/// Access an object value by name, returns null if there is no member with
/// that name.
- const Value& operator[](const std::string& key) const;
+ /// \param key may contain embedded nulls.
+ const Value& operator[](const JSONCPP_STRING& key) const;
/** \brief Access an object value by name, create a null member if it does not
exist.
- * If the object as no entry for that name, then the member name used to store
+ * 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
@@ -378,27 +490,71 @@ Json::Value obj_value(Json::objectValue); // {}
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.
- Value get(const std::string& key, const Value& defaultValue) const;
+ /// \note deep copy
+ /// \note key may contain embedded nulls.
+ 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
+ /// 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
+ Value const* find(char const* begin, char const* end) const;
+ /// 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);
/// \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);
/// Same as removeMember(const char*)
- Value removeMember(const std::string& key);
+ /// \param key may contain embedded nulls.
+ /// deprecated
+ JSONCPP_DEPRECATED("")
+ Value removeMember(const JSONCPP_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)
+ 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);
/// 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.
- bool isMember(const std::string& key) const;
+ /// \param key may contain embedded nulls.
+ bool isMember(const JSONCPP_STRING& key) const;
+ /// Same as isMember(JSONCPP_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;
@@ -416,15 +572,18 @@ Json::Value obj_value(Json::objectValue); // {}
// EnumValues enumValues() const;
//# endif
- /// Comments must be //... or /* ... */
+ /// deprecated Always pass len.
+ JSONCPP_DEPRECATED("Use setComment(JSONCPP_STRING const&) instead.")
void setComment(const char* comment, CommentPlacement placement);
/// Comments must be //... or /* ... */
- void setComment(const std::string& comment, CommentPlacement placement);
+ void setComment(const char* comment, size_t len, CommentPlacement placement);
+ /// Comments must be //... or /* ... */
+ void setComment(const JSONCPP_STRING& comment, CommentPlacement placement);
bool hasComment(CommentPlacement placement) const;
/// Include delimiters and embedded newlines.
- std::string getComment(CommentPlacement placement) const;
+ JSONCPP_STRING getComment(CommentPlacement placement) const;
- std::string toStyledString() const;
+ JSONCPP_STRING toStyledString() const;
const_iterator begin() const;
const_iterator end() const;
@@ -434,34 +593,22 @@ Json::Value obj_value(Json::objectValue); // {}
// Accessors for the [start, limit) range of bytes within the JSON text from
// which this value was parsed, if any.
- void setOffsetStart(size_t start);
- void setOffsetLimit(size_t limit);
- size_t getOffsetStart() const;
- size_t getOffsetLimit() const;
+ void setOffsetStart(ptrdiff_t start);
+ void setOffsetLimit(ptrdiff_t limit);
+ ptrdiff_t getOffsetStart() const;
+ ptrdiff_t getOffsetLimit() const;
private:
void initBasic(ValueType type, bool allocated = false);
- Value& resolveReference(const char* key, bool isStatic);
-
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
- inline bool isItemAvailable() const { return itemIsUsed_ == 0; }
+ Value& resolveReference(const char* key);
+ Value& resolveReference(const char* key, const char* end);
- inline void setItemUsed(bool isUsed = true) { itemIsUsed_ = isUsed ? 1 : 0; }
-
- inline bool isMemberNameStatic() const { return memberNameIsStatic_ == 0; }
-
- inline void setMemberNameIsStatic(bool isStatic) {
- memberNameIsStatic_ = isStatic ? 1 : 0;
- }
-#endif // # ifdef JSON_VALUE_USE_INTERNAL_MAP
-
-private:
struct CommentInfo {
CommentInfo();
~CommentInfo();
- void setComment(const char* text);
+ void setComment(const char* text, size_t len);
char* comment_;
};
@@ -480,26 +627,18 @@ private:
LargestUInt uint_;
double real_;
bool bool_;
- char* string_;
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
- ValueInternalArray* array_;
- ValueInternalMap* map_;
-#else
+ char* string_; // actually ptr to unsigned, followed by str, unless !allocated_
ObjectValues* map_;
-#endif
} value_;
ValueType type_ : 8;
- int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
- unsigned int itemIsUsed_ : 1; // used by the ValueInternalMap container.
- int memberNameIsStatic_ : 1; // used by the ValueInternalMap container.
-#endif
+ unsigned int allocated_ : 1; // Notes: if declared as bool, bitfield is useless.
+ // If not allocated_, string_ must be null-terminated.
CommentInfo* comments_;
// [start, limit) byte offsets in the source JSON text from which this Value
// was extracted.
- size_t start_;
- size_t limit_;
+ ptrdiff_t start_;
+ ptrdiff_t limit_;
};
/** \brief Experimental and untested: represents an element of the "path" to
@@ -512,7 +651,7 @@ public:
PathArgument();
PathArgument(ArrayIndex index);
PathArgument(const char* key);
- PathArgument(const std::string& key);
+ PathArgument(const JSONCPP_STRING& key);
private:
enum Kind {
@@ -520,7 +659,7 @@ private:
kindIndex,
kindKey
};
- std::string key_;
+ JSONCPP_STRING key_;
ArrayIndex index_;
Kind kind_;
};
@@ -538,7 +677,7 @@ private:
*/
class JSON_API Path {
public:
- Path(const std::string& path,
+ Path(const JSONCPP_STRING& path,
const PathArgument& a1 = PathArgument(),
const PathArgument& a2 = PathArgument(),
const PathArgument& a3 = PathArgument(),
@@ -555,355 +694,16 @@ private:
typedef std::vector<const PathArgument*> InArgs;
typedef std::vector<PathArgument> Args;
- void makePath(const std::string& path, const InArgs& in);
- void addPathInArg(const std::string& path,
+ 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 std::string& path, int location);
+ void invalidPath(const JSONCPP_STRING& path, int location);
Args args_;
};
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
-/** \brief Allocator to customize Value internal map.
- * Below is an example of a simple implementation (default implementation
- actually
- * use memory pool for speed).
- * \code
- class DefaultValueMapAllocator : public ValueMapAllocator
- {
- public: // overridden from ValueMapAllocator
- virtual ValueInternalMap *newMap()
- {
- return new ValueInternalMap();
- }
-
- virtual ValueInternalMap *newMapCopy( const ValueInternalMap &other )
- {
- return new ValueInternalMap( other );
- }
-
- virtual void destructMap( ValueInternalMap *map )
- {
- delete map;
- }
-
- virtual ValueInternalLink *allocateMapBuckets( unsigned int size )
- {
- return new ValueInternalLink[size];
- }
-
- virtual void releaseMapBuckets( ValueInternalLink *links )
- {
- delete [] links;
- }
-
- virtual ValueInternalLink *allocateMapLink()
- {
- return new ValueInternalLink();
- }
-
- virtual void releaseMapLink( ValueInternalLink *link )
- {
- delete link;
- }
- };
- * \endcode
- */
-class JSON_API ValueMapAllocator {
-public:
- virtual ~ValueMapAllocator();
- virtual ValueInternalMap* newMap() = 0;
- virtual ValueInternalMap* newMapCopy(const ValueInternalMap& other) = 0;
- virtual void destructMap(ValueInternalMap* map) = 0;
- virtual ValueInternalLink* allocateMapBuckets(unsigned int size) = 0;
- virtual void releaseMapBuckets(ValueInternalLink* links) = 0;
- virtual ValueInternalLink* allocateMapLink() = 0;
- virtual void releaseMapLink(ValueInternalLink* link) = 0;
-};
-
-/** \brief ValueInternalMap hash-map bucket chain link (for internal use only).
- * \internal previous_ & next_ allows for bidirectional traversal.
- */
-class JSON_API ValueInternalLink {
-public:
- enum {
- itemPerLink = 6
- }; // sizeof(ValueInternalLink) = 128 on 32 bits architecture.
- enum InternalFlags {
- flagAvailable = 0,
- flagUsed = 1
- };
-
- ValueInternalLink();
-
- ~ValueInternalLink();
-
- Value items_[itemPerLink];
- char* keys_[itemPerLink];
- ValueInternalLink* previous_;
- ValueInternalLink* next_;
-};
-
-/** \brief A linked page based hash-table implementation used internally by
- *Value.
- * \internal ValueInternalMap is a tradional bucket based hash-table, with a
- *linked
- * list in each bucket to handle collision. There is an addional twist in that
- * each node of the collision linked list is a page containing a fixed amount of
- * value. This provides a better compromise between memory usage and speed.
- *
- * Each bucket is made up of a chained list of ValueInternalLink. The last
- * link of a given bucket can be found in the 'previous_' field of the following
- *bucket.
- * The last link of the last bucket is stored in tailLink_ as it has no
- *following bucket.
- * Only the last link of a bucket may contains 'available' item. The last link
- *always
- * contains at least one element unless is it the bucket one very first link.
- */
-class JSON_API ValueInternalMap {
- friend class ValueIteratorBase;
- friend class Value;
-
-public:
- typedef unsigned int HashKey;
- typedef unsigned int BucketIndex;
-
-#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
- struct IteratorState {
- IteratorState() : map_(0), link_(0), itemIndex_(0), bucketIndex_(0) {}
- ValueInternalMap* map_;
- ValueInternalLink* link_;
- BucketIndex itemIndex_;
- BucketIndex bucketIndex_;
- };
-#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
-
- ValueInternalMap();
- ValueInternalMap(const ValueInternalMap& other);
- ValueInternalMap& operator=(ValueInternalMap other);
- ~ValueInternalMap();
-
- void swap(ValueInternalMap& other);
-
- BucketIndex size() const;
-
- void clear();
-
- bool reserveDelta(BucketIndex growth);
-
- bool reserve(BucketIndex newItemCount);
-
- const Value* find(const char* key) const;
-
- Value* find(const char* key);
-
- Value& resolveReference(const char* key, bool isStatic);
-
- void remove(const char* key);
-
- void doActualRemove(ValueInternalLink* link,
- BucketIndex index,
- BucketIndex bucketIndex);
-
- ValueInternalLink*& getLastLinkInBucket(BucketIndex bucketIndex);
-
- Value& setNewItem(const char* key,
- bool isStatic,
- ValueInternalLink* link,
- BucketIndex index);
-
- Value& unsafeAdd(const char* key, bool isStatic, HashKey hashedKey);
-
- HashKey hash(const char* key) const;
-
- int compare(const ValueInternalMap& other) const;
-
-private:
- void makeBeginIterator(IteratorState& it) const;
- void makeEndIterator(IteratorState& it) const;
- static bool equals(const IteratorState& x, const IteratorState& other);
- static void increment(IteratorState& iterator);
- static void incrementBucket(IteratorState& iterator);
- static void decrement(IteratorState& iterator);
- static const char* key(const IteratorState& iterator);
- static const char* key(const IteratorState& iterator, bool& isStatic);
- static Value& value(const IteratorState& iterator);
- static int distance(const IteratorState& x, const IteratorState& y);
-
-private:
- ValueInternalLink* buckets_;
- ValueInternalLink* tailLink_;
- BucketIndex bucketsSize_;
- BucketIndex itemCount_;
-};
-
-/** \brief A simplified deque implementation used internally by Value.
-* \internal
-* It is based on a list of fixed "page", each page contains a fixed number of
-*items.
-* Instead of using a linked-list, a array of pointer is used for fast item
-*look-up.
-* Look-up for an element is as follow:
-* - compute page index: pageIndex = itemIndex / itemsPerPage
-* - look-up item in page: pages_[pageIndex][itemIndex % itemsPerPage]
-*
-* Insertion is amortized constant time (only the array containing the index of
-*pointers
-* need to be reallocated when items are appended).
-*/
-class JSON_API ValueInternalArray {
- friend class Value;
- friend class ValueIteratorBase;
-
-public:
- enum {
- itemsPerPage = 8
- }; // should be a power of 2 for fast divide and modulo.
- typedef Value::ArrayIndex ArrayIndex;
- typedef unsigned int PageIndex;
-
-#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
- struct IteratorState // Must be a POD
- {
- IteratorState() : array_(0), currentPageIndex_(0), currentItemIndex_(0) {}
- ValueInternalArray* array_;
- Value** currentPageIndex_;
- unsigned int currentItemIndex_;
- };
-#endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
-
- ValueInternalArray();
- ValueInternalArray(const ValueInternalArray& other);
- ValueInternalArray& operator=(ValueInternalArray other);
- ~ValueInternalArray();
- void swap(ValueInternalArray& other);
-
- void clear();
- void resize(ArrayIndex newSize);
-
- Value& resolveReference(ArrayIndex index);
-
- Value* find(ArrayIndex index) const;
-
- ArrayIndex size() const;
-
- int compare(const ValueInternalArray& other) const;
-
-private:
- static bool equals(const IteratorState& x, const IteratorState& other);
- static void increment(IteratorState& iterator);
- static void decrement(IteratorState& iterator);
- static Value& dereference(const IteratorState& iterator);
- static Value& unsafeDereference(const IteratorState& iterator);
- static int distance(const IteratorState& x, const IteratorState& y);
- static ArrayIndex indexOf(const IteratorState& iterator);
- void makeBeginIterator(IteratorState& it) const;
- void makeEndIterator(IteratorState& it) const;
- void makeIterator(IteratorState& it, ArrayIndex index) const;
-
- void makeIndexValid(ArrayIndex index);
-
- Value** pages_;
- ArrayIndex size_;
- PageIndex pageCount_;
-};
-
-/** \brief Experimental: do not use. Allocator to customize Value internal
-array.
- * Below is an example of a simple implementation (actual implementation use
- * memory pool).
- \code
-class DefaultValueArrayAllocator : public ValueArrayAllocator
-{
-public: // overridden from ValueArrayAllocator
-virtual ~DefaultValueArrayAllocator()
-{
-}
-
-virtual ValueInternalArray *newArray()
-{
- return new ValueInternalArray();
-}
-
-virtual ValueInternalArray *newArrayCopy( const ValueInternalArray &other )
-{
- return new ValueInternalArray( other );
-}
-
-virtual void destruct( ValueInternalArray *array )
-{
- delete array;
-}
-
-virtual void reallocateArrayPageIndex( Value **&indexes,
- ValueInternalArray::PageIndex
-&indexCount,
- ValueInternalArray::PageIndex
-minNewIndexCount )
-{
- ValueInternalArray::PageIndex newIndexCount = (indexCount*3)/2 + 1;
- if ( minNewIndexCount > newIndexCount )
- newIndexCount = minNewIndexCount;
- void *newIndexes = realloc( indexes, sizeof(Value*) * newIndexCount );
- if ( !newIndexes )
- throw std::bad_alloc();
- indexCount = newIndexCount;
- indexes = static_cast<Value **>( newIndexes );
-}
-virtual void releaseArrayPageIndex( Value **indexes,
- ValueInternalArray::PageIndex indexCount )
-{
- if ( indexes )
- free( indexes );
-}
-
-virtual Value *allocateArrayPage()
-{
- return static_cast<Value *>( malloc( sizeof(Value) *
-ValueInternalArray::itemsPerPage ) );
-}
-
-virtual void releaseArrayPage( Value *value )
-{
- if ( value )
- free( value );
-}
-};
- \endcode
- */
-class JSON_API ValueArrayAllocator {
-public:
- virtual ~ValueArrayAllocator();
- virtual ValueInternalArray* newArray() = 0;
- virtual ValueInternalArray* newArrayCopy(const ValueInternalArray& other) = 0;
- virtual void destructArray(ValueInternalArray* array) = 0;
- /** \brief Reallocate array page index.
- * Reallocates an array of pointer on each page.
- * \param indexes [input] pointer on the current index. May be \c NULL.
- * [output] pointer on the new index of at least
- * \a minNewIndexCount pages.
- * \param indexCount [input] current number of pages in the index.
- * [output] number of page the reallocated index can handle.
- * \b MUST be >= \a minNewIndexCount.
- * \param minNewIndexCount Minimum number of page the new index must be able
- * to
- * handle.
- */
- virtual void
- reallocateArrayPageIndex(Value**& indexes,
- ValueInternalArray::PageIndex& indexCount,
- ValueInternalArray::PageIndex minNewIndexCount) = 0;
- virtual void
- releaseArrayPageIndex(Value** indexes,
- ValueInternalArray::PageIndex indexCount) = 0;
- virtual Value* allocateArrayPage() = 0;
- virtual void releaseArrayPage(Value* value) = 0;
-};
-#endif // #ifdef JSON_VALUE_USE_INTERNAL_MAP
-
/** \brief base class for Value iterators.
*
*/
@@ -914,32 +714,35 @@ public:
typedef int difference_type;
typedef ValueIteratorBase SelfType;
- ValueIteratorBase();
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
- explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
-#else
- ValueIteratorBase(const ValueInternalArray::IteratorState& state);
- ValueIteratorBase(const ValueInternalMap::IteratorState& state);
-#endif
-
bool operator==(const SelfType& other) const { return isEqual(other); }
bool operator!=(const SelfType& other) const { return !isEqual(other); }
difference_type operator-(const SelfType& other) const {
- return computeDistance(other);
+ return other.computeDistance(*this);
}
/// Return either the index or the member name of the referenced value as a
/// Value.
Value key() const;
- /// Return the index of the referenced Value. -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;
+
/// Return the member name of the referenced Value. "" if it is not an
/// objectValue.
- const char* memberName() const;
+ /// 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
+ /// objectValue.
+ /// \note Better version than memberName(). Allows embedded nulls.
+ char const* memberName(char const** end) const;
protected:
Value& deref() const;
@@ -955,17 +758,15 @@ protected:
void copy(const SelfType& other);
private:
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
Value::ObjectValues::iterator current_;
// Indicates that iterator is for a null value.
bool isNull_;
-#else
- union {
- ValueInternalArray::IteratorState array_;
- ValueInternalMap::IteratorState map_;
- } iterator_;
- bool isArray_;
-#endif
+
+public:
+ // For some reason, BORLAND needs these at the end, rather
+ // than earlier. No idea why.
+ ValueIteratorBase();
+ explicit ValueIteratorBase(const Value::ObjectValues::iterator& current);
};
/** \brief const iterator for object and array value.
@@ -976,23 +777,19 @@ class JSON_API ValueConstIterator : public ValueIteratorBase {
public:
typedef const Value value_type;
- typedef unsigned int size_t;
- typedef int difference_type;
+ //typedef unsigned int size_t;
+ //typedef int difference_type;
typedef const Value& reference;
typedef const Value* pointer;
typedef ValueConstIterator SelfType;
ValueConstIterator();
+ ValueConstIterator(ValueIterator const& other);
private:
-/*! \internal Use by Value to create an iterator.
+/*! internal Use by Value to create an iterator.
*/
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
explicit ValueConstIterator(const Value::ObjectValues::iterator& current);
-#else
- ValueConstIterator(const ValueInternalArray::IteratorState& state);
- ValueConstIterator(const ValueInternalMap::IteratorState& state);
-#endif
public:
SelfType& operator=(const ValueIteratorBase& other);
@@ -1037,18 +834,13 @@ public:
typedef ValueIterator SelfType;
ValueIterator();
- ValueIterator(const ValueConstIterator& other);
+ 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.
*/
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
explicit ValueIterator(const Value::ObjectValues::iterator& current);
-#else
- ValueIterator(const ValueInternalArray::IteratorState& state);
- ValueIterator(const ValueInternalMap::IteratorState& state);
-#endif
public:
SelfType& operator=(const SelfType& other);
@@ -1081,6 +873,17 @@ public:
} // namespace Json
+
+namespace std {
+/// Specialize std::swap() for Json::Value.
+template<>
+inline void swap(Json::Value& a, Json::Value& b) { a.swap(b); }
+}
+
+#if !defined(__SUNPRO_CC)
+#pragma pack(pop)
+#endif
+
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
diff --git a/Utilities/cmjsoncpp/include/json/version.h b/Utilities/cmjsoncpp/include/json/version.h
index 6fe06824d..d95396189 100644
--- a/Utilities/cmjsoncpp/include/json/version.h
+++ b/Utilities/cmjsoncpp/include/json/version.h
@@ -1,14 +1,20 @@
-// DO NOT EDIT. This file is generated by CMake from "version"
-// and "version.h.in" files.
+// 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 JSONCPP_VERSION_STRING "1.0.0"
+# define JSONCPP_VERSION_STRING "1.8.2"
# define JSONCPP_VERSION_MAJOR 1
-# define JSONCPP_VERSION_MINOR 0
-# define JSONCPP_VERSION_PATCH 0
+# 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))
+#ifdef JSONCPP_USING_SECURE_MEMORY
+#undef JSONCPP_USING_SECURE_MEMORY
+#endif
+#define JSONCPP_USING_SECURE_MEMORY 0
+// If non-zero, the library zeroes any memory that it has allocated before
+// it frees its memory.
+
#endif // JSON_VERSION_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/include/json/writer.h b/Utilities/cmjsoncpp/include/json/writer.h
index 10863b078..d3ae62b28 100644
--- a/Utilities/cmjsoncpp/include/json/writer.h
+++ b/Utilities/cmjsoncpp/include/json/writer.h
@@ -1,4 +1,4 @@
-// Copyright 2007-2010 Baptiste Lepilleur
+// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
@@ -12,6 +12,7 @@
#include <iosfwd>
#include <vector>
#include <string>
+#include <ostream>
// Disable warning C4251: <data member>: <type> needs to have dll-interface to
// be used by...
@@ -20,17 +21,133 @@
#pragma warning(disable : 4251)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
+#if !defined(__SUNPRO_CC)
+#pragma pack(push, 8)
+#endif
+
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
+*/
+class JSON_API StreamWriter {
+protected:
+ JSONCPP_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
+ */
+ virtual int write(Value const& root, JSONCPP_OSTREAM* sout) = 0;
+
+ /** \brief A simple abstract factory.
+ */
+ class JSON_API Factory {
+ public:
+ virtual ~Factory();
+ /** \brief Allocate a CharReader via operator new().
+ * \throw std::exception if something goes wrong (e.g. invalid settings)
+ */
+ virtual StreamWriter* newStreamWriter() const = 0;
+ }; // 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);
+
+
+/** \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
+*/
+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()
+ */
+ Json::Value settings_;
+
+ StreamWriterBuilder();
+ ~StreamWriterBuilder() JSONCPP_OVERRIDE;
+
+ /**
+ * \throw std::exception if something goes wrong (e.g. invalid settings)
+ */
+ StreamWriter* newStreamWriter() const JSONCPP_OVERRIDE;
+
+ /** \return true if 'settings' are legal and consistent;
+ * otherwise, indicate bad settings via 'invalid'.
+ */
+ bool validate(Json::Value* invalid) const;
+ /** A simple way to update a specific setting.
+ */
+ Value& operator[](JSONCPP_STRING key);
+
+ /** Called by ctor, but you can use this to reset settings_.
+ * \pre 'settings' != NULL (but Json::null is fine)
+ * \remark Defaults:
+ * snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults
+ */
+ static void setDefaults(Json::Value* settings);
+};
+
/** \brief Abstract class for writers.
+ * deprecated Use StreamWriter. (And really, this is an implementation detail.)
*/
-class JSON_API Writer {
+class JSONCPP_DEPRECATED("Use StreamWriter instead") JSON_API Writer {
public:
virtual ~Writer();
- virtual std::string write(const Value& root) = 0;
+ virtual JSONCPP_STRING write(const Value& root) = 0;
};
/** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format
@@ -40,11 +157,13 @@ public:
*consumption,
* but may be usefull to support feature such as RPC where bandwith is limited.
* \sa Reader, Value
+ * deprecated Use StreamWriterBuilder.
*/
-class JSON_API FastWriter : public Writer {
+class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API FastWriter : public Writer {
+
public:
FastWriter();
- virtual ~FastWriter() {}
+ ~FastWriter() JSONCPP_OVERRIDE {}
void enableYAMLCompatibility();
@@ -58,12 +177,12 @@ public:
void omitEndingLineFeed();
public: // overridden from Writer
- virtual std::string write(const Value& root);
+ JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
private:
void writeValue(const Value& value);
- std::string document_;
+ JSONCPP_STRING document_;
bool yamlCompatiblityEnabled_;
bool dropNullPlaceholders_;
bool omitEndingLineFeed_;
@@ -91,40 +210,41 @@ private:
*#CommentPlacement.
*
* \sa Reader, Value, Value::setComment()
+ * deprecated Use StreamWriterBuilder.
*/
-class JSON_API StyledWriter : public Writer {
+class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledWriter : public Writer {
public:
StyledWriter();
- virtual ~StyledWriter() {}
+ ~StyledWriter() JSONCPP_OVERRIDE {}
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.
*/
- virtual std::string write(const Value& root);
+ JSONCPP_STRING write(const Value& root) JSONCPP_OVERRIDE;
private:
void writeValue(const Value& value);
void writeArrayValue(const Value& value);
bool isMultineArray(const Value& value);
- void pushValue(const std::string& value);
+ void pushValue(const JSONCPP_STRING& value);
void writeIndent();
- void writeWithIndent(const std::string& value);
+ void writeWithIndent(const JSONCPP_STRING& value);
void indent();
void unindent();
void writeCommentBeforeValue(const Value& root);
void writeCommentAfterValueOnSameLine(const Value& root);
bool hasCommentForValue(const Value& value);
- static std::string normalizeEOL(const std::string& text);
+ static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
- typedef std::vector<std::string> ChildValues;
+ typedef std::vector<JSONCPP_STRING> ChildValues;
ChildValues childValues_;
- std::string document_;
- std::string indentString_;
- int rightMargin_;
- int indentSize_;
+ JSONCPP_STRING document_;
+ JSONCPP_STRING indentString_;
+ unsigned int rightMargin_;
+ unsigned int indentSize_;
bool addChildValues_;
};
@@ -151,10 +271,14 @@ private:
#CommentPlacement.
*
* \sa Reader, Value, Value::setComment()
+ * deprecated Use StreamWriterBuilder.
*/
-class JSON_API StyledStreamWriter {
+class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledStreamWriter {
public:
- StyledStreamWriter(std::string indentation = "\t");
+/**
+ * \param indentation Each level will be indented by this amount extra.
+ */
+ StyledStreamWriter(JSONCPP_STRING indentation = "\t");
~StyledStreamWriter() {}
public:
@@ -164,48 +288,53 @@ public:
* \note There is no point in deriving from Writer, since write() should not
* return a value.
*/
- void write(std::ostream& out, const Value& root);
+ void write(JSONCPP_OSTREAM& out, const Value& root);
private:
void writeValue(const Value& value);
void writeArrayValue(const Value& value);
bool isMultineArray(const Value& value);
- void pushValue(const std::string& value);
+ void pushValue(const JSONCPP_STRING& value);
void writeIndent();
- void writeWithIndent(const std::string& value);
+ void writeWithIndent(const JSONCPP_STRING& value);
void indent();
void unindent();
void writeCommentBeforeValue(const Value& root);
void writeCommentAfterValueOnSameLine(const Value& root);
bool hasCommentForValue(const Value& value);
- static std::string normalizeEOL(const std::string& text);
+ static JSONCPP_STRING normalizeEOL(const JSONCPP_STRING& text);
- typedef std::vector<std::string> ChildValues;
+ typedef std::vector<JSONCPP_STRING> ChildValues;
ChildValues childValues_;
- std::ostream* document_;
- std::string indentString_;
- int rightMargin_;
- std::string indentation_;
- bool addChildValues_;
+ JSONCPP_OSTREAM* document_;
+ JSONCPP_STRING indentString_;
+ unsigned int rightMargin_;
+ JSONCPP_STRING indentation_;
+ bool addChildValues_ : 1;
+ bool indented_ : 1;
};
#if defined(JSON_HAS_INT64)
-std::string JSON_API valueToString(Int value);
-std::string JSON_API valueToString(UInt value);
+JSONCPP_STRING JSON_API valueToString(Int value);
+JSONCPP_STRING JSON_API valueToString(UInt value);
#endif // if defined(JSON_HAS_INT64)
-std::string JSON_API valueToString(LargestInt value);
-std::string JSON_API valueToString(LargestUInt value);
-std::string JSON_API valueToString(double value);
-std::string JSON_API valueToString(bool value);
-std::string JSON_API valueToQuotedString(const char* value);
+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);
/// \brief Output using the StyledStreamWriter.
/// \see Json::operator>>()
-JSON_API std::ostream& operator<<(std::ostream&, const Value& root);
+JSON_API JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM&, const Value& root);
} // namespace Json
+#if !defined(__SUNPRO_CC)
+#pragma pack(pop)
+#endif
+
#if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
#pragma warning(pop)
#endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING)
diff --git a/Utilities/cmjsoncpp/src/lib_json/json_batchallocator.h b/Utilities/cmjsoncpp/src/lib_json/json_batchallocator.h
deleted file mode 100644
index 2fbef7a86..000000000
--- a/Utilities/cmjsoncpp/src/lib_json/json_batchallocator.h
+++ /dev/null
@@ -1,121 +0,0 @@
-// Copyright 2007-2010 Baptiste Lepilleur
-// Distributed under MIT license, or public domain if desired and
-// recognized in your jurisdiction.
-// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
-
-#ifndef JSONCPP_BATCHALLOCATOR_H_INCLUDED
-#define JSONCPP_BATCHALLOCATOR_H_INCLUDED
-
-#include <stdlib.h>
-#include <assert.h>
-
-#ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION
-
-namespace Json {
-
-/* Fast memory allocator.
- *
- * This memory allocator allocates memory for a batch of object (specified by
- * the page size, the number of object in each page).
- *
- * It does not allow the destruction of a single object. All the allocated
- * objects can be destroyed at once. The memory can be either released or reused
- * for future allocation.
- *
- * The in-place new operator must be used to construct the object using the
- * pointer returned by allocate.
- */
-template <typename AllocatedType, const unsigned int objectPerAllocation>
-class BatchAllocator {
-public:
- BatchAllocator(unsigned int objectsPerPage = 255)
- : freeHead_(0), objectsPerPage_(objectsPerPage) {
- // printf( "Size: %d => %s\n", sizeof(AllocatedType),
- // typeid(AllocatedType).name() );
- assert(sizeof(AllocatedType) * objectPerAllocation >=
- sizeof(AllocatedType*)); // We must be able to store a slist in the
- // object free space.
- assert(objectsPerPage >= 16);
- batches_ = allocateBatch(0); // allocated a dummy page
- currentBatch_ = batches_;
- }
-
- ~BatchAllocator() {
- for (BatchInfo* batch = batches_; batch;) {
- BatchInfo* nextBatch = batch->next_;
- free(batch);
- batch = nextBatch;
- }
- }
-
- /// allocate space for an array of objectPerAllocation object.
- /// @warning it is the responsability of the caller to call objects
- /// constructors.
- AllocatedType* allocate() {
- if (freeHead_) // returns node from free list.
- {
- AllocatedType* object = freeHead_;
- freeHead_ = *(AllocatedType**)object;
- return object;
- }
- if (currentBatch_->used_ == currentBatch_->end_) {
- currentBatch_ = currentBatch_->next_;
- while (currentBatch_ && currentBatch_->used_ == currentBatch_->end_)
- currentBatch_ = currentBatch_->next_;
-
- if (!currentBatch_) // no free batch found, allocate a new one
- {
- currentBatch_ = allocateBatch(objectsPerPage_);
- currentBatch_->next_ = batches_; // insert at the head of the list
- batches_ = currentBatch_;
- }
- }
- AllocatedType* allocated = currentBatch_->used_;
- currentBatch_->used_ += objectPerAllocation;
- return allocated;
- }
-
- /// Release the object.
- /// @warning it is the responsability of the caller to actually destruct the
- /// object.
- void release(AllocatedType* object) {
- assert(object != 0);
- *(AllocatedType**)object = freeHead_;
- freeHead_ = object;
- }
-
-private:
- struct BatchInfo {
- BatchInfo* next_;
- AllocatedType* used_;
- AllocatedType* end_;
- AllocatedType buffer_[objectPerAllocation];
- };
-
- // disabled copy constructor and assignement operator.
- BatchAllocator(const BatchAllocator&);
- void operator=(const BatchAllocator&);
-
- static BatchInfo* allocateBatch(unsigned int objectsPerPage) {
- const unsigned int mallocSize =
- sizeof(BatchInfo) - sizeof(AllocatedType) * objectPerAllocation +
- sizeof(AllocatedType) * objectPerAllocation * objectsPerPage;
- BatchInfo* batch = static_cast<BatchInfo*>(malloc(mallocSize));
- batch->next_ = 0;
- batch->used_ = batch->buffer_;
- batch->end_ = batch->buffer_ + objectsPerPage;
- return batch;
- }
-
- BatchInfo* batches_;
- BatchInfo* currentBatch_;
- /// Head of a single linked list within the allocated space of freeed object
- AllocatedType* freeHead_;
- unsigned int objectsPerPage_;
-};
-
-} // namespace Json
-
-#endif // ifndef JSONCPP_DOC_INCLUDE_IMPLEMENTATION
-
-#endif // JSONCPP_BATCHALLOCATOR_H_INCLUDED
diff --git a/Utilities/cmjsoncpp/src/lib_json/json_internalarray.inl b/Utilities/cmjsoncpp/src/lib_json/json_internalarray.inl
deleted file mode 100644
index 9ee15e9db..000000000
--- a/Utilities/cmjsoncpp/src/lib_json/json_internalarray.inl
+++ /dev/null
@@ -1,360 +0,0 @@
-// Copyright 2007-2010 Baptiste Lepilleur
-// Distributed under MIT license, or public domain if desired and
-// recognized in your jurisdiction.
-// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
-
-// included by json_value.cpp
-
-namespace Json {
-
-// //////////////////////////////////////////////////////////////////
-// //////////////////////////////////////////////////////////////////
-// //////////////////////////////////////////////////////////////////
-// class ValueInternalArray
-// //////////////////////////////////////////////////////////////////
-// //////////////////////////////////////////////////////////////////
-// //////////////////////////////////////////////////////////////////
-
-ValueArrayAllocator::~ValueArrayAllocator() {}
-
-// //////////////////////////////////////////////////////////////////
-// class DefaultValueArrayAllocator
-// //////////////////////////////////////////////////////////////////
-#ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
-class DefaultValueArrayAllocator : public ValueArrayAllocator {
-public: // overridden from ValueArrayAllocator
- virtual ~DefaultValueArrayAllocator() {}
-
- virtual ValueInternalArray* newArray() { return new ValueInternalArray(); }
-
- virtual ValueInternalArray* newArrayCopy(const ValueInternalArray& other) {
- return new ValueInternalArray(other);
- }
-
- virtual void destructArray(ValueInternalArray* array) { delete array; }
-
- virtual void
- reallocateArrayPageIndex(Value**& indexes,
- ValueInternalArray::PageIndex& indexCount,
- ValueInternalArray::PageIndex minNewIndexCount) {
- ValueInternalArray::PageIndex newIndexCount = (indexCount * 3) / 2 + 1;
- if (minNewIndexCount > newIndexCount)
- newIndexCount = minNewIndexCount;
- void* newIndexes = realloc(indexes, sizeof(Value*) * newIndexCount);
- JSON_ASSERT_MESSAGE(newIndexes, "Couldn't realloc.");
- indexCount = newIndexCount;
- indexes = static_cast<Value**>(newIndexes);
- }
- virtual void releaseArrayPageIndex(Value** indexes,
- ValueInternalArray::PageIndex indexCount) {
- if (indexes)
- free(indexes);
- }
-
- virtual Value* allocateArrayPage() {
- return static_cast<Value*>(
- malloc(sizeof(Value) * ValueInternalArray::itemsPerPage));
- }
-
- virtual void releaseArrayPage(Value* value) {
- if (value)
- free(value);
- }
-};
-
-#else // #ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
-/// @todo make this thread-safe (lock when accessign batch allocator)
-class DefaultValueArrayAllocator : public ValueArrayAllocator {
-public: // overridden from ValueArrayAllocator
- virtual ~DefaultValueArrayAllocator() {}
-
- virtual ValueInternalArray* newArray() {
- ValueInternalArray* array = arraysAllocator_.allocate();
- new (array) ValueInternalArray(); // placement new
- return array;
- }
-
- virtual ValueInternalArray* newArrayCopy(const ValueInternalArray& other) {
- ValueInternalArray* array = arraysAllocator_.allocate();
- new (array) ValueInternalArray(other); // placement new
- return array;
- }
-
- virtual void destructArray(ValueInternalArray* array) {
- if (array) {
- array->~ValueInternalArray();
- arraysAllocator_.release(array);
- }
- }
-
- virtual void
- reallocateArrayPageIndex(Value**& indexes,
- ValueInternalArray::PageIndex& indexCount,
- ValueInternalArray::PageIndex minNewIndexCount) {
- ValueInternalArray::PageIndex newIndexCount = (indexCount * 3) / 2 + 1;
- if (minNewIndexCount > newIndexCount)
- newIndexCount = minNewIndexCount;
- void* newIndexes = realloc(indexes, sizeof(Value*) * newIndexCount);
- JSON_ASSERT_MESSAGE(newIndexes, "Couldn't realloc.");
- indexCount = newIndexCount;
- indexes = static_cast<Value**>(newIndexes);
- }
- virtual void releaseArrayPageIndex(Value** indexes,
- ValueInternalArray::PageIndex indexCount) {
- if (indexes)
- free(indexes);
- }
-
- virtual Value* allocateArrayPage() {
- return static_cast<Value*>(pagesAllocator_.allocate());
- }
-
- virtual void releaseArrayPage(Value* value) {
- if (value)
- pagesAllocator_.release(value);
- }
-
-private:
- BatchAllocator<ValueInternalArray, 1> arraysAllocator_;
- BatchAllocator<Value, ValueInternalArray::itemsPerPage> pagesAllocator_;
-};
-#endif // #ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
-
-static ValueArrayAllocator*& arrayAllocator() {
- static DefaultValueArrayAllocator defaultAllocator;
- static ValueArrayAllocator* arrayAllocator = &defaultAllocator;
- return arrayAllocator;
-}
-
-static struct DummyArrayAllocatorInitializer {
- DummyArrayAllocatorInitializer() {
- arrayAllocator(); // ensure arrayAllocator() statics are initialized before
- // main().
- }
-} dummyArrayAllocatorInitializer;
-
-// //////////////////////////////////////////////////////////////////
-// class ValueInternalArray
-// //////////////////////////////////////////////////////////////////
-bool ValueInternalArray::equals(const IteratorState& x,
- const IteratorState& other) {
- return x.array_ == other.array_ &&
- x.currentItemIndex_ == other.currentItemIndex_ &&
- x.currentPageIndex_ == other.currentPageIndex_;
-}
-
-void ValueInternalArray::increment(IteratorState& it) {
- JSON_ASSERT_MESSAGE(
- it.array_ && (it.currentPageIndex_ - it.array_->pages_) * itemsPerPage +
- it.currentItemIndex_ !=
- it.array_->size_,
- "ValueInternalArray::increment(): moving iterator beyond end");
- ++(it.currentItemIndex_);
- if (it.currentItemIndex_ == itemsPerPage) {
- it.currentItemIndex_ = 0;
- ++(it.currentPageIndex_);
- }
-}
-
-void ValueInternalArray::decrement(IteratorState& it) {
- JSON_ASSERT_MESSAGE(
- it.array_ && it.currentPageIndex_ == it.array_->pages_ &&
- it.currentItemIndex_ == 0,
- "ValueInternalArray::decrement(): moving iterator beyond end");
- if (it.currentItemIndex_ == 0) {
- it.currentItemIndex_ = itemsPerPage - 1;
- --(it.currentPageIndex_);
- } else {
- --(it.currentItemIndex_);
- }
-}
-
-Value& ValueInternalArray::unsafeDereference(const IteratorState& it) {
- return (*(it.currentPageIndex_))[it.currentItemIndex_];
-}
-
-Value& ValueInternalArray::dereference(const IteratorState& it) {
- JSON_ASSERT_MESSAGE(
- it.array_ && (it.currentPageIndex_ - it.array_->pages_) * itemsPerPage +
- it.currentItemIndex_ <
- it.array_->size_,
- "ValueInternalArray::dereference(): dereferencing invalid iterator");
- return unsafeDereference(it);
-}
-
-void ValueInternalArray::makeBeginIterator(IteratorState& it) const {
- it.array_ = const_cast<ValueInternalArray*>(this);
- it.currentItemIndex_ = 0;
- it.currentPageIndex_ = pages_;
-}
-
-void ValueInternalArray::makeIterator(IteratorState& it,
- ArrayIndex index) const {
- it.array_ = const_cast<ValueInternalArray*>(this);
- it.currentItemIndex_ = index % itemsPerPage;
- it.currentPageIndex_ = pages_ + index / itemsPerPage;
-}
-
-void ValueInternalArray::makeEndIterator(IteratorState& it) const {
- makeIterator(it, size_);
-}
-
-ValueInternalArray::ValueInternalArray() : pages_(0), size_(0), pageCount_(0) {}
-
-ValueInternalArray::ValueInternalArray(const ValueInternalArray& other)
- : pages_(0), size_(other.size_), pageCount_(0) {
- PageIndex minNewPages = other.size_ / itemsPerPage;
- arrayAllocator()->reallocateArrayPageIndex(pages_, pageCount_, minNewPages);
- JSON_ASSERT_MESSAGE(pageCount_ >= minNewPages,
- "ValueInternalArray::reserve(): bad reallocation");
- IteratorState itOther;
- other.makeBeginIterator(itOther);
- Value* value;
- for (ArrayIndex index = 0; index < size_; ++index, increment(itOther)) {
- if (index % itemsPerPage == 0) {
- PageIndex pageIndex = index / itemsPerPage;
- value = arrayAllocator()->allocateArrayPage();
- pages_[pageIndex] = value;
- }
- new (value) Value(dereference(itOther));
- }
-}
-
-ValueInternalArray& ValueInternalArray::operator=(ValueInternalArray other) {
- swap(other);
- return *this;
-}
-
-ValueInternalArray::~ValueInternalArray() {
- // destroy all constructed items
- IteratorState it;
- IteratorState itEnd;
- makeBeginIterator(it);
- makeEndIterator(itEnd);
- for (; !equals(it, itEnd); increment(it)) {
- Value* value = &dereference(it);
- value->~Value();
- }
- // release all pages
- PageIndex lastPageIndex = size_ / itemsPerPage;
- for (PageIndex pageIndex = 0; pageIndex < lastPageIndex; ++pageIndex)
- arrayAllocator()->releaseArrayPage(pages_[pageIndex]);
- // release pages index
- arrayAllocator()->releaseArrayPageIndex(pages_, pageCount_);
-}
-
-void ValueInternalArray::swap(ValueInternalArray& other) {
- Value** tempPages = pages_;
- pages_ = other.pages_;
- other.pages_ = tempPages;
- ArrayIndex tempSize = size_;
- size_ = other.size_;
- other.size_ = tempSize;
- PageIndex tempPageCount = pageCount_;
- pageCount_ = other.pageCount_;
- other.pageCount_ = tempPageCount;
-}
-
-void ValueInternalArray::clear() {
- ValueInternalArray dummy;
- swap(dummy);
-}
-
-void ValueInternalArray::resize(ArrayIndex newSize) {
- if (newSize == 0)
- clear();
- else if (newSize < size_) {
- IteratorState it;
- IteratorState itEnd;
- makeIterator(it, newSize);
- makeIterator(itEnd, size_);
- for (; !equals(it, itEnd); increment(it)) {
- Value* value = &dereference(it);
- value->~Value();
- }
- PageIndex pageIndex = (newSize + itemsPerPage - 1) / itemsPerPage;
- PageIndex lastPageIndex = size_ / itemsPerPage;
- for (; pageIndex < lastPageIndex; ++pageIndex)
- arrayAllocator()->releaseArrayPage(pages_[pageIndex]);
- size_ = newSize;
- } else if (newSize > size_)
- resolveReference(newSize);
-}
-
-void ValueInternalArray::makeIndexValid(ArrayIndex index) {
- // Need to enlarge page index ?
- if (index >= pageCount_ * itemsPerPage) {
- PageIndex minNewPages = (index + 1) / itemsPerPage;
- arrayAllocator()->reallocateArrayPageIndex(pages_, pageCount_, minNewPages);
- JSON_ASSERT_MESSAGE(pageCount_ >= minNewPages,
- "ValueInternalArray::reserve(): bad reallocation");
- }
-
- // Need to allocate new pages ?
- ArrayIndex nextPageIndex = (size_ % itemsPerPage) != 0
- ? size_ - (size_ % itemsPerPage) + itemsPerPage
- : size_;
- if (nextPageIndex <= index) {
- PageIndex pageIndex = nextPageIndex / itemsPerPage;
- PageIndex pageToAllocate = (index - nextPageIndex) / itemsPerPage + 1;
- for (; pageToAllocate-- > 0; ++pageIndex)
- pages_[pageIndex] = arrayAllocator()->allocateArrayPage();
- }
-
- // Initialize all new entries
- IteratorState it;
- IteratorState itEnd;
- makeIterator(it, size_);
- size_ = index + 1;
- makeIterator(itEnd, size_);
- for (; !equals(it, itEnd); increment(it)) {
- Value* value = &dereference(it);
- new (value) Value(); // Construct a default value using placement new
- }
-}
-
-Value& ValueInternalArray::resolveReference(ArrayIndex index) {
- if (index >= size_)
- makeIndexValid(index);
- return pages_[index / itemsPerPage][index % itemsPerPage];
-}
-
-Value* ValueInternalArray::find(ArrayIndex index) const {
- if (index >= size_)
- return 0;
- return &(pages_[index / itemsPerPage][index % itemsPerPage]);
-}
-
-ValueInternalArray::ArrayIndex ValueInternalArray::size() const {
- return size_;
-}
-
-int ValueInternalArray::distance(const IteratorState& x,
- const IteratorState& y) {
- return indexOf(y) - indexOf(x);
-}
-
-ValueInternalArray::ArrayIndex
-ValueInternalArray::indexOf(const IteratorState& iterator) {
- if (!iterator.array_)
- return ArrayIndex(-1);
- return ArrayIndex((iterator.currentPageIndex_ - iterator.array_->pages_) *
- itemsPerPage +
- iterator.currentItemIndex_);
-}
-
-int ValueInternalArray::compare(const ValueInternalArray& other) const {
- int sizeDiff(size_ - other.size_);
- if (sizeDiff != 0)
- return sizeDiff;
-
- for (ArrayIndex index = 0; index < size_; ++index) {
- int diff = pages_[index / itemsPerPage][index % itemsPerPage].compare(
- other.pages_[index / itemsPerPage][index % itemsPerPage]);
- if (diff != 0)
- return diff;
- }
- return 0;
-}
-
-} // namespace Json
diff --git a/Utilities/cmjsoncpp/src/lib_json/json_internalmap.inl b/Utilities/cmjsoncpp/src/lib_json/json_internalmap.inl
deleted file mode 100644
index ef3f3302d..000000000
--- a/Utilities/cmjsoncpp/src/lib_json/json_internalmap.inl
+++ /dev/null
@@ -1,473 +0,0 @@
-// Copyright 2007-2010 Baptiste Lepilleur
-// Distributed under MIT license, or public domain if desired and
-// recognized in your jurisdiction.
-// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
-
-// included by json_value.cpp
-
-namespace Json {
-
-// //////////////////////////////////////////////////////////////////
-// //////////////////////////////////////////////////////////////////
-// //////////////////////////////////////////////////////////////////
-// class ValueInternalMap
-// //////////////////////////////////////////////////////////////////
-// //////////////////////////////////////////////////////////////////
-// //////////////////////////////////////////////////////////////////
-
-/** \internal MUST be safely initialized using memset( this, 0,
- * sizeof(ValueInternalLink) );
- * This optimization is used by the fast allocator.
- */
-ValueInternalLink::ValueInternalLink() : previous_(0), next_(0) {}
-
-ValueInternalLink::~ValueInternalLink() {
- for (int index = 0; index < itemPerLink; ++index) {
- if (!items_[index].isItemAvailable()) {
- if (!items_[index].isMemberNameStatic())
- free(keys_[index]);
- } else
- break;
- }
-}
-
-ValueMapAllocator::~ValueMapAllocator() {}
-
-#ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
-class DefaultValueMapAllocator : public ValueMapAllocator {
-public: // overridden from ValueMapAllocator
- virtual ValueInternalMap* newMap() { return new ValueInternalMap(); }
-
- virtual ValueInternalMap* newMapCopy(const ValueInternalMap& other) {
- return new ValueInternalMap(other);
- }
-
- virtual void destructMap(ValueInternalMap* map) { delete map; }
-
- virtual ValueInternalLink* allocateMapBuckets(unsigned int size) {
- return new ValueInternalLink[size];
- }
-
- virtual void releaseMapBuckets(ValueInternalLink* links) { delete[] links; }
-
- virtual ValueInternalLink* allocateMapLink() {
- return new ValueInternalLink();
- }
-
- virtual void releaseMapLink(ValueInternalLink* link) { delete link; }
-};
-#else
-/// @todo make this thread-safe (lock when accessign batch allocator)
-class DefaultValueMapAllocator : public ValueMapAllocator {
-public: // overridden from ValueMapAllocator
- virtual ValueInternalMap* newMap() {
- ValueInternalMap* map = mapsAllocator_.allocate();
- new (map) ValueInternalMap(); // placement new
- return map;
- }
-
- virtual ValueInternalMap* newMapCopy(const ValueInternalMap& other) {
- ValueInternalMap* map = mapsAllocator_.allocate();
- new (map) ValueInternalMap(other); // placement new
- return map;
- }
-
- virtual void destructMap(ValueInternalMap* map) {
- if (map) {
- map->~ValueInternalMap();
- mapsAllocator_.release(map);
- }
- }
-
- virtual ValueInternalLink* allocateMapBuckets(unsigned int size) {
- return new ValueInternalLink[size];
- }
-
- virtual void releaseMapBuckets(ValueInternalLink* links) { delete[] links; }
-
- virtual ValueInternalLink* allocateMapLink() {
- ValueInternalLink* link = linksAllocator_.allocate();
- memset(link, 0, sizeof(ValueInternalLink));
- return link;
- }
-
- virtual void releaseMapLink(ValueInternalLink* link) {
- link->~ValueInternalLink();
- linksAllocator_.release(link);
- }
-
-private:
- BatchAllocator<ValueInternalMap, 1> mapsAllocator_;
- BatchAllocator<ValueInternalLink, 1> linksAllocator_;
-};
-#endif
-
-static ValueMapAllocator*& mapAllocator() {
- static DefaultValueMapAllocator defaultAllocator;
- static ValueMapAllocator* mapAllocator = &defaultAllocator;
- return mapAllocator;
-}
-
-static struct DummyMapAllocatorInitializer {
- DummyMapAllocatorInitializer() {
- mapAllocator(); // ensure mapAllocator() statics are initialized before
- // main().
- }
-} dummyMapAllocatorInitializer;
-
-// h(K) = value * K >> w ; with w = 32 & K prime w.r.t. 2^32.
-
-/*
-use linked list hash map.
-buckets array is a container.
-linked list element contains 6 key/values. (memory = (16+4) * 6 + 4 = 124)
-value have extra state: valid, available, deleted
-*/
-
-ValueInternalMap::ValueInternalMap()
- : buckets_(0), tailLink_(0), bucketsSize_(0), itemCount_(0) {}
-
-ValueInternalMap::ValueInternalMap(const ValueInternalMap& other)
- : buckets_(0), tailLink_(0), bucketsSize_(0), itemCount_(0) {
- reserve(other.itemCount_);
- IteratorState it;
- IteratorState itEnd;
- other.makeBeginIterator(it);
- other.makeEndIterator(itEnd);
- for (; !equals(it, itEnd); increment(it)) {
- bool isStatic;
- const char* memberName = key(it, isStatic);
- const Value& aValue = value(it);
- resolveReference(memberName, isStatic) = aValue;
- }
-}
-
-ValueInternalMap& ValueInternalMap::operator=(ValueInternalMap other) {
- swap(other);
- return *this;
-}
-
-ValueInternalMap::~ValueInternalMap() {
- if (buckets_) {
- for (BucketIndex bucketIndex = 0; bucketIndex < bucketsSize_;
- ++bucketIndex) {
- ValueInternalLink* link = buckets_[bucketIndex].next_;
- while (link) {
- ValueInternalLink* linkToRelease = link;
- link = link->next_;
- mapAllocator()->releaseMapLink(linkToRelease);
- }
- }
- mapAllocator()->releaseMapBuckets(buckets_);
- }
-}
-
-void ValueInternalMap::swap(ValueInternalMap& other) {
- ValueInternalLink* tempBuckets = buckets_;
- buckets_ = other.buckets_;
- other.buckets_ = tempBuckets;
- ValueInternalLink* tempTailLink = tailLink_;
- tailLink_ = other.tailLink_;
- other.tailLink_ = tempTailLink;
- BucketIndex tempBucketsSize = bucketsSize_;
- bucketsSize_ = other.bucketsSize_;
- other.bucketsSize_ = tempBucketsSize;
- BucketIndex tempItemCount = itemCount_;
- itemCount_ = other.itemCount_;
- other.itemCount_ = tempItemCount;
-}
-
-void ValueInternalMap::clear() {
- ValueInternalMap dummy;
- swap(dummy);
-}
-
-ValueInternalMap::BucketIndex ValueInternalMap::size() const {
- return itemCount_;
-}
-
-bool ValueInternalMap::reserveDelta(BucketIndex growth) {
- return reserve(itemCount_ + growth);
-}
-
-bool ValueInternalMap::reserve(BucketIndex newItemCount) {
- if (!buckets_ && newItemCount > 0) {
- buckets_ = mapAllocator()->allocateMapBuckets(1);
- bucketsSize_ = 1;
- tailLink_ = &buckets_[0];
- }
- // BucketIndex idealBucketCount = (newItemCount +
- // ValueInternalLink::itemPerLink) / ValueInternalLink::itemPerLink;
- return true;
-}
-
-const Value* ValueInternalMap::find(const char* key) const {
- if (!bucketsSize_)
- return 0;
- HashKey hashedKey = hash(key);
- BucketIndex bucketIndex = hashedKey % bucketsSize_;
- for (const ValueInternalLink* current = &buckets_[bucketIndex]; current != 0;
- current = current->next_) {
- for (BucketIndex index = 0; index < ValueInternalLink::itemPerLink;
- ++index) {
- if (current->items_[index].isItemAvailable())
- return 0;
- if (strcmp(key, current->keys_[index]) == 0)
- return &current->items_[index];
- }
- }
- return 0;
-}
-
-Value* ValueInternalMap::find(const char* key) {
- const ValueInternalMap* constThis = this;
- return const_cast<Value*>(constThis->find(key));
-}
-
-Value& ValueInternalMap::resolveReference(const char* key, bool isStatic) {
- HashKey hashedKey = hash(key);
- if (bucketsSize_) {
- BucketIndex bucketIndex = hashedKey % bucketsSize_;
- ValueInternalLink** previous = 0;
- BucketIndex index;
- for (ValueInternalLink* current = &buckets_[bucketIndex]; current != 0;
- previous = &current->next_, current = current->next_) {
- for (index = 0; index < ValueInternalLink::itemPerLink; ++index) {
- if (current->items_[index].isItemAvailable())
- return setNewItem(key, isStatic, current, index);
- if (strcmp(key, current->keys_[index]) == 0)
- return current->items_[index];
- }
- }
- }
-
- reserveDelta(1);
- return unsafeAdd(key, isStatic, hashedKey);
-}
-
-void ValueInternalMap::remove(const char* key) {
- HashKey hashedKey = hash(key);
- if (!bucketsSize_)
- return;
- BucketIndex bucketIndex = hashedKey % bucketsSize_;
- for (ValueInternalLink* link = &buckets_[bucketIndex]; link != 0;
- link = link->next_) {
- BucketIndex index;
- for (index = 0; index < ValueInternalLink::itemPerLink; ++index) {
- if (link->items_[index].isItemAvailable())
- return;
- if (strcmp(key, link->keys_[index]) == 0) {
- doActualRemove(link, index, bucketIndex);
- return;
- }
- }
- }
-}
-
-void ValueInternalMap::doActualRemove(ValueInternalLink* link,
- BucketIndex index,
- BucketIndex bucketIndex) {
- // find last item of the bucket and swap it with the 'removed' one.
- // set removed items flags to 'available'.
- // if last page only contains 'available' items, then desallocate it (it's
- // empty)
- ValueInternalLink*& lastLink = getLastLinkInBucket(index);
- BucketIndex lastItemIndex = 1; // a link can never be empty, so start at 1
- for (; lastItemIndex < ValueInternalLink::itemPerLink;
- ++lastItemIndex) // may be optimized with dicotomic search
- {
- if (lastLink->items_[lastItemIndex].isItemAvailable())
- break;
- }
-
- BucketIndex lastUsedIndex = lastItemIndex - 1;
- Value* valueToDelete = &link->items_[index];
- Value* valueToPreserve = &lastLink->items_[lastUsedIndex];
- if (valueToDelete != valueToPreserve)
- valueToDelete->swap(*valueToPreserve);
- if (lastUsedIndex == 0) // page is now empty
- { // remove it from bucket linked list and delete it.
- ValueInternalLink* linkPreviousToLast = lastLink->previous_;
- if (linkPreviousToLast != 0) // can not deleted bucket link.
- {
- mapAllocator()->releaseMapLink(lastLink);
- linkPreviousToLast->next_ = 0;
- lastLink = linkPreviousToLast;
- }
- } else {
- Value dummy;
- valueToPreserve->swap(dummy); // restore deleted to default Value.
- valueToPreserve->setItemUsed(false);
- }
- --itemCount_;
-}
-
-ValueInternalLink*&
-ValueInternalMap::getLastLinkInBucket(BucketIndex bucketIndex) {
- if (bucketIndex == bucketsSize_ - 1)
- return tailLink_;
- ValueInternalLink*& previous = buckets_[bucketIndex + 1].previous_;
- if (!previous)
- previous = &buckets_[bucketIndex];
- return previous;
-}
-
-Value& ValueInternalMap::setNewItem(const char* key,
- bool isStatic,
- ValueInternalLink* link,
- BucketIndex index) {
- char* duplicatedKey = makeMemberName(key);
- ++itemCount_;
- link->keys_[index] = duplicatedKey;
- link->items_[index].setItemUsed();
- link->items_[index].setMemberNameIsStatic(isStatic);
- return link->items_[index]; // items already default constructed.
-}
-
-Value&
-ValueInternalMap::unsafeAdd(const char* key, bool isStatic, HashKey hashedKey) {
- JSON_ASSERT_MESSAGE(bucketsSize_ > 0,
- "ValueInternalMap::unsafeAdd(): internal logic error.");
- BucketIndex bucketIndex = hashedKey % bucketsSize_;
- ValueInternalLink*& previousLink = getLastLinkInBucket(bucketIndex);
- ValueInternalLink* link = previousLink;
- BucketIndex index;
- for (index = 0; index < ValueInternalLink::itemPerLink; ++index) {
- if (link->items_[index].isItemAvailable())
- break;
- }
- if (index == ValueInternalLink::itemPerLink) // need to add a new page
- {
- ValueInternalLink* newLink = mapAllocator()->allocateMapLink();
- index = 0;
- link->next_ = newLink;
- previousLink = newLink;
- link = newLink;
- }
- return setNewItem(key, isStatic, link, index);
-}
-
-ValueInternalMap::HashKey ValueInternalMap::hash(const char* key) const {
- HashKey hash = 0;
- while (*key)
- hash += *key++ * 37;
- return hash;
-}
-
-int ValueInternalMap::compare(const ValueInternalMap& other) const {
- int sizeDiff(itemCount_ - other.itemCount_);
- if (sizeDiff != 0)
- return sizeDiff;
- // Strict order guaranty is required. Compare all keys FIRST, then compare
- // values.
- IteratorState it;
- IteratorState itEnd;
- makeBeginIterator(it);
- makeEndIterator(itEnd);
- for (; !equals(it, itEnd); increment(it)) {
- if (!other.find(key(it)))
- return 1;
- }
-
- // All keys are equals, let's compare values
- makeBeginIterator(it);
- for (; !equals(it, itEnd); increment(it)) {
- const Value* otherValue = other.find(key(it));
- int valueDiff = value(it).compare(*otherValue);
- if (valueDiff != 0)
- return valueDiff;
- }
- return 0;
-}
-
-void ValueInternalMap::makeBeginIterator(IteratorState& it) const {
- it.map_ = const_cast<ValueInternalMap*>(this);
- it.bucketIndex_ = 0;
- it.itemIndex_ = 0;
- it.link_ = buckets_;
-}
-
-void ValueInternalMap::makeEndIterator(IteratorState& it) const {
- it.map_ = const_cast<ValueInternalMap*>(this);
- it.bucketIndex_ = bucketsSize_;
- it.itemIndex_ = 0;
- it.link_ = 0;
-}
-
-bool ValueInternalMap::equals(const IteratorState& x,
- const IteratorState& other) {
- return x.map_ == other.map_ && x.bucketIndex_ == other.bucketIndex_ &&
- x.link_ == other.link_ && x.itemIndex_ == other.itemIndex_;
-}
-
-void ValueInternalMap::incrementBucket(IteratorState& iterator) {
- ++iterator.bucketIndex_;
- JSON_ASSERT_MESSAGE(
- iterator.bucketIndex_ <= iterator.map_->bucketsSize_,
- "ValueInternalMap::increment(): attempting to iterate beyond end.");
- if (iterator.bucketIndex_ == iterator.map_->bucketsSize_)
- iterator.link_ = 0;
- else
- iterator.link_ = &(iterator.map_->buckets_[iterator.bucketIndex_]);
- iterator.itemIndex_ = 0;
-}
-
-void ValueInternalMap::increment(IteratorState& iterator) {
- JSON_ASSERT_MESSAGE(iterator.map_,
- "Attempting to iterator using invalid iterator.");
- ++iterator.itemIndex_;
- if (iterator.itemIndex_ == ValueInternalLink::itemPerLink) {
- JSON_ASSERT_MESSAGE(
- iterator.link_ != 0,
- "ValueInternalMap::increment(): attempting to iterate beyond end.");
- iterator.link_ = iterator.link_->next_;
- if (iterator.link_ == 0)
- incrementBucket(iterator);
- } else if (iterator.link_->items_[iterator.itemIndex_].isItemAvailable()) {
- incrementBucket(iterator);
- }
-}
-
-void ValueInternalMap::decrement(IteratorState& iterator) {
- if (iterator.itemIndex_ == 0) {
- JSON_ASSERT_MESSAGE(iterator.map_,
- "Attempting to iterate using invalid iterator.");
- if (iterator.link_ == &iterator.map_->buckets_[iterator.bucketIndex_]) {
- JSON_ASSERT_MESSAGE(iterator.bucketIndex_ > 0,
- "Attempting to iterate beyond beginning.");
- --(iterator.bucketIndex_);
- }
- iterator.link_ = iterator.link_->previous_;
- iterator.itemIndex_ = ValueInternalLink::itemPerLink - 1;
- }
-}
-
-const char* ValueInternalMap::key(const IteratorState& iterator) {
- JSON_ASSERT_MESSAGE(iterator.link_,
- "Attempting to iterate using invalid iterator.");
- return iterator.link_->keys_[iterator.itemIndex_];
-}
-
-const char* ValueInternalMap::key(const IteratorState& iterator,
- bool& isStatic) {
- JSON_ASSERT_MESSAGE(iterator.link_,
- "Attempting to iterate using invalid iterator.");
- isStatic = iterator.link_->items_[iterator.itemIndex_].isMemberNameStatic();
- return iterator.link_->keys_[iterator.itemIndex_];
-}
-
-Value& ValueInternalMap::value(const IteratorState& iterator) {
- JSON_ASSERT_MESSAGE(iterator.link_,
- "Attempting to iterate using invalid iterator.");
- return iterator.link_->items_[iterator.itemIndex_];
-}
-
-int ValueInternalMap::distance(const IteratorState& x, const IteratorState& y) {
- int offset = 0;
- IteratorState it = x;
- while (!equals(it, y))
- increment(it);
- return offset;
-}
-
-} // namespace Json
diff --git a/Utilities/cmjsoncpp/src/lib_json/json_reader.cpp b/Utilities/cmjsoncpp/src/lib_json/json_reader.cpp
index 7b338285c..0249cc9f1 100644
--- a/Utilities/cmjsoncpp/src/lib_json/json_reader.cpp
+++ b/Utilities/cmjsoncpp/src/lib_json/json_reader.cpp
@@ -1,4 +1,5 @@
-// Copyright 2007-2011 Baptiste Lepilleur
+// Copyright 2007-2011 Baptiste Lepilleur and The JsonCpp Authors
+// Copyright (C) 2016 InfoTeCS JSC. All rights reserved.
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
@@ -14,18 +15,51 @@
#include <assert.h>
#include <string.h>
#include <istream>
-
-#if defined(_MSC_VER) && _MSC_VER < 1500 // VC++ 8.0 and below
+#include <sstream>
+#include <memory>
+#include <set>
+#include <limits>
+
+#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
+
+#if defined(__QNXNTO__)
+#define sscanf std::sscanf
+#endif
#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
// 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
+#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()
+
namespace Json {
+#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
+typedef std::unique_ptr<CharReader> CharReaderPtr;
+#else
+typedef std::auto_ptr<CharReader> CharReaderPtr;
+#endif
+
// Implementation of class Features
// ////////////////////////////////
@@ -47,24 +81,7 @@ Features Features::strictMode() {
// Implementation of class Reader
// ////////////////////////////////
-static inline bool in(Reader::Char c,
- Reader::Char c1,
- Reader::Char c2,
- Reader::Char c3,
- Reader::Char c4) {
- return c == c1 || c == c2 || c == c3 || c == c4;
-}
-
-static inline bool in(Reader::Char c,
- Reader::Char c1,
- Reader::Char c2,
- Reader::Char c3,
- Reader::Char c4,
- Reader::Char c5) {
- return c == c1 || c == c2 || c == c3 || c == c4 || c == c5;
-}
-
-static bool containsNewLine(Reader::Location begin, Reader::Location end) {
+bool Reader::containsNewLine(Reader::Location begin, Reader::Location end) {
for (; begin < end; ++begin)
if (*begin == '\n' || *begin == '\r')
return true;
@@ -86,7 +103,7 @@ Reader::Reader(const Features& features)
bool
Reader::parse(const std::string& document, Value& root, bool collectComments) {
- document_ = document;
+ document_.assign(document.begin(), document.end());
const char* begin = document_.c_str();
const char* end = begin + document_.length();
return parse(begin, end, root, collectComments);
@@ -98,11 +115,11 @@ bool Reader::parse(std::istream& sin, Value& root, bool collectComments) {
// Those would allow streamed input from a file, if parse() were a
// template function.
- // Since std::string is reference-counted, this at least does not
+ // Since JSONCPP_STRING is reference-counted, this at least does not
// create an extra copy.
- std::string doc;
+ JSONCPP_STRING doc;
std::getline(sin, doc, (char)EOF);
- return parse(doc, root, collectComments);
+ return parse(doc.data(), doc.data() + doc.size(), root, collectComments);
}
bool Reader::parse(const char* beginDoc,
@@ -119,7 +136,7 @@ bool Reader::parse(const char* beginDoc,
current_ = begin_;
lastValueEnd_ = 0;
lastValue_ = 0;
- commentsBefore_ = "";
+ commentsBefore_.clear();
errors_.clear();
while (!nodes_.empty())
nodes_.pop();
@@ -147,21 +164,18 @@ 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().");
+
Token token;
skipCommentTokens(token);
bool successful = true;
if (collectComments_ && !commentsBefore_.empty()) {
- // Remove newline characters at the end of the comments
- size_t lastNonNewline = commentsBefore_.find_last_not_of("\r\n");
- if (lastNonNewline != std::string::npos) {
- commentsBefore_.erase(lastNonNewline + 1);
- } else {
- commentsBefore_.clear();
- }
-
currentValue().setComment(commentsBefore_, commentBefore);
- commentsBefore_ = "";
+ commentsBefore_.clear();
}
switch (token.type_) {
@@ -180,31 +194,42 @@ bool Reader::readValue() {
successful = decodeString(token);
break;
case tokenTrue:
- currentValue() = true;
+ {
+ Value v(true);
+ currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
+ }
break;
case tokenFalse:
- currentValue() = false;
+ {
+ Value v(false);
+ currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
+ }
break;
case tokenNull:
- currentValue() = Value();
+ {
+ Value v;
+ currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
+ }
break;
case tokenArraySeparator:
+ case tokenObjectEnd:
+ case tokenArrayEnd:
if (features_.allowDroppedNullPlaceholders_) {
// "Un-read" the current token and mark the current value as a null
// token.
current_--;
- currentValue() = Value();
+ Value v;
+ currentValue().swapPayload(v);
currentValue().setOffsetStart(current_ - begin_ - 1);
currentValue().setOffsetLimit(current_ - begin_);
break;
- }
- // Else, fall through...
+ } // Else, fall through...
default:
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
@@ -229,13 +254,6 @@ void Reader::skipCommentTokens(Token& token) {
}
}
-bool Reader::expectToken(TokenType type, Token& token, const char* message) {
- readToken(token);
- if (token.type_ != type)
- return addError(message, token);
- return true;
-}
-
bool Reader::readToken(Token& token) {
skipSpaces();
token.start_ = current_;
@@ -351,19 +369,39 @@ bool Reader::readComment() {
return true;
}
+JSONCPP_STRING Reader::normalizeEOL(Reader::Location begin, Reader::Location end) {
+ JSONCPP_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 Mac EOL
+ normalized += '\n';
+ } else {
+ normalized += c;
+ }
+ }
+ return normalized;
+}
+
void
Reader::addComment(Location begin, Location end, CommentPlacement placement) {
assert(collectComments_);
+ const JSONCPP_STRING& normalized = normalizeEOL(begin, end);
if (placement == commentAfterOnSameLine) {
assert(lastValue_ != 0);
- lastValue_->setComment(std::string(begin, end), placement);
+ lastValue_->setComment(normalized, placement);
} else {
- commentsBefore_ += std::string(begin, end);
+ commentsBefore_ += normalized;
}
}
bool Reader::readCStyleComment() {
- while (current_ != end_) {
+ while ((current_ + 1) < end_) {
Char c = getNextChar();
if (c == '*' && *current_ == '/')
break;
@@ -374,23 +412,43 @@ bool Reader::readCStyleComment() {
bool Reader::readCppStyleComment() {
while (current_ != end_) {
Char c = getNextChar();
- if (c == '\r' || c == '\n')
+ if (c == '\n')
break;
+ if (c == '\r') {
+ // Consume DOS EOL. It will be normalized in addComment.
+ if (current_ != end_ && *current_ == '\n')
+ getNextChar();
+ // Break on Moc OS 9 EOL.
+ break;
+ }
}
return true;
}
void Reader::readNumber() {
- while (current_ != end_) {
- if (!(*current_ >= '0' && *current_ <= '9') &&
- !in(*current_, '.', 'e', 'E', '+', '-'))
- break;
- ++current_;
+ const char *p = current_;
+ char c = '0'; // stopgap for already consumed character
+ // integral part
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : '\0';
+ // fractional part
+ if (c == '.') {
+ c = (current_ = p) < end_ ? *p++ : '\0';
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : '\0';
+ }
+ // exponential part
+ if (c == 'e' || c == 'E') {
+ c = (current_ = p) < end_ ? *p++ : '\0';
+ if (c == '+' || c == '-')
+ c = (current_ = p) < end_ ? *p++ : '\0';
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : '\0';
}
}
bool Reader::readString() {
- Char c = 0;
+ Char c = '\0';
while (current_ != end_) {
c = getNextChar();
if (c == '\\')
@@ -403,8 +461,9 @@ bool Reader::readString() {
bool Reader::readObject(Token& tokenStart) {
Token tokenName;
- std::string name;
- currentValue() = Value(objectValue);
+ JSONCPP_STRING name;
+ Value init(objectValue);
+ currentValue().swapPayload(init);
currentValue().setOffsetStart(tokenStart.start_ - begin_);
while (readToken(tokenName)) {
bool initialTokenOk = true;
@@ -414,7 +473,7 @@ bool Reader::readObject(Token& tokenStart) {
break;
if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
return true;
- name = "";
+ name.clear();
if (tokenName.type_ == tokenString) {
if (!decodeString(tokenName, name))
return recoverFromError(tokenObjectEnd);
@@ -422,7 +481,7 @@ bool Reader::readObject(Token& tokenStart) {
Value numberName;
if (!decodeNumber(tokenName, numberName))
return recoverFromError(tokenObjectEnd);
- name = numberName.asString();
+ name = JSONCPP_STRING(numberName.asCString());
} else {
break;
}
@@ -457,10 +516,11 @@ bool Reader::readObject(Token& tokenStart) {
}
bool Reader::readArray(Token& tokenStart) {
- currentValue() = Value(arrayValue);
+ Value init(arrayValue);
+ currentValue().swapPayload(init);
currentValue().setOffsetStart(tokenStart.start_ - begin_);
skipSpaces();
- if (*current_ == ']') // empty array
+ if (current_ != end_ && *current_ == ']') // empty array
{
Token endArray;
readToken(endArray);
@@ -497,20 +557,1021 @@ bool Reader::decodeNumber(Token& token) {
Value decoded;
if (!decodeNumber(token, decoded))
return false;
- currentValue() = decoded;
+ currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool Reader::decodeNumber(Token& token, Value& decoded) {
- bool isDouble = false;
- for (Location inspect = token.start_; inspect != token.end_; ++inspect) {
- isDouble = isDouble || in(*inspect, '.', 'e', 'E', '+') ||
- (*inspect == '-' && inspect != token.start_);
+ // Attempts to parse the number as an integer. If the number is
+ // 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)
+ ++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::maxLargestInt) + 1
+ : Value::maxLargestUInt;
+ Value::LargestUInt threshold = maxIntegerValue / 10;
+ 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'));
+ 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
+ // 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) {
+ return decodeDouble(token, decoded);
+ }
+ }
+ value = value * 10 + digit;
+ }
+ if (isNegative && value == maxIntegerValue)
+ decoded = Value::minLargestInt;
+ else if (isNegative)
+ decoded = -Value::LargestInt(value);
+ else if (value <= Value::LargestUInt(Value::maxInt))
+ decoded = Value::LargestInt(value);
+ else
+ decoded = value;
+ return true;
+}
+
+bool Reader::decodeDouble(Token& token) {
+ Value decoded;
+ if (!decodeDouble(token, decoded))
+ return false;
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool Reader::decodeDouble(Token& token, Value& decoded) {
+ double value = 0;
+ JSONCPP_STRING buffer(token.start_, token.end_);
+ JSONCPP_ISTRINGSTREAM is(buffer);
+ if (!(is >> value))
+ return addError("'" + JSONCPP_STRING(token.start_, token.end_) +
+ "' is not a number.",
+ token);
+ decoded = value;
+ return true;
+}
+
+bool Reader::decodeString(Token& token) {
+ JSONCPP_STRING decoded_string;
+ if (!decodeString(token, decoded_string))
+ return false;
+ Value decoded(decoded_string);
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool Reader::decodeString(Token& token, JSONCPP_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 '"'
+ while (current != end) {
+ Char c = *current++;
+ if (c == '"')
+ break;
+ else if (c == '\\') {
+ if (current == end)
+ return addError("Empty escape sequence in string", token, current);
+ Char escape = *current++;
+ switch (escape) {
+ case '"':
+ decoded += '"';
+ break;
+ case '/':
+ decoded += '/';
+ break;
+ case '\\':
+ decoded += '\\';
+ break;
+ case 'b':
+ decoded += '\b';
+ break;
+ case 'f':
+ decoded += '\f';
+ break;
+ case 'n':
+ decoded += '\n';
+ break;
+ case 'r':
+ decoded += '\r';
+ break;
+ case 't':
+ decoded += '\t';
+ break;
+ case 'u': {
+ unsigned int unicode;
+ if (!decodeUnicodeCodePoint(token, current, end, unicode))
+ return false;
+ decoded += codePointToUTF8(unicode);
+ } break;
+ default:
+ return addError("Bad escape sequence in string", token, current);
+ }
+ } else {
+ decoded += c;
+ }
+ }
+ return true;
+}
+
+bool Reader::decodeUnicodeCodePoint(Token& token,
+ Location& current,
+ Location end,
+ unsigned int& unicode) {
+
+ if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
+ return false;
+ if (unicode >= 0xD800 && unicode <= 0xDBFF) {
+ // surrogate pairs
+ if (end - current < 6)
+ return addError(
+ "additional six characters expected to parse unicode surrogate pair.",
+ token,
+ current);
+ unsigned int surrogatePair;
+ if (*(current++) == '\\' && *(current++) == 'u') {
+ if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
+ unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
+ } else
+ return false;
+ } else
+ return addError("expecting another \\u token to begin the second half of "
+ "a unicode surrogate pair",
+ token,
+ current);
+ }
+ return true;
+}
+
+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,
+ current);
+ int unicode = 0;
+ for (int index = 0; index < 4; ++index) {
+ Char c = *current++;
+ unicode *= 16;
+ if (c >= '0' && c <= '9')
+ unicode += c - '0';
+ else if (c >= 'a' && c <= 'f')
+ unicode += c - 'a' + 10;
+ else if (c >= 'A' && c <= 'F')
+ unicode += c - 'A' + 10;
+ else
+ return addError(
+ "Bad unicode escape sequence in string: hexadecimal digit expected.",
+ token,
+ current);
+ }
+ ret_unicode = static_cast<unsigned int>(unicode);
+ return true;
+}
+
+bool
+Reader::addError(const JSONCPP_STRING& message, Token& token, Location extra) {
+ ErrorInfo info;
+ info.token_ = token;
+ info.message_ = message;
+ info.extra_ = extra;
+ errors_.push_back(info);
+ return false;
+}
+
+bool Reader::recoverFromError(TokenType skipUntilToken) {
+ size_t const errorCount = errors_.size();
+ Token skip;
+ for (;;) {
+ if (!readToken(skip))
+ errors_.resize(errorCount); // discard errors caused by recovery
+ if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
+ break;
+ }
+ errors_.resize(errorCount);
+ return false;
+}
+
+bool Reader::addErrorAndRecover(const JSONCPP_STRING& message,
+ Token& token,
+ TokenType skipUntilToken) {
+ addError(message, token);
+ return recoverFromError(skipUntilToken);
+}
+
+Value& Reader::currentValue() { return *(nodes_.top()); }
+
+Reader::Char Reader::getNextChar() {
+ if (current_ == end_)
+ return 0;
+ return *current_++;
+}
+
+void Reader::getLocationLineAndColumn(Location location,
+ int& line,
+ int& column) const {
+ Location current = begin_;
+ Location lastLineStart = current;
+ line = 0;
+ while (current < location && current != end_) {
+ Char c = *current++;
+ if (c == '\r') {
+ if (*current == '\n')
+ ++current;
+ lastLineStart = current;
+ ++line;
+ } else if (c == '\n') {
+ lastLineStart = current;
+ ++line;
+ }
+ }
+ // column & line start at 1
+ column = int(location - lastLineStart) + 1;
+ ++line;
+}
+
+JSONCPP_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);
+ return buffer;
+}
+
+// Deprecated. Preserved for backward compatibility
+JSONCPP_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;
+ formattedMessage +=
+ "* " + getLocationLineAndColumn(error.token_.start_) + "\n";
+ formattedMessage += " " + error.message_ + "\n";
+ if (error.extra_)
+ formattedMessage +=
+ "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
+ }
+ return formattedMessage;
+}
+
+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;
+ Reader::StructuredError structured;
+ structured.offset_start = error.token_.start_ - begin_;
+ structured.offset_limit = error.token_.end_ - begin_;
+ structured.message = error.message_;
+ allErrors.push_back(structured);
+ }
+ return allErrors;
+}
+
+bool Reader::pushError(const Value& value, const JSONCPP_STRING& message) {
+ ptrdiff_t const 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 Reader::pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra) {
+ ptrdiff_t const 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 Reader::good() const {
+ return !errors_.size();
+}
+
+// exact copy of Features
+class OurFeatures {
+public:
+ static OurFeatures all();
+ bool allowComments_;
+ bool strictRoot_;
+ bool allowDroppedNullPlaceholders_;
+ bool allowNumericKeys_;
+ bool allowSingleQuotes_;
+ bool failIfExtra_;
+ bool rejectDupKeys_;
+ bool allowSpecialFloats_;
+ int stackLimit_;
+}; // OurFeatures
+
+// exact copy of Implementation of class Features
+// ////////////////////////////////
+
+OurFeatures OurFeatures::all() { return OurFeatures(); }
+
+// Implementation of class Reader
+// ////////////////////////////////
+
+// exact copy of Reader, renamed to OurReader
+class OurReader {
+public:
+ typedef char Char;
+ typedef const Char* Location;
+ struct StructuredError {
+ ptrdiff_t offset_start;
+ ptrdiff_t offset_limit;
+ JSONCPP_STRING message;
+ };
+
+ OurReader(OurFeatures const& features);
+ bool parse(const char* beginDoc,
+ const char* endDoc,
+ Value& root,
+ bool collectComments = true);
+ JSONCPP_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
+
+ enum TokenType {
+ tokenEndOfStream = 0,
+ tokenObjectBegin,
+ tokenObjectEnd,
+ tokenArrayBegin,
+ tokenArrayEnd,
+ tokenString,
+ tokenNumber,
+ tokenTrue,
+ tokenFalse,
+ tokenNull,
+ tokenNaN,
+ tokenPosInf,
+ tokenNegInf,
+ tokenArraySeparator,
+ tokenMemberSeparator,
+ tokenComment,
+ tokenError
+ };
+
+ class Token {
+ public:
+ TokenType type_;
+ Location start_;
+ Location end_;
+ };
+
+ class ErrorInfo {
+ public:
+ Token token_;
+ JSONCPP_STRING message_;
+ Location extra_;
+ };
+
+ typedef std::deque<ErrorInfo> Errors;
+
+ bool readToken(Token& token);
+ void skipSpaces();
+ bool match(Location pattern, int patternLength);
+ bool readComment();
+ bool readCStyleComment();
+ bool readCppStyleComment();
+ bool readString();
+ bool readStringSingleQuote();
+ bool readNumber(bool checkInf);
+ bool readValue();
+ bool readObject(Token& token);
+ bool readArray(Token& token);
+ bool decodeNumber(Token& token);
+ bool decodeNumber(Token& token, Value& decoded);
+ bool decodeString(Token& token);
+ bool decodeString(Token& token, JSONCPP_STRING& decoded);
+ bool decodeDouble(Token& token);
+ bool decodeDouble(Token& token, Value& decoded);
+ 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 recoverFromError(TokenType skipUntilToken);
+ bool addErrorAndRecover(const JSONCPP_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 addComment(Location begin, Location end, CommentPlacement placement);
+ void skipCommentTokens(Token& token);
+
+ static JSONCPP_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_;
+
+ OurFeatures const features_;
+ bool collectComments_;
+}; // 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;
+}
+
+OurReader::OurReader(OurFeatures const& features)
+ : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
+ lastValue_(), commentsBefore_(),
+ features_(features), collectComments_() {
+}
+
+bool OurReader::parse(const char* beginDoc,
+ const char* endDoc,
+ Value& root,
+ bool collectComments) {
+ if (!features_.allowComments_) {
+ collectComments = false;
+ }
+
+ begin_ = beginDoc;
+ end_ = endDoc;
+ collectComments_ = collectComments;
+ current_ = begin_;
+ lastValueEnd_ = 0;
+ lastValue_ = 0;
+ commentsBefore_.clear();
+ errors_.clear();
+ while (!nodes_.empty())
+ nodes_.pop();
+ nodes_.push(&root);
+
+ bool successful = readValue();
+ 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 (collectComments_ && !commentsBefore_.empty())
+ root.setComment(commentsBefore_, commentAfter);
+ if (features_.strictRoot_) {
+ if (!root.isArray() && !root.isObject()) {
+ // Set error location to start of doc, ideally should be first token found
+ // in doc
+ token.type_ = tokenError;
+ token.start_ = beginDoc;
+ token.end_ = endDoc;
+ addError(
+ "A valid JSON document must be either an array or an object value.",
+ token);
+ return false;
+ }
+ }
+ return successful;
+}
+
+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().");
+ Token token;
+ skipCommentTokens(token);
+ bool successful = true;
+
+ if (collectComments_ && !commentsBefore_.empty()) {
+ currentValue().setComment(commentsBefore_, commentBefore);
+ commentsBefore_.clear();
+ }
+
+ switch (token.type_) {
+ case tokenObjectBegin:
+ successful = readObject(token);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ case tokenArrayBegin:
+ successful = readArray(token);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ case tokenNumber:
+ successful = decodeNumber(token);
+ break;
+ case tokenString:
+ successful = decodeString(token);
+ break;
+ case tokenTrue:
+ {
+ Value v(true);
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenFalse:
+ {
+ Value v(false);
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenNull:
+ {
+ Value v;
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ 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:
+ {
+ Value v(std::numeric_limits<double>::infinity());
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenNegInf:
+ {
+ Value v(-std::numeric_limits<double>::infinity());
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ }
+ break;
+ case tokenArraySeparator:
+ case tokenObjectEnd:
+ case tokenArrayEnd:
+ if (features_.allowDroppedNullPlaceholders_) {
+ // "Un-read" the current token and mark the current value as a null
+ // token.
+ current_--;
+ Value v;
+ currentValue().swapPayload(v);
+ currentValue().setOffsetStart(current_ - begin_ - 1);
+ currentValue().setOffsetLimit(current_ - begin_);
+ break;
+ } // else, fall through ...
+ default:
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return addError("Syntax error: value, object or array expected.", token);
+ }
+
+ if (collectComments_) {
+ lastValueEnd_ = current_;
+ lastValue_ = &currentValue();
+ }
+
+ return successful;
+}
+
+void OurReader::skipCommentTokens(Token& token) {
+ if (features_.allowComments_) {
+ do {
+ readToken(token);
+ } while (token.type_ == tokenComment);
+ } else {
+ readToken(token);
+ }
+}
+
+bool OurReader::readToken(Token& token) {
+ skipSpaces();
+ token.start_ = current_;
+ Char c = getNextChar();
+ bool ok = true;
+ switch (c) {
+ case '{':
+ token.type_ = tokenObjectBegin;
+ break;
+ case '}':
+ token.type_ = tokenObjectEnd;
+ break;
+ case '[':
+ token.type_ = tokenArrayBegin;
+ break;
+ case ']':
+ token.type_ = tokenArrayEnd;
+ break;
+ case '"':
+ token.type_ = tokenString;
+ ok = readString();
+ break;
+ case '\'':
+ if (features_.allowSingleQuotes_) {
+ token.type_ = tokenString;
+ ok = readStringSingleQuote();
+ break;
+ } // else continue
+ case '/':
+ token.type_ = tokenComment;
+ ok = readComment();
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ token.type_ = tokenNumber;
+ readNumber(false);
+ break;
+ case '-':
+ if (readNumber(true)) {
+ token.type_ = tokenNumber;
+ } else {
+ token.type_ = tokenNegInf;
+ ok = features_.allowSpecialFloats_ && match("nfinity", 7);
+ }
+ break;
+ case 't':
+ token.type_ = tokenTrue;
+ ok = match("rue", 3);
+ break;
+ case 'f':
+ token.type_ = tokenFalse;
+ ok = match("alse", 4);
+ break;
+ case 'n':
+ token.type_ = tokenNull;
+ ok = match("ull", 3);
+ break;
+ case 'N':
+ if (features_.allowSpecialFloats_) {
+ token.type_ = tokenNaN;
+ ok = match("aN", 2);
+ } else {
+ ok = false;
+ }
+ break;
+ case 'I':
+ if (features_.allowSpecialFloats_) {
+ token.type_ = tokenPosInf;
+ ok = match("nfinity", 7);
+ } else {
+ ok = false;
+ }
+ break;
+ case ',':
+ token.type_ = tokenArraySeparator;
+ break;
+ case ':':
+ token.type_ = tokenMemberSeparator;
+ break;
+ case 0:
+ token.type_ = tokenEndOfStream;
+ break;
+ default:
+ ok = false;
+ break;
}
- if (isDouble)
- return decodeDouble(token, decoded);
+ if (!ok)
+ token.type_ = tokenError;
+ token.end_ = current_;
+ return true;
+}
+
+void OurReader::skipSpaces() {
+ while (current_ != end_) {
+ Char c = *current_;
+ if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
+ ++current_;
+ else
+ break;
+ }
+}
+
+bool OurReader::match(Location pattern, int patternLength) {
+ if (end_ - current_ < patternLength)
+ return false;
+ int index = patternLength;
+ while (index--)
+ if (current_[index] != pattern[index])
+ return false;
+ current_ += patternLength;
+ return true;
+}
+
+bool OurReader::readComment() {
+ Location commentBegin = current_ - 1;
+ Char c = getNextChar();
+ bool successful = false;
+ if (c == '*')
+ successful = readCStyleComment();
+ else if (c == '/')
+ successful = readCppStyleComment();
+ if (!successful)
+ return false;
+
+ if (collectComments_) {
+ CommentPlacement placement = commentBefore;
+ if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
+ if (c != '*' || !containsNewLine(commentBegin, current_))
+ placement = commentAfterOnSameLine;
+ }
+
+ addComment(commentBegin, current_, placement);
+ }
+ return true;
+}
+
+JSONCPP_STRING OurReader::normalizeEOL(OurReader::Location begin, OurReader::Location end) {
+ JSONCPP_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 Mac EOL
+ normalized += '\n';
+ } else {
+ normalized += c;
+ }
+ }
+ return normalized;
+}
+
+void
+OurReader::addComment(Location begin, Location end, CommentPlacement placement) {
+ assert(collectComments_);
+ const JSONCPP_STRING& normalized = normalizeEOL(begin, end);
+ if (placement == commentAfterOnSameLine) {
+ assert(lastValue_ != 0);
+ lastValue_->setComment(normalized, placement);
+ } else {
+ commentsBefore_ += normalized;
+ }
+}
+
+bool OurReader::readCStyleComment() {
+ while ((current_ + 1) < end_) {
+ Char c = getNextChar();
+ if (c == '*' && *current_ == '/')
+ break;
+ }
+ return getNextChar() == '/';
+}
+
+bool OurReader::readCppStyleComment() {
+ while (current_ != end_) {
+ Char c = getNextChar();
+ if (c == '\n')
+ break;
+ if (c == '\r') {
+ // Consume DOS EOL. It will be normalized in addComment.
+ if (current_ != end_ && *current_ == '\n')
+ getNextChar();
+ // Break on Moc OS 9 EOL.
+ break;
+ }
+ }
+ return true;
+}
+
+bool OurReader::readNumber(bool checkInf) {
+ const char *p = current_;
+ if (checkInf && p != end_ && *p == 'I') {
+ current_ = ++p;
+ return false;
+ }
+ char c = '0'; // stopgap for already consumed character
+ // integral part
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : '\0';
+ // fractional part
+ if (c == '.') {
+ c = (current_ = p) < end_ ? *p++ : '\0';
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : '\0';
+ }
+ // exponential part
+ if (c == 'e' || c == 'E') {
+ c = (current_ = p) < end_ ? *p++ : '\0';
+ if (c == '+' || c == '-')
+ c = (current_ = p) < end_ ? *p++ : '\0';
+ while (c >= '0' && c <= '9')
+ c = (current_ = p) < end_ ? *p++ : '\0';
+ }
+ return true;
+}
+bool OurReader::readString() {
+ Char c = 0;
+ while (current_ != end_) {
+ c = getNextChar();
+ if (c == '\\')
+ getNextChar();
+ else if (c == '"')
+ break;
+ }
+ return c == '"';
+}
+
+
+bool OurReader::readStringSingleQuote() {
+ Char c = 0;
+ while (current_ != end_) {
+ c = getNextChar();
+ if (c == '\\')
+ getNextChar();
+ else if (c == '\'')
+ break;
+ }
+ return c == '\'';
+}
+
+bool OurReader::readObject(Token& tokenStart) {
+ Token tokenName;
+ JSONCPP_STRING name;
+ Value init(objectValue);
+ currentValue().swapPayload(init);
+ currentValue().setOffsetStart(tokenStart.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
+ return true;
+ name.clear();
+ if (tokenName.type_ == tokenString) {
+ if (!decodeString(tokenName, name))
+ return recoverFromError(tokenObjectEnd);
+ } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
+ Value numberName;
+ if (!decodeNumber(tokenName, numberName))
+ return recoverFromError(tokenObjectEnd);
+ name = numberName.asString();
+ } else {
+ break;
+ }
+
+ 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);
+ }
+ Value& value = currentValue()[name];
+ nodes_.push(&value);
+ bool ok = readValue();
+ nodes_.pop();
+ if (!ok) // error already set
+ return recoverFromError(tokenObjectEnd);
+
+ Token comma;
+ if (!readToken(comma) ||
+ (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
+ comma.type_ != tokenComment)) {
+ return addErrorAndRecover(
+ "Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
+ }
+ bool finalizeTokenOk = true;
+ while (comma.type_ == tokenComment && finalizeTokenOk)
+ finalizeTokenOk = readToken(comma);
+ if (comma.type_ == tokenObjectEnd)
+ return true;
+ }
+ return addErrorAndRecover(
+ "Missing '}' or object member name", tokenName, tokenObjectEnd);
+}
+
+bool OurReader::readArray(Token& tokenStart) {
+ Value init(arrayValue);
+ currentValue().swapPayload(init);
+ currentValue().setOffsetStart(tokenStart.start_ - begin_);
+ skipSpaces();
+ if (current_ != end_ && *current_ == ']') // empty array
+ {
+ Token endArray;
+ readToken(endArray);
+ return true;
+ }
+ int index = 0;
+ for (;;) {
+ Value& value = currentValue()[index++];
+ nodes_.push(&value);
+ bool ok = readValue();
+ nodes_.pop();
+ if (!ok) // error already set
+ return recoverFromError(tokenArrayEnd);
+
+ Token token;
+ // Accept Comment after last item in the array.
+ ok = readToken(token);
+ while (token.type_ == tokenComment && ok) {
+ ok = readToken(token);
+ }
+ bool badTokenType =
+ (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
+ if (!ok || badTokenType) {
+ return addErrorAndRecover(
+ "Missing ',' or ']' in array declaration", token, tokenArrayEnd);
+ }
+ if (token.type_ == tokenArrayEnd)
+ break;
+ }
+ return true;
+}
+
+bool OurReader::decodeNumber(Token& token) {
+ Value decoded;
+ if (!decodeNumber(token, decoded))
+ return false;
+ currentValue().swapPayload(decoded);
+ currentValue().setOffsetStart(token.start_ - begin_);
+ currentValue().setOffsetLimit(token.end_ - begin_);
+ return true;
+}
+
+bool OurReader::decodeNumber(Token& token, Value& decoded) {
// Attempts to parse the number as an integer. If the number is
// larger than the maximum supported value of an integer then
// we decode the number as a double.
@@ -518,6 +1579,7 @@ 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.
Value::LargestUInt maxIntegerValue =
isNegative ? Value::LargestUInt(-Value::minLargestInt)
: Value::maxLargestUInt;
@@ -526,9 +1588,7 @@ bool Reader::decodeNumber(Token& token, Value& decoded) {
while (current < token.end_) {
Char c = *current++;
if (c < '0' || c > '9')
- return addError("'" + std::string(token.start_, token.end_) +
- "' is not a number.",
- token);
+ return decodeDouble(token, decoded);
Value::UInt digit(static_cast<Value::UInt>(c - '0'));
if (value >= threshold) {
// We've hit or exceeded the max value divided by 10 (rounded down). If
@@ -551,26 +1611,27 @@ bool Reader::decodeNumber(Token& token, Value& decoded) {
return true;
}
-bool Reader::decodeDouble(Token& token) {
+bool OurReader::decodeDouble(Token& token) {
Value decoded;
if (!decodeDouble(token, decoded))
return false;
- currentValue() = decoded;
+ currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
-bool Reader::decodeDouble(Token& token, Value& decoded) {
+bool OurReader::decodeDouble(Token& token, Value& decoded) {
double value = 0;
const int bufferSize = 32;
int count;
- int length = int(token.end_ - token.start_);
+ 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
@@ -581,34 +1642,36 @@ bool Reader::decodeDouble(Token& token, Value& decoded) {
if (length <= bufferSize) {
Char buffer[bufferSize + 1];
- memcpy(buffer, token.start_, length);
+ memcpy(buffer, token.start_, ulength);
buffer[length] = 0;
+ fixNumericLocaleInput(buffer, buffer + length);
count = sscanf(buffer, format, &value);
} else {
- std::string buffer(token.start_, token.end_);
+ JSONCPP_STRING buffer(token.start_, token.end_);
count = sscanf(buffer.c_str(), format, &value);
}
if (count != 1)
- return addError("'" + std::string(token.start_, token.end_) +
+ return addError("'" + JSONCPP_STRING(token.start_, token.end_) +
"' is not a number.",
token);
decoded = value;
return true;
}
-bool Reader::decodeString(Token& token) {
- std::string decoded;
- if (!decodeString(token, decoded))
+bool OurReader::decodeString(Token& token) {
+ JSONCPP_STRING decoded_string;
+ if (!decodeString(token, decoded_string))
return false;
- currentValue() = decoded;
+ Value decoded(decoded_string);
+ currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
-bool Reader::decodeString(Token& token, std::string& decoded) {
- decoded.reserve(token.end_ - token.start_ - 2);
+bool OurReader::decodeString(Token& token, JSONCPP_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 '"'
while (current != end) {
@@ -660,11 +1723,12 @@ bool Reader::decodeString(Token& token, std::string& decoded) {
return true;
}
-bool Reader::decodeUnicodeCodePoint(Token& token,
+bool OurReader::decodeUnicodeCodePoint(Token& token,
Location& current,
Location end,
unsigned int& unicode) {
+ unicode = 0; // Convince scanbuild this is always initialized before use.
if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
return false;
if (unicode >= 0xD800 && unicode <= 0xDBFF) {
@@ -689,16 +1753,16 @@ bool Reader::decodeUnicodeCodePoint(Token& token,
return true;
}
-bool Reader::decodeUnicodeEscapeSequence(Token& token,
+bool OurReader::decodeUnicodeEscapeSequence(Token& token,
Location& current,
Location end,
- unsigned int& unicode) {
+ unsigned int& ret_unicode) {
if (end - current < 4)
return addError(
"Bad unicode escape sequence in string: four digits expected.",
token,
current);
- unicode = 0;
+ int unicode = 0;
for (int index = 0; index < 4; ++index) {
Char c = *current++;
unicode *= 16;
@@ -714,11 +1778,12 @@ bool Reader::decodeUnicodeEscapeSequence(Token& token,
token,
current);
}
+ ret_unicode = static_cast<unsigned int>(unicode);
return true;
}
bool
-Reader::addError(const std::string& message, Token& token, Location extra) {
+OurReader::addError(const JSONCPP_STRING& message, Token& token, Location extra) {
ErrorInfo info;
info.token_ = token;
info.message_ = message;
@@ -727,8 +1792,8 @@ Reader::addError(const std::string& message, Token& token, Location extra) {
return false;
}
-bool Reader::recoverFromError(TokenType skipUntilToken) {
- int errorCount = int(errors_.size());
+bool OurReader::recoverFromError(TokenType skipUntilToken) {
+ size_t errorCount = errors_.size();
Token skip;
for (;;) {
if (!readToken(skip))
@@ -740,22 +1805,22 @@ bool Reader::recoverFromError(TokenType skipUntilToken) {
return false;
}
-bool Reader::addErrorAndRecover(const std::string& message,
+bool OurReader::addErrorAndRecover(const JSONCPP_STRING& message,
Token& token,
TokenType skipUntilToken) {
addError(message, token);
return recoverFromError(skipUntilToken);
}
-Value& Reader::currentValue() { return *(nodes_.top()); }
+Value& OurReader::currentValue() { return *(nodes_.top()); }
-Reader::Char Reader::getNextChar() {
+OurReader::Char OurReader::getNextChar() {
if (current_ == end_)
return 0;
return *current_++;
}
-void Reader::getLocationLineAndColumn(Location location,
+void OurReader::getLocationLineAndColumn(Location location,
int& line,
int& column) const {
Location current = begin_;
@@ -778,29 +1843,16 @@ void Reader::getLocationLineAndColumn(Location location,
++line;
}
-std::string Reader::getLocationLineAndColumn(Location location) const {
+JSONCPP_STRING OurReader::getLocationLineAndColumn(Location location) const {
int line, column;
getLocationLineAndColumn(location, line, column);
char buffer[18 + 16 + 16 + 1];
-#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__)
-#if defined(WINCE)
- _snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
-#else
- sprintf_s(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
-#endif
-#else
snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
-#endif
return buffer;
}
-// Deprecated. Preserved for backward compatibility
-std::string Reader::getFormatedErrorMessages() const {
- return getFormattedErrorMessages();
-}
-
-std::string Reader::getFormattedErrorMessages() const {
- std::string formattedMessage;
+JSONCPP_STRING OurReader::getFormattedErrorMessages() const {
+ JSONCPP_STRING formattedMessage;
for (Errors::const_iterator itError = errors_.begin();
itError != errors_.end();
++itError) {
@@ -815,13 +1867,13 @@ std::string Reader::getFormattedErrorMessages() const {
return formattedMessage;
}
-std::vector<Reader::StructuredError> Reader::getStructuredErrors() const {
- std::vector<Reader::StructuredError> allErrors;
+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;
- Reader::StructuredError structured;
+ OurReader::StructuredError structured;
structured.offset_start = error.token_.start_ - begin_;
structured.offset_limit = error.token_.end_ - begin_;
structured.message = error.message_;
@@ -830,8 +1882,8 @@ std::vector<Reader::StructuredError> Reader::getStructuredErrors() const {
return allErrors;
}
-bool Reader::pushError(const Value& value, const std::string& message) {
- size_t length = end_ - begin_;
+bool OurReader::pushError(const Value& value, const JSONCPP_STRING& message) {
+ ptrdiff_t length = end_ - begin_;
if(value.getOffsetStart() > length
|| value.getOffsetLimit() > length)
return false;
@@ -847,8 +1899,8 @@ bool Reader::pushError(const Value& value, const std::string& message) {
return true;
}
-bool Reader::pushError(const Value& value, const std::string& message, const Value& extra) {
- size_t length = end_ - begin_;
+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)
@@ -865,19 +1917,147 @@ bool Reader::pushError(const Value& value, const std::string& message, const Val
return true;
}
-bool Reader::good() const {
+bool OurReader::good() const {
return !errors_.size();
}
-std::istream& operator>>(std::istream& sin, Value& root) {
- Json::Reader reader;
- bool ok = reader.parse(sin, root, true);
+
+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 {
+ bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_);
+ if (errs) {
+ *errs = reader_.getFormattedErrorMessages();
+ }
+ return ok;
+ }
+};
+
+CharReaderBuilder::CharReaderBuilder()
+{
+ setDefaults(&settings_);
+}
+CharReaderBuilder::~CharReaderBuilder()
+{}
+CharReader* CharReaderBuilder::newCharReader() const
+{
+ bool collectComments = settings_["collectComments"].asBool();
+ OurFeatures features = OurFeatures::all();
+ features.allowComments_ = settings_["allowComments"].asBool();
+ features.strictRoot_ = settings_["strictRoot"].asBool();
+ features.allowDroppedNullPlaceholders_ = settings_["allowDroppedNullPlaceholders"].asBool();
+ features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool();
+ features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool();
+ features.stackLimit_ = settings_["stackLimit"].asInt();
+ features.failIfExtra_ = settings_["failIfExtra"].asBool();
+ features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool();
+ features.allowSpecialFloats_ = settings_["allowSpecialFloats"].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];
+ }
+ }
+ return 0u == inv.size();
+}
+Value& CharReaderBuilder::operator[](JSONCPP_STRING key)
+{
+ return settings_[key];
+}
+// static
+void CharReaderBuilder::strictMode(Json::Value* settings)
+{
+//! [CharReaderBuilderStrictMode]
+ (*settings)["allowComments"] = false;
+ (*settings)["strictRoot"] = true;
+ (*settings)["allowDroppedNullPlaceholders"] = false;
+ (*settings)["allowNumericKeys"] = false;
+ (*settings)["allowSingleQuotes"] = false;
+ (*settings)["stackLimit"] = 1000;
+ (*settings)["failIfExtra"] = true;
+ (*settings)["rejectDupKeys"] = true;
+ (*settings)["allowSpecialFloats"] = false;
+//! [CharReaderBuilderStrictMode]
+}
+// static
+void CharReaderBuilder::setDefaults(Json::Value* settings)
+{
+//! [CharReaderBuilderDefaults]
+ (*settings)["collectComments"] = true;
+ (*settings)["allowComments"] = true;
+ (*settings)["strictRoot"] = false;
+ (*settings)["allowDroppedNullPlaceholders"] = false;
+ (*settings)["allowNumericKeys"] = false;
+ (*settings)["allowSingleQuotes"] = false;
+ (*settings)["stackLimit"] = 1000;
+ (*settings)["failIfExtra"] = false;
+ (*settings)["rejectDupKeys"] = false;
+ (*settings)["allowSpecialFloats"] = false;
+//! [CharReaderBuilderDefaults]
+}
+
+//////////////////////////////////
+// global functions
+
+bool parseFromStream(
+ CharReader::Factory const& fact, JSONCPP_ISTREAM& sin,
+ Value* root, JSONCPP_STRING* errs)
+{
+ JSONCPP_OSTRINGSTREAM ssin;
+ ssin << sin.rdbuf();
+ JSONCPP_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.
+ CharReaderPtr const reader(fact.newCharReader());
+ return reader->parse(begin, end, root, errs);
+}
+
+JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM& sin, Value& root) {
+ CharReaderBuilder b;
+ JSONCPP_STRING errs;
+ bool ok = parseFromStream(b, sin, &root, &errs);
if (!ok) {
fprintf(stderr,
"Error from reader: %s",
- reader.getFormattedErrorMessages().c_str());
+ errs.c_str());
- JSON_FAIL_MESSAGE("reader error");
+ 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 f9b61c38c..431617830 100644
--- a/Utilities/cmjsoncpp/src/lib_json/json_tool.h
+++ b/Utilities/cmjsoncpp/src/lib_json/json_tool.h
@@ -1,4 +1,4 @@
-// Copyright 2007-2010 Baptiste Lepilleur
+// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
@@ -6,6 +6,16 @@
#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
#define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
+
+// Also support old flag NO_LOCALE_SUPPORT
+#ifdef NO_LOCALE_SUPPORT
+#define JSONCPP_NO_LOCALE_SUPPORT
+#endif
+
+#ifndef JSONCPP_NO_LOCALE_SUPPORT
+#include <clocale>
+#endif
+
/* This header provides common string manipulation support, such as UTF-8,
* portable conversion from/to string...
*
@@ -13,10 +23,18 @@
*/
namespace Json {
+static char getDecimalPoint() {
+#ifdef JSONCPP_NO_LOCALE_SUPPORT
+ return '\0';
+#else
+ struct lconv* lc = localeconv();
+ return lc ? *(lc->decimal_point) : '\0';
+#endif
+}
/// Converts a unicode code-point to UTF-8.
-static inline std::string codePointToUTF8(unsigned int cp) {
- std::string result;
+static inline JSONCPP_STRING codePointToUTF8(unsigned int cp) {
+ JSONCPP_STRING result;
// based on description from http://en.wikipedia.org/wiki/UTF-8
@@ -30,8 +48,8 @@ static inline std::string codePointToUTF8(unsigned int cp) {
} else if (cp <= 0xFFFF) {
result.resize(3);
result[2] = static_cast<char>(0x80 | (0x3f & cp));
- result[1] = 0x80 | static_cast<char>((0x3f & (cp >> 6)));
- result[0] = 0xE0 | static_cast<char>((0xf & (cp >> 12)));
+ result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
+ result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12)));
} else if (cp <= 0x10FFFF) {
result.resize(4);
result[3] = static_cast<char>(0x80 | (0x3f & cp));
@@ -43,7 +61,7 @@ static inline std::string codePointToUTF8(unsigned int cp) {
return result;
}
-/// Returns true if ch is a control character (in range [0,32[).
+/// Returns true if ch is a control character (in range [1,31]).
static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; }
enum {
@@ -63,7 +81,7 @@ typedef char UIntToStringBuffer[uintToStringBufferSize];
static inline void uintToString(LargestUInt value, char*& current) {
*--current = 0;
do {
- *--current = char(value % 10) + '0';
+ *--current = static_cast<char>(value % 10U + static_cast<unsigned>('0'));
value /= 10;
} while (value != 0);
}
@@ -82,6 +100,18 @@ static inline void fixNumericLocale(char* begin, char* end) {
}
}
+static inline void fixNumericLocaleInput(char* begin, char* end) {
+ char decimalPoint = getDecimalPoint();
+ if (decimalPoint != '\0' && decimalPoint != '.') {
+ while (begin < end) {
+ if (*begin == '.') {
+ *begin = decimalPoint;
+ }
+ ++begin;
+ }
+ }
+}
+
} // 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 478afe102..f271e5731 100644
--- a/Utilities/cmjsoncpp/src/lib_json/json_value.cpp
+++ b/Utilities/cmjsoncpp/src/lib_json/json_value.cpp
@@ -1,4 +1,4 @@
-// Copyright 2011 Baptiste Lepilleur
+// Copyright 2011 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
@@ -7,9 +7,6 @@
#include <json/assertions.h>
#include <json/value.h>
#include <json/writer.h>
-#ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
-#include "json_batchallocator.h"
-#endif // #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <math.h>
#include <sstream>
@@ -20,6 +17,7 @@
#include <cpptl/conststring.h>
#endif
#include <cstddef> // size_t
+#include <algorithm> // min()
#define JSON_ASSERT_UNREACHABLE assert(false)
@@ -33,9 +31,22 @@ 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);
+//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;
+}
+
+// for backwards compatibility, we'll leave these global references around, but DO NOT
+// use them in JSONCPP library code any more!
+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);
@@ -53,17 +64,17 @@ const LargestInt Value::minLargestInt = LargestInt(~(LargestUInt(-1) / 2));
const LargestInt Value::maxLargestInt = LargestInt(LargestUInt(-1) / 2);
const LargestUInt Value::maxLargestUInt = LargestUInt(-1);
-/// Unknown size marker
-static const unsigned int unknown = (unsigned)-1;
-
#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;
}
#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
static inline double integerToDouble(Json::UInt64 value) {
- return static_cast<double>(Int64(value / 2)) * 2.0 + 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) {
@@ -84,27 +95,84 @@ static inline bool InRange(double d, T min, U max) {
* @return Pointer on the duplicate instance of string.
*/
static inline char* duplicateStringValue(const char* value,
- unsigned int length = unknown) {
- if (length == unknown)
- length = (unsigned int)strlen(value);
-
+ size_t length)
+{
// Avoid an integer overflow in the call to malloc below by limiting length
// to a sane value.
- if (length >= (unsigned)Value::maxInt)
+ if (length >= static_cast<size_t>(Value::maxInt))
length = Value::maxInt - 1;
char* newString = static_cast<char*>(malloc(length + 1));
- JSON_ASSERT_MESSAGE(newString != 0,
- "in Json::Value::duplicateStringValue(): "
- "Failed to allocate string value buffer");
+ if (newString == NULL) {
+ throwRuntimeError(
+ "in Json::Value::duplicateStringValue(): "
+ "Failed to allocate string value buffer");
+ }
memcpy(newString, value, length);
newString[length] = 0;
return newString;
}
-/** Free the string duplicated by duplicateStringValue().
+/* Record the length as a prefix.
+ */
+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,
+ "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");
+ }
+ *reinterpret_cast<unsigned*>(newString) = length;
+ memcpy(newString + sizeof(unsigned), value, length);
+ 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)
+{
+ if (!isPrefixed) {
+ *length = static_cast<unsigned>(strlen(prefixed));
+ *value = prefixed;
+ } else {
+ *length = *reinterpret_cast<unsigned const*>(prefixed);
+ *value = prefixed + sizeof(unsigned);
+ }
+}
+/** Free the string duplicated by duplicateStringValue()/duplicateAndPrefixStringValue().
*/
-static inline void releaseStringValue(char* value) { free(value); }
+#if JSONCPP_USING_SECURE_MEMORY
+static inline void releasePrefixedStringValue(char* value) {
+ unsigned length = 0;
+ char const* valueDecoded;
+ decodePrefixedString(true, value, &length, &valueDecoded);
+ size_t const size = sizeof(unsigned) + length + 1U;
+ memset(value, 0, size);
+ free(value);
+}
+static inline void releaseStringValue(char* value, unsigned length) {
+ // length==0 => we allocated the strings memory
+ 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);
+}
+#endif // JSONCPP_USING_SECURE_MEMORY
} // namespace Json
@@ -116,16 +184,36 @@ static inline void releaseStringValue(char* value) { free(value); }
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
#if !defined(JSON_IS_AMALGAMATION)
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
-#include "json_internalarray.inl"
-#include "json_internalmap.inl"
-#endif // JSON_VALUE_USE_INTERNAL_MAP
#include "json_valueiterator.inl"
#endif // if !defined(JSON_IS_AMALGAMATION)
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)
+{
+ throw RuntimeError(msg);
+}
+JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg)
+{
+ throw LogicError(msg);
+}
+
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
@@ -134,22 +222,25 @@ namespace Json {
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
-Value::CommentInfo::CommentInfo() : comment_(0) {}
+Value::CommentInfo::CommentInfo() : comment_(0)
+{}
Value::CommentInfo::~CommentInfo() {
if (comment_)
- releaseStringValue(comment_);
+ releaseStringValue(comment_, 0u);
}
-void Value::CommentInfo::setComment(const char* text) {
- if (comment_)
- releaseStringValue(comment_);
+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);
+ comment_ = duplicateStringValue(text, len);
}
// //////////////////////////////////////////////////////////////////
@@ -159,29 +250,41 @@ void Value::CommentInfo::setComment(const char* text) {
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
-// Notes: index_ indicates if the string was allocated when
+// Notes: policy_ indicates if the string was allocated when
// a string is stored.
-Value::CZString::CZString(ArrayIndex index) : cstr_(0), index_(index) {}
+Value::CZString::CZString(ArrayIndex aindex) : cstr_(0), index_(aindex) {}
-Value::CZString::CZString(const char* cstr, DuplicationPolicy allocate)
- : cstr_(allocate == duplicate ? duplicateStringValue(cstr) : cstr),
- index_(allocate) {}
+Value::CZString::CZString(char const* str, unsigned ulength, DuplicationPolicy allocate)
+ : cstr_(str) {
+ // allocate != duplicate
+ storage_.policy_ = allocate & 0x3;
+ storage_.length_ = ulength & 0x3FFFFFFF;
+}
-Value::CZString::CZString(const CZString& other)
- : cstr_(other.index_ != noDuplication && other.cstr_ != 0
- ? duplicateStringValue(other.cstr_)
- : other.cstr_),
- index_(other.cstr_
- ? static_cast<ArrayIndex>(other.index_ == noDuplication
+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)
- : other.index_) {}
+ : 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_) {
+ other.cstr_ = nullptr;
+}
+#endif
Value::CZString::~CZString() {
- if (cstr_ && index_ == duplicate)
- releaseStringValue(const_cast<char*>(cstr_));
+ 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
+ }
}
void Value::CZString::swap(CZString& other) {
@@ -189,34 +292,53 @@ void Value::CZString::swap(CZString& other) {
std::swap(index_, other.index_);
}
-Value::CZString& Value::CZString::operator=(CZString other) {
- swap(other);
+Value::CZString& Value::CZString::operator=(const CZString& other) {
+ cstr_ = other.cstr_;
+ index_ = other.index_;
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_) {
- assert(other.cstr_);
- return strcmp(cstr_, other.cstr_) < 0;
- }
- return index_ < other.index_;
+ 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;
+ return (this_len < other_len);
}
bool Value::CZString::operator==(const CZString& other) const {
- if (cstr_) {
- assert(other.cstr_);
- return strcmp(cstr_, other.cstr_) == 0;
- }
- return index_ == other.index_;
+ 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;
+ JSON_ASSERT(this->cstr_ && other.cstr_);
+ int comp = memcmp(this->cstr_, other.cstr_, this_len);
+ return comp == 0;
}
ArrayIndex Value::CZString::index() const { return index_; }
-const char* Value::CZString::c_str() const { return cstr_; }
-
-bool Value::CZString::isStaticString() const { return index_ == noDuplication; }
-
-#endif // ifndef JSON_VALUE_USE_INTERNAL_MAP
+//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; }
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
@@ -226,13 +348,14 @@ bool Value::CZString::isStaticString() const { return index_ == noDuplication; }
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
-/*! \internal Default constructor initialization must be equivalent to:
+/*! internal Default constructor initialization must be equivalent to:
* memset( this, 0, sizeof(Value) )
* This optimization is used in ValueInternalMap fast allocator.
*/
-Value::Value(ValueType type) {
- initBasic(type);
- switch (type) {
+Value::Value(ValueType vtype) {
+ static char const emptyString[] = "";
+ initBasic(vtype);
+ switch (vtype) {
case nullValue:
break;
case intValue:
@@ -243,21 +366,13 @@ Value::Value(ValueType type) {
value_.real_ = 0.0;
break;
case stringValue:
- value_.string_ = 0;
+ // allocated_ == false, so this is safe.
+ value_.string_ = const_cast<char*>(static_cast<char const*>(emptyString));
break;
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
value_.map_ = new ObjectValues();
break;
-#else
- case arrayValue:
- value_.array_ = arrayAllocator()->newArray();
- break;
- case objectValue:
- value_.map_ = mapAllocator()->newMap();
- break;
-#endif
case booleanValue:
value_.bool_ = false;
break;
@@ -293,19 +408,20 @@ Value::Value(double value) {
Value::Value(const char* value) {
initBasic(stringValue, true);
- value_.string_ = duplicateStringValue(value);
+ JSON_ASSERT_MESSAGE(value != NULL, "Null Value Passed to Value Constructor");
+ value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(strlen(value)));
}
Value::Value(const char* beginValue, const char* endValue) {
initBasic(stringValue, true);
value_.string_ =
- duplicateStringValue(beginValue, (unsigned int)(endValue - beginValue));
+ duplicateAndPrefixStringValue(beginValue, static_cast<unsigned>(endValue - beginValue));
}
-Value::Value(const std::string& value) {
+Value::Value(const JSONCPP_STRING& value) {
initBasic(stringValue, true);
value_.string_ =
- duplicateStringValue(value.c_str(), (unsigned int)value.length());
+ duplicateAndPrefixStringValue(value.data(), static_cast<unsigned>(value.length()));
}
Value::Value(const StaticString& value) {
@@ -316,7 +432,7 @@ Value::Value(const StaticString& value) {
#ifdef JSON_USE_CPPTL
Value::Value(const CppTL::ConstString& value) {
initBasic(stringValue, true);
- value_.string_ = duplicateStringValue(value, value.length());
+ value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(value.length()));
}
#endif
@@ -325,14 +441,11 @@ Value::Value(bool value) {
value_.bool_ = value;
}
-Value::Value(const Value& other)
+Value::Value(Value const& other)
: type_(other.type_), allocated_(false)
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
,
- itemIsUsed_(0)
-#endif
- ,
- comments_(0), start_(other.start_), limit_(other.limit_) {
+ comments_(0), start_(other.start_), limit_(other.limit_)
+{
switch (type_) {
case nullValue:
case intValue:
@@ -342,27 +455,22 @@ Value::Value(const Value& other)
value_ = other.value_;
break;
case stringValue:
- if (other.value_.string_) {
- value_.string_ = duplicateStringValue(other.value_.string_);
+ 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_ = 0;
+ value_.string_ = other.value_.string_;
allocated_ = false;
}
break;
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
value_.map_ = new ObjectValues(*other.value_.map_);
break;
-#else
- case arrayValue:
- value_.array_ = arrayAllocator()->newArrayCopy(*other.value_.array_);
- break;
- case objectValue:
- value_.map_ = mapAllocator()->newMapCopy(*other.value_.map_);
- break;
-#endif
default:
JSON_ASSERT_UNREACHABLE;
}
@@ -371,11 +479,20 @@ Value::Value(const Value& other)
for (int comment = 0; comment < numberOfCommentPlacement; ++comment) {
const CommentInfo& otherComment = other.comments_[comment];
if (otherComment.comment_)
- comments_[comment].setComment(otherComment.comment_);
+ comments_[comment].setComment(
+ otherComment.comment_, strlen(otherComment.comment_));
}
}
}
+#if JSON_HAS_RVALUE_REFERENCES
+// Move constructor
+Value::Value(Value&& other) {
+ initBasic(nullValue);
+ swap(other);
+}
+#endif
+
Value::~Value() {
switch (type_) {
case nullValue:
@@ -386,27 +503,19 @@ Value::~Value() {
break;
case stringValue:
if (allocated_)
- releaseStringValue(value_.string_);
+ releasePrefixedStringValue(value_.string_);
break;
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
delete value_.map_;
break;
-#else
- case arrayValue:
- arrayAllocator()->destructArray(value_.array_);
- break;
- case objectValue:
- mapAllocator()->destructMap(value_.map_);
- break;
-#endif
default:
JSON_ASSERT_UNREACHABLE;
}
- if (comments_)
- delete[] comments_;
+ delete[] comments_;
+
+ value_.uint_ = 0;
}
Value& Value::operator=(Value other) {
@@ -414,18 +523,36 @@ Value& Value::operator=(Value other) {
return *this;
}
-void Value::swap(Value& other) {
+void Value::swapPayload(Value& other) {
ValueType temp = type_;
type_ = other.type_;
other.type_ = temp;
std::swap(value_, other.value_);
int temp2 = allocated_;
allocated_ = other.allocated_;
- other.allocated_ = temp2;
+ other.allocated_ = temp2 & 0x1;
+}
+
+void Value::copyPayload(const Value& other) {
+ type_ = other.type_;
+ value_ = other.value_;
+ allocated_ = other.allocated_;
+}
+
+void Value::swap(Value& other) {
+ swapPayload(other);
+ std::swap(comments_, other.comments_);
std::swap(start_, other.start_);
std::swap(limit_, other.limit_);
}
+void Value::copy(const Value& other) {
+ copyPayload(other);
+ comments_ = other.comments_;
+ start_ = other.start_;
+ limit_ = other.limit_;
+}
+
ValueType Value::type() const { return type_; }
int Value::compare(const Value& other) const {
@@ -452,10 +579,24 @@ bool Value::operator<(const Value& other) const {
case booleanValue:
return value_.bool_ < other.value_.bool_;
case stringValue:
- return (value_.string_ == 0 && other.value_.string_) ||
- (other.value_.string_ && value_.string_ &&
- strcmp(value_.string_, other.value_.string_) < 0);
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
+ {
+ if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
+ if (other.value_.string_) return true;
+ else return false;
+ }
+ 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);
+ 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;
+ return (this_len < other_len);
+ }
case arrayValue:
case objectValue: {
int delta = int(value_.map_->size() - other.value_.map_->size());
@@ -463,12 +604,6 @@ bool Value::operator<(const Value& other) const {
return delta < 0;
return (*value_.map_) < (*other.value_.map_);
}
-#else
- case arrayValue:
- return value_.array_->compare(*(other.value_.array_)) < 0;
- case objectValue:
- return value_.map_->compare(*(other.value_.map_)) < 0;
-#endif
default:
JSON_ASSERT_UNREACHABLE;
}
@@ -501,20 +636,25 @@ bool Value::operator==(const Value& other) const {
case booleanValue:
return value_.bool_ == other.value_.bool_;
case stringValue:
- return (value_.string_ == other.value_.string_) ||
- (other.value_.string_ && value_.string_ &&
- strcmp(value_.string_, other.value_.string_) == 0);
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
+ {
+ if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
+ 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;
+ JSON_ASSERT(this_str && other_str);
+ int comp = memcmp(this_str, other_str, this_len);
+ return comp == 0;
+ }
case arrayValue:
case objectValue:
return value_.map_->size() == other.value_.map_->size() &&
(*value_.map_) == (*other.value_.map_);
-#else
- case arrayValue:
- return value_.array_->compare(*(other.value_.array_)) == 0;
- case objectValue:
- return value_.map_->compare(*(other.value_.map_)) == 0;
-#endif
default:
JSON_ASSERT_UNREACHABLE;
}
@@ -526,15 +666,46 @@ bool Value::operator!=(const Value& other) const { return !(*this == other); }
const char* Value::asCString() const {
JSON_ASSERT_MESSAGE(type_ == stringValue,
"in Json::Value::asCString(): requires stringValue");
- return value_.string_;
+ if (value_.string_ == 0) return 0;
+ unsigned this_len;
+ char const* this_str;
+ decodePrefixedString(this->allocated_, 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;
+ unsigned this_len;
+ char const* this_str;
+ decodePrefixedString(this->allocated_, 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;
+ unsigned length;
+ decodePrefixedString(this->allocated_, this->value_.string_, &length, str);
+ *cend = *str + length;
+ return true;
}
-std::string Value::asString() const {
+JSONCPP_STRING Value::asString() const {
switch (type_) {
case nullValue:
return "";
case stringValue:
- return value_.string_ ? value_.string_ : "";
+ {
+ if (value_.string_ == 0) 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);
+ }
case booleanValue:
return value_.bool_ ? "true" : "false";
case intValue:
@@ -550,7 +721,11 @@ std::string Value::asString() const {
#ifdef JSON_USE_CPPTL
CppTL::ConstString Value::asConstString() const {
- return CppTL::ConstString(asString().c_str());
+ unsigned len;
+ char const* str;
+ decodePrefixedString(allocated_, value_.string_,
+ &len, &str);
+ return CppTL::ConstString(str, len);
}
#endif
@@ -689,7 +864,8 @@ float Value::asFloat() const {
#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
return static_cast<float>(value_.uint_);
#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
- return integerToDouble(value_.uint_);
+ // This can fail (silently?) if the value is bigger than MAX_FLOAT.
+ return static_cast<float>(integerToDouble(value_.uint_));
#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
case realValue:
return static_cast<float>(value_.real_);
@@ -714,7 +890,8 @@ bool Value::asBool() const {
case uintValue:
return value_.uint_ ? true : false;
case realValue:
- return value_.real_ ? true : false;
+ // This is kind of strange. Not recommended.
+ return (value_.real_ != 0.0) ? true : false;
default:
break;
}
@@ -726,7 +903,7 @@ bool Value::isConvertibleTo(ValueType other) const {
case nullValue:
return (isNumeric() && asDouble() == 0.0) ||
(type_ == booleanValue && value_.bool_ == false) ||
- (type_ == stringValue && asString() == "") ||
+ (type_ == stringValue && asString().empty()) ||
(type_ == arrayValue && value_.map_->size() == 0) ||
(type_ == objectValue && value_.map_->size() == 0) ||
type_ == nullValue;
@@ -764,7 +941,6 @@ ArrayIndex Value::size() const {
case booleanValue:
case stringValue:
return 0;
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue: // size of the array is highest index + 1
if (!value_.map_->empty()) {
ObjectValues::const_iterator itLast = value_.map_->end();
@@ -774,12 +950,6 @@ ArrayIndex Value::size() const {
return 0;
case objectValue:
return ArrayIndex(value_.map_->size());
-#else
- case arrayValue:
- return Int(value_.array_->size());
- case objectValue:
- return Int(value_.map_->size());
-#endif
}
JSON_ASSERT_UNREACHABLE;
return 0; // unreachable;
@@ -801,19 +971,10 @@ void Value::clear() {
start_ = 0;
limit_ = 0;
switch (type_) {
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
value_.map_->clear();
break;
-#else
- case arrayValue:
- value_.array_->clear();
- break;
- case objectValue:
- value_.map_->clear();
- break;
-#endif
default:
break;
}
@@ -824,7 +985,6 @@ void Value::resize(ArrayIndex newSize) {
"in Json::Value::resize(): requires arrayValue");
if (type_ == nullValue)
*this = Value(arrayValue);
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
ArrayIndex oldSize = size();
if (newSize == 0)
clear();
@@ -834,11 +994,8 @@ void Value::resize(ArrayIndex newSize) {
for (ArrayIndex index = newSize; index < oldSize; ++index) {
value_.map_->erase(index);
}
- assert(size() == newSize);
+ JSON_ASSERT(size() == newSize);
}
-#else
- value_.array_->resize(newSize);
-#endif
}
Value& Value::operator[](ArrayIndex index) {
@@ -847,18 +1004,14 @@ Value& Value::operator[](ArrayIndex index) {
"in Json::Value::operator[](ArrayIndex): requires arrayValue");
if (type_ == nullValue)
*this = Value(arrayValue);
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString key(index);
ObjectValues::iterator it = value_.map_->lower_bound(key);
if (it != value_.map_->end() && (*it).first == key)
return (*it).second;
- ObjectValues::value_type defaultValue(key, null);
+ ObjectValues::value_type defaultValue(key, nullSingleton());
it = value_.map_->insert(it, defaultValue);
return (*it).second;
-#else
- return value_.array_->resolveReference(index);
-#endif
}
Value& Value::operator[](int index) {
@@ -873,17 +1026,12 @@ const Value& Value::operator[](ArrayIndex index) const {
type_ == nullValue || type_ == arrayValue,
"in Json::Value::operator[](ArrayIndex)const: requires arrayValue");
if (type_ == nullValue)
- return null;
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
+ return nullSingleton();
CZString key(index);
ObjectValues::const_iterator it = value_.map_->find(key);
if (it == value_.map_->end())
- return null;
+ return nullSingleton();
return (*it).second;
-#else
- Value* value = value_.array_->find(index);
- return value ? *value : null;
-#endif
}
const Value& Value::operator[](int index) const {
@@ -893,149 +1041,215 @@ const Value& Value::operator[](int index) const {
return (*this)[ArrayIndex(index)];
}
-Value& Value::operator[](const char* key) {
- return resolveReference(key, false);
-}
-
-void Value::initBasic(ValueType type, bool allocated) {
- type_ = type;
+void Value::initBasic(ValueType vtype, bool allocated) {
+ type_ = vtype;
allocated_ = allocated;
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
- itemIsUsed_ = 0;
-#endif
comments_ = 0;
start_ = 0;
limit_ = 0;
}
-Value& Value::resolveReference(const char* key, bool isStatic) {
+// 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,
"in Json::Value::resolveReference(): requires objectValue");
if (type_ == nullValue)
*this = Value(objectValue);
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString actualKey(
- key, isStatic ? CZString::noDuplication : CZString::duplicateOnCopy);
+ key, static_cast<unsigned>(strlen(key)), CZString::noDuplication); // NOTE!
ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
if (it != value_.map_->end() && (*it).first == actualKey)
return (*it).second;
- ObjectValues::value_type defaultValue(actualKey, null);
+ ObjectValues::value_type defaultValue(actualKey, nullSingleton());
+ it = value_.map_->insert(it, defaultValue);
+ Value& value = (*it).second;
+ return value;
+}
+
+// @param key is not null-terminated.
+Value& Value::resolveReference(char const* key, char const* cend)
+{
+ JSON_ASSERT_MESSAGE(
+ type_ == nullValue || type_ == objectValue,
+ "in Json::Value::resolveReference(key, end): requires objectValue");
+ if (type_ == nullValue)
+ *this = Value(objectValue);
+ CZString actualKey(
+ key, static_cast<unsigned>(cend-key), CZString::duplicateOnCopy);
+ ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
+ if (it != value_.map_->end() && (*it).first == actualKey)
+ return (*it).second;
+
+ ObjectValues::value_type defaultValue(actualKey, nullSingleton());
it = value_.map_->insert(it, defaultValue);
Value& value = (*it).second;
return value;
-#else
- return value_.map_->resolveReference(key, isStatic);
-#endif
}
Value Value::get(ArrayIndex index, const Value& defaultValue) const {
const Value* value = &((*this)[index]);
- return value == &null ? defaultValue : *value;
+ return value == &nullSingleton() ? defaultValue : *value;
}
bool Value::isValidIndex(ArrayIndex index) const { return index < size(); }
-const Value& Value::operator[](const char* key) const {
+Value const* Value::find(char const* key, char const* cend) const
+{
JSON_ASSERT_MESSAGE(
type_ == nullValue || type_ == objectValue,
- "in Json::Value::operator[](char const*)const: requires objectValue");
- if (type_ == nullValue)
- return null;
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
- CZString actualKey(key, CZString::noDuplication);
+ "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);
ObjectValues::const_iterator it = value_.map_->find(actualKey);
- if (it == value_.map_->end())
- return null;
- return (*it).second;
-#else
- const Value* value = value_.map_->find(key);
- return value ? *value : null;
-#endif
+ if (it == value_.map_->end()) return NULL;
+ return &(*it).second;
+}
+const Value& Value::operator[](const char* key) const
+{
+ Value const* found = find(key, key + strlen(key));
+ if (!found) return nullSingleton();
+ return *found;
+}
+Value const& Value::operator[](JSONCPP_STRING const& key) const
+{
+ Value const* found = find(key.data(), key.data() + key.length());
+ if (!found) return nullSingleton();
+ return *found;
}
-Value& Value::operator[](const std::string& key) {
- return (*this)[key.c_str()];
+Value& Value::operator[](const char* key) {
+ return resolveReference(key, key + strlen(key));
}
-const Value& Value::operator[](const std::string& key) const {
- return (*this)[key.c_str()];
+Value& Value::operator[](const JSONCPP_STRING& key) {
+ return resolveReference(key.data(), key.data() + key.length());
}
Value& Value::operator[](const StaticString& key) {
- return resolveReference(key, true);
+ return resolveReference(key.c_str());
}
#ifdef JSON_USE_CPPTL
Value& Value::operator[](const CppTL::ConstString& key) {
- return (*this)[key.c_str()];
+ return resolveReference(key.c_str(), key.end_c_str());
}
-
-const Value& Value::operator[](const CppTL::ConstString& key) const {
- return (*this)[key.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;
}
#endif
Value& Value::append(const Value& value) { return (*this)[size()] = value; }
-Value Value::get(const char* key, const Value& defaultValue) const {
- const Value* value = &((*this)[key]);
- return value == &null ? defaultValue : *value;
-}
+#if JSON_HAS_RVALUE_REFERENCES
+ Value& Value::append(Value&& value) { return (*this)[size()] = value; }
+#endif
-Value Value::get(const std::string& key, const Value& defaultValue) const {
- return get(key.c_str(), defaultValue);
+Value Value::get(char const* key, char const* cend, Value const& defaultValue) const
+{
+ Value const* found = find(key, cend);
+ return !found ? defaultValue : *found;
+}
+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
+{
+ return get(key.data(), key.data() + key.length(), defaultValue);
}
-Value Value::removeMember(const char* key) {
- JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == objectValue,
- "in Json::Value::removeMember(): requires objectValue");
- if (type_ == nullValue)
- return null;
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
- CZString actualKey(key, CZString::noDuplication);
+
+bool Value::removeMember(const char* key, const char* cend, Value* removed)
+{
+ if (type_ != objectValue) {
+ return false;
+ }
+ CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
ObjectValues::iterator it = value_.map_->find(actualKey);
if (it == value_.map_->end())
- return null;
- Value old(it->second);
+ return false;
+ *removed = it->second;
value_.map_->erase(it);
- return old;
-#else
- Value* value = value_.map_->find(key);
- if (value) {
- Value old(*value);
- value_.map_.remove(key);
- return old;
- } else {
- return null;
- }
-#endif
+ return true;
+}
+bool Value::removeMember(const char* key, Value* removed)
+{
+ return removeMember(key, key + strlen(key), removed);
}
+bool Value::removeMember(JSONCPP_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,
+ "in Json::Value::removeMember(): requires objectValue");
+ if (type_ == nullValue)
+ return nullSingleton();
-Value Value::removeMember(const std::string& key) {
+ 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());
}
+bool Value::removeIndex(ArrayIndex index, Value* removed) {
+ if (type_ != arrayValue) {
+ return false;
+ }
+ CZString key(index);
+ ObjectValues::iterator it = value_.map_->find(key);
+ if (it == value_.map_->end()) {
+ return false;
+ }
+ *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){
+ 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);
+ 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(), defaultValue);
+ return get(key.c_str(), key.end_c_str(), defaultValue);
}
#endif
-bool Value::isMember(const char* key) const {
- const Value* value = &((*this)[key]);
- return value != &null;
+bool Value::isMember(char const* key, char const* cend) const
+{
+ Value const* value = find(key, cend);
+ return NULL != value;
}
-
-bool Value::isMember(const std::string& key) const {
- return isMember(key.c_str());
+bool Value::isMember(char const* key) const
+{
+ return isMember(key, key + strlen(key));
+}
+bool Value::isMember(JSONCPP_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());
+ return isMember(key.c_str(), key.end_c_str());
}
#endif
@@ -1047,19 +1261,12 @@ Value::Members Value::getMemberNames() const {
return Value::Members();
Members members;
members.reserve(value_.map_->size());
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
ObjectValues::const_iterator it = value_.map_->begin();
ObjectValues::const_iterator itEnd = value_.map_->end();
- for (; it != itEnd; ++it)
- members.push_back(std::string((*it).first.c_str()));
-#else
- ValueInternalMap::IteratorState it;
- ValueInternalMap::IteratorState itEnd;
- value_.map_->makeBeginIterator(it);
- value_.map_->makeEndIterator(itEnd);
- for (; !ValueInternalMap::equals(it, itEnd); ValueInternalMap::increment(it))
- members.push_back(std::string(ValueInternalMap::key(it)));
-#endif
+ for (; it != itEnd; ++it) {
+ members.push_back(JSONCPP_STRING((*it).first.data(),
+ (*it).first.length()));
+ }
return members;
}
//
@@ -1100,7 +1307,11 @@ bool Value::isBool() const { return type_ == booleanValue; }
bool Value::isInt() const {
switch (type_) {
case intValue:
+#if defined(JSON_HAS_INT64)
return value_.int_ >= minInt && value_.int_ <= maxInt;
+#else
+ return true;
+#endif
case uintValue:
return value_.uint_ <= UInt(maxInt);
case realValue:
@@ -1115,9 +1326,17 @@ bool Value::isInt() const {
bool Value::isUInt() const {
switch (type_) {
case intValue:
+#if defined(JSON_HAS_INT64)
return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt);
+#else
+ return value_.int_ >= 0;
+#endif
case uintValue:
+#if defined(JSON_HAS_INT64)
return value_.uint_ <= maxUInt;
+#else
+ return true;
+#endif
case realValue:
return value_.real_ >= 0 && value_.real_ <= maxUInt &&
IsIntegral(value_.real_);
@@ -1168,16 +1387,28 @@ bool Value::isUInt64() const {
}
bool Value::isIntegral() const {
+ switch (type_) {
+ case intValue:
+ case uintValue:
+ return true;
+ case realValue:
#if defined(JSON_HAS_INT64)
- return isInt64() || isUInt64();
+ // 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 isInt() || isUInt();
-#endif
+ return value_.real_ >= minInt && value_.real_ <= maxUInt && IsIntegral(value_.real_);
+#endif // JSON_HAS_INT64
+ default:
+ break;
+ }
+ return false;
}
-bool Value::isDouble() const { return type_ == realValue || isIntegral(); }
+bool Value::isDouble() const { return type_ == intValue || type_ == uintValue || type_ == realValue; }
-bool Value::isNumeric() const { return isIntegral() || isDouble(); }
+bool Value::isNumeric() const { return isDouble(); }
bool Value::isString() const { return type_ == stringValue; }
@@ -1185,63 +1416,59 @@ bool Value::isArray() const { return type_ == arrayValue; }
bool Value::isObject() const { return type_ == objectValue; }
-void Value::setComment(const char* comment, CommentPlacement placement) {
+void Value::setComment(const char* comment, size_t len, CommentPlacement placement) {
if (!comments_)
comments_ = new CommentInfo[numberOfCommentPlacement];
- comments_[placement].setComment(comment);
+ if ((len > 0) && (comment[len-1] == '\n')) {
+ // Always discard trailing newline, to aid indentation.
+ len -= 1;
+ }
+ comments_[placement].setComment(comment, len);
+}
+
+void Value::setComment(const char* comment, CommentPlacement placement) {
+ setComment(comment, strlen(comment), placement);
}
-void Value::setComment(const std::string& comment, CommentPlacement placement) {
- setComment(comment.c_str(), placement);
+void Value::setComment(const JSONCPP_STRING& comment, CommentPlacement placement) {
+ setComment(comment.c_str(), comment.length(), placement);
}
bool Value::hasComment(CommentPlacement placement) const {
return comments_ != 0 && comments_[placement].comment_ != 0;
}
-std::string Value::getComment(CommentPlacement placement) const {
+JSONCPP_STRING Value::getComment(CommentPlacement placement) const {
if (hasComment(placement))
return comments_[placement].comment_;
return "";
}
-void Value::setOffsetStart(size_t start) { start_ = start; }
+void Value::setOffsetStart(ptrdiff_t start) { start_ = start; }
+
+void Value::setOffsetLimit(ptrdiff_t limit) { limit_ = limit; }
-void Value::setOffsetLimit(size_t limit) { limit_ = limit; }
+ptrdiff_t Value::getOffsetStart() const { return start_; }
-size_t Value::getOffsetStart() const { return start_; }
+ptrdiff_t Value::getOffsetLimit() const { return limit_; }
-size_t Value::getOffsetLimit() const { return limit_; }
+JSONCPP_STRING Value::toStyledString() const {
+ StreamWriterBuilder builder;
-std::string Value::toStyledString() const {
- StyledWriter writer;
- return writer.write(*this);
+ JSONCPP_STRING out = this->hasComment(commentBefore) ? "\n" : "";
+ out += Json::writeString(builder, *this);
+ out += "\n";
+
+ return out;
}
Value::const_iterator Value::begin() const {
switch (type_) {
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
- case arrayValue:
- if (value_.array_) {
- ValueInternalArray::IteratorState it;
- value_.array_->makeBeginIterator(it);
- return const_iterator(it);
- }
- break;
- case objectValue:
- if (value_.map_) {
- ValueInternalMap::IteratorState it;
- value_.map_->makeBeginIterator(it);
- return const_iterator(it);
- }
- break;
-#else
case arrayValue:
case objectValue:
if (value_.map_)
return const_iterator(value_.map_->begin());
break;
-#endif
default:
break;
}
@@ -1250,28 +1477,11 @@ Value::const_iterator Value::begin() const {
Value::const_iterator Value::end() const {
switch (type_) {
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
- case arrayValue:
- if (value_.array_) {
- ValueInternalArray::IteratorState it;
- value_.array_->makeEndIterator(it);
- return const_iterator(it);
- }
- break;
- case objectValue:
- if (value_.map_) {
- ValueInternalMap::IteratorState it;
- value_.map_->makeEndIterator(it);
- return const_iterator(it);
- }
- break;
-#else
case arrayValue:
case objectValue:
if (value_.map_)
return const_iterator(value_.map_->end());
break;
-#endif
default:
break;
}
@@ -1280,28 +1490,11 @@ Value::const_iterator Value::end() const {
Value::iterator Value::begin() {
switch (type_) {
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
- case arrayValue:
- if (value_.array_) {
- ValueInternalArray::IteratorState it;
- value_.array_->makeBeginIterator(it);
- return iterator(it);
- }
- break;
- case objectValue:
- if (value_.map_) {
- ValueInternalMap::IteratorState it;
- value_.map_->makeBeginIterator(it);
- return iterator(it);
- }
- break;
-#else
case arrayValue:
case objectValue:
if (value_.map_)
return iterator(value_.map_->begin());
break;
-#endif
default:
break;
}
@@ -1310,28 +1503,11 @@ Value::iterator Value::begin() {
Value::iterator Value::end() {
switch (type_) {
-#ifdef JSON_VALUE_USE_INTERNAL_MAP
- case arrayValue:
- if (value_.array_) {
- ValueInternalArray::IteratorState it;
- value_.array_->makeEndIterator(it);
- return iterator(it);
- }
- break;
- case objectValue:
- if (value_.map_) {
- ValueInternalMap::IteratorState it;
- value_.map_->makeEndIterator(it);
- return iterator(it);
- }
- break;
-#else
case arrayValue:
case objectValue:
if (value_.map_)
return iterator(value_.map_->end());
break;
-#endif
default:
break;
}
@@ -1349,19 +1525,20 @@ PathArgument::PathArgument(ArrayIndex index)
PathArgument::PathArgument(const char* key)
: key_(key), index_(), kind_(kindKey) {}
-PathArgument::PathArgument(const std::string& key)
+PathArgument::PathArgument(const JSONCPP_STRING& key)
: key_(key.c_str()), index_(), kind_(kindKey) {}
// class Path
// //////////////////////////////////////////////////////////////////
-Path::Path(const std::string& path,
+Path::Path(const JSONCPP_STRING& path,
const PathArgument& a1,
const PathArgument& a2,
const PathArgument& a3,
const PathArgument& a4,
const PathArgument& a5) {
InArgs in;
+ in.reserve(5);
in.push_back(&a1);
in.push_back(&a2);
in.push_back(&a3);
@@ -1370,7 +1547,7 @@ Path::Path(const std::string& path,
makePath(path, in);
}
-void Path::makePath(const std::string& path, const InArgs& in) {
+void Path::makePath(const JSONCPP_STRING& path, const InArgs& in) {
const char* current = path.c_str();
const char* end = current + path.length();
InArgs::const_iterator itInArg = in.begin();
@@ -1385,23 +1562,23 @@ void Path::makePath(const std::string& path, const InArgs& in) {
index = index * 10 + ArrayIndex(*current - '0');
args_.push_back(index);
}
- if (current == end || *current++ != ']')
+ if (current == end || *++current != ']')
invalidPath(path, int(current - path.c_str()));
} else if (*current == '%') {
addPathInArg(path, in, itInArg, PathArgument::kindKey);
++current;
- } else if (*current == '.') {
+ } else if (*current == '.' || *current == ']') {
++current;
} else {
const char* beginName = current;
while (current != end && !strchr("[.", *current))
++current;
- args_.push_back(std::string(beginName, current));
+ args_.push_back(JSONCPP_STRING(beginName, current));
}
}
}
-void Path::addPathInArg(const std::string& /*path*/,
+void Path::addPathInArg(const JSONCPP_STRING& /*path*/,
const InArgs& in,
InArgs::const_iterator& itInArg,
PathArgument::Kind kind) {
@@ -1410,11 +1587,11 @@ void Path::addPathInArg(const std::string& /*path*/,
} else if ((*itInArg)->kind_ != kind) {
// Error: bad argument type
} else {
- args_.push_back(**itInArg);
+ args_.push_back(**itInArg++);
}
}
-void Path::invalidPath(const std::string& /*path*/, int /*location*/) {
+void Path::invalidPath(const JSONCPP_STRING& /*path*/, int /*location*/) {
// Error: invalid path.
}
@@ -1425,16 +1602,19 @@ const Value& Path::resolve(const Value& root) const {
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;
}
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;
}
node = &((*node)[arg.key_]);
- if (node == &Value::null) {
+ if (node == &Value::nullSingleton()) {
// Error: unable to resolve path (object has no member named '' at
// position...)
+ return Value::null;
}
}
}
@@ -1453,7 +1633,7 @@ Value Path::resolve(const Value& root, const Value& defaultValue) const {
if (!node->isObject())
return defaultValue;
node = &((*node)[arg.key_]);
- if (node == &Value::null)
+ if (node == &Value::nullSingleton())
return defaultValue;
}
}
diff --git a/Utilities/cmjsoncpp/src/lib_json/json_valueiterator.inl b/Utilities/cmjsoncpp/src/lib_json/json_valueiterator.inl
index a9f7df63a..5243bfe4b 100644
--- a/Utilities/cmjsoncpp/src/lib_json/json_valueiterator.inl
+++ b/Utilities/cmjsoncpp/src/lib_json/json_valueiterator.inl
@@ -1,4 +1,4 @@
-// Copyright 2007-2010 Baptiste Lepilleur
+// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
@@ -16,68 +16,29 @@ namespace Json {
// //////////////////////////////////////////////////////////////////
ValueIteratorBase::ValueIteratorBase()
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
: current_(), isNull_(true) {
}
-#else
- : isArray_(true), isNull_(true) {
- iterator_.array_ = ValueInternalArray::IteratorState();
-}
-#endif
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
ValueIteratorBase::ValueIteratorBase(
const Value::ObjectValues::iterator& current)
: current_(current), isNull_(false) {}
-#else
-ValueIteratorBase::ValueIteratorBase(
- const ValueInternalArray::IteratorState& state)
- : isArray_(true) {
- iterator_.array_ = state;
-}
-
-ValueIteratorBase::ValueIteratorBase(
- const ValueInternalMap::IteratorState& state)
- : isArray_(false) {
- iterator_.map_ = state;
-}
-#endif
Value& ValueIteratorBase::deref() const {
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
return current_->second;
-#else
- if (isArray_)
- return ValueInternalArray::dereference(iterator_.array_);
- return ValueInternalMap::value(iterator_.map_);
-#endif
}
void ValueIteratorBase::increment() {
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
++current_;
-#else
- if (isArray_)
- ValueInternalArray::increment(iterator_.array_);
- ValueInternalMap::increment(iterator_.map_);
-#endif
}
void ValueIteratorBase::decrement() {
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
--current_;
-#else
- if (isArray_)
- ValueInternalArray::decrement(iterator_.array_);
- ValueInternalMap::decrement(iterator_.map_);
-#endif
}
ValueIteratorBase::difference_type
ValueIteratorBase::computeDistance(const SelfType& other) const {
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
#ifdef JSON_USE_CPPTL_SMALLMAP
- return current_ - other.current_;
+ return other.current_ - current_;
#else
// Iterator for null value are initialized using the default
// constructor, which initialize current_ to the default
@@ -100,80 +61,58 @@ ValueIteratorBase::computeDistance(const SelfType& other) const {
}
return myDistance;
#endif
-#else
- if (isArray_)
- return ValueInternalArray::distance(iterator_.array_,
- other.iterator_.array_);
- return ValueInternalMap::distance(iterator_.map_, other.iterator_.map_);
-#endif
}
bool ValueIteratorBase::isEqual(const SelfType& other) const {
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
if (isNull_) {
return other.isNull_;
}
return current_ == other.current_;
-#else
- if (isArray_)
- return ValueInternalArray::equals(iterator_.array_, other.iterator_.array_);
- return ValueInternalMap::equals(iterator_.map_, other.iterator_.map_);
-#endif
}
void ValueIteratorBase::copy(const SelfType& other) {
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
current_ = other.current_;
isNull_ = other.isNull_;
-#else
- if (isArray_)
- iterator_.array_ = other.iterator_.array_;
- iterator_.map_ = other.iterator_.map_;
-#endif
}
Value ValueIteratorBase::key() const {
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
const Value::CZString czstring = (*current_).first;
- if (czstring.c_str()) {
+ if (czstring.data()) {
if (czstring.isStaticString())
- return Value(StaticString(czstring.c_str()));
- return Value(czstring.c_str());
+ return Value(StaticString(czstring.data()));
+ return Value(czstring.data(), czstring.data() + czstring.length());
}
return Value(czstring.index());
-#else
- if (isArray_)
- return Value(ValueInternalArray::indexOf(iterator_.array_));
- bool isStatic;
- const char* memberName = ValueInternalMap::key(iterator_.map_, isStatic);
- if (isStatic)
- return Value(StaticString(memberName));
- return Value(memberName);
-#endif
}
UInt ValueIteratorBase::index() const {
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
const Value::CZString czstring = (*current_).first;
- if (!czstring.c_str())
+ if (!czstring.data())
return czstring.index();
return Value::UInt(-1);
-#else
- if (isArray_)
- return Value::UInt(ValueInternalArray::indexOf(iterator_.array_));
- return Value::UInt(-1);
-#endif
}
-const char* ValueIteratorBase::memberName() const {
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
- const char* name = (*current_).first.c_str();
- return name ? name : "";
-#else
- if (!isArray_)
- return ValueInternalMap::key(iterator_.map_);
- return "";
-#endif
+JSONCPP_STRING ValueIteratorBase::name() const {
+ char const* keey;
+ char const* end;
+ keey = memberName(&end);
+ if (!keey) return JSONCPP_STRING();
+ return JSONCPP_STRING(keey, end);
+}
+
+char const* ValueIteratorBase::memberName() const {
+ const char* cname = (*current_).first.data();
+ return cname ? cname : "";
+}
+
+char const* ValueIteratorBase::memberName(char const** end) const {
+ const char* cname = (*current_).first.data();
+ if (!cname) {
+ *end = NULL;
+ return NULL;
+ }
+ *end = cname + (*current_).first.length();
+ return cname;
}
// //////////////////////////////////////////////////////////////////
@@ -186,19 +125,12 @@ const char* ValueIteratorBase::memberName() const {
ValueConstIterator::ValueConstIterator() {}
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
ValueConstIterator::ValueConstIterator(
const Value::ObjectValues::iterator& current)
: ValueIteratorBase(current) {}
-#else
-ValueConstIterator::ValueConstIterator(
- const ValueInternalArray::IteratorState& state)
- : ValueIteratorBase(state) {}
-ValueConstIterator::ValueConstIterator(
- const ValueInternalMap::IteratorState& state)
- : ValueIteratorBase(state) {}
-#endif
+ValueConstIterator::ValueConstIterator(ValueIterator const& other)
+ : ValueIteratorBase(other) {}
ValueConstIterator& ValueConstIterator::
operator=(const ValueIteratorBase& other) {
@@ -216,19 +148,13 @@ operator=(const ValueIteratorBase& other) {
ValueIterator::ValueIterator() {}
-#ifndef JSON_VALUE_USE_INTERNAL_MAP
ValueIterator::ValueIterator(const Value::ObjectValues::iterator& current)
: ValueIteratorBase(current) {}
-#else
-ValueIterator::ValueIterator(const ValueInternalArray::IteratorState& state)
- : ValueIteratorBase(state) {}
-
-ValueIterator::ValueIterator(const ValueInternalMap::IteratorState& state)
- : ValueIteratorBase(state) {}
-#endif
ValueIterator::ValueIterator(const ValueConstIterator& other)
- : ValueIteratorBase(other) {}
+ : ValueIteratorBase(other) {
+ throwRuntimeError("ConstIterator to Iterator should never be allowed.");
+}
ValueIterator::ValueIterator(const ValueIterator& other)
: ValueIteratorBase(other) {}
diff --git a/Utilities/cmjsoncpp/src/lib_json/json_writer.cpp b/Utilities/cmjsoncpp/src/lib_json/json_writer.cpp
index e3f4e53cf..6e6e57e1f 100644
--- a/Utilities/cmjsoncpp/src/lib_json/json_writer.cpp
+++ b/Utilities/cmjsoncpp/src/lib_json/json_writer.cpp
@@ -1,4 +1,4 @@
-// Copyright 2011 Baptiste Lepilleur
+// Copyright 2011 Baptiste Lepilleur and The JsonCpp Authors
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
@@ -7,15 +7,62 @@
#include <json/writer.h>
#include "json_tool.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
-#include <utility>
-#include <assert.h>
-#include <stdio.h>
-#include <string.h>
-#include <sstream>
#include <iomanip>
+#include <memory>
+#include <sstream>
+#include <utility>
+#include <set>
+#include <cassert>
+#include <cstring>
+#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
+#endif
+#elif defined(_AIX)
+#if !defined(isfinite)
#include <math.h>
+#define isfinite finite
+#endif
+#elif defined(__hpux)
+#if !defined(isfinite)
+#if defined(__ia64) && !defined(finite)
+#define isfinite(x) ((sizeof(x) == sizeof(float) ? \
+ _Isfinitef(x) : _IsFinite(x)))
+#else
+#include <math.h>
+#define isfinite finite
+#endif
+#endif
+#else
+#include <cmath>
+#if !(defined(__QNXNTO__)) // QNX already defines isfinite
+#define isfinite std::isfinite
+#endif
+#endif
+
+#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
-#if defined(_MSC_VER) && _MSC_VER < 1500 // VC++ 8.0 and below
+#if defined(__BORLANDC__)
#include <float.h>
#define isfinite _finite
#define snprintf _snprintf
@@ -62,6 +109,12 @@
namespace Json {
+#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
+typedef std::unique_ptr<StreamWriter> StreamWriterPtr;
+#else
+typedef std::auto_ptr<StreamWriter> StreamWriterPtr;
+#endif
+
static bool containsControlCharacter(const char* str) {
while (*str) {
if (isControlCharacter(*(str++)))
@@ -70,20 +123,33 @@ static bool containsControlCharacter(const char* str) {
return false;
}
-std::string valueToString(LargestInt value) {
+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) {
UIntToStringBuffer buffer;
char* current = buffer + sizeof(buffer);
- bool isNegative = value < 0;
- if (isNegative)
- value = -value;
- uintToString(LargestUInt(value), current);
- if (isNegative)
+ if (value == Value::minLargestInt) {
+ uintToString(LargestUInt(Value::maxLargestInt) + 1, current);
*--current = '-';
+ } else if (value < 0) {
+ uintToString(LargestUInt(-value), current);
+ *--current = '-';
+ } else {
+ uintToString(LargestUInt(value), current);
+ }
assert(current >= buffer);
return current;
}
-std::string valueToString(LargestUInt value) {
+JSONCPP_STRING valueToString(LargestUInt value) {
UIntToStringBuffer buffer;
char* current = buffer + sizeof(buffer);
uintToString(value, current);
@@ -93,68 +159,70 @@ std::string valueToString(LargestUInt value) {
#if defined(JSON_HAS_INT64)
-std::string valueToString(Int value) {
+JSONCPP_STRING valueToString(Int value) {
return valueToString(LargestInt(value));
}
-std::string valueToString(UInt value) {
+JSONCPP_STRING valueToString(UInt value) {
return valueToString(LargestUInt(value));
}
#endif // # if defined(JSON_HAS_INT64)
-std::string valueToString(double value) {
+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[32];
+ char buffer[36];
int len = -1;
-// Print into the buffer. We need not request the alternative representation
-// that always has a decimal point because JSON doesn't distingish the
-// concepts of reals and integers.
-#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__) // Use secure version with
- // visual studio 2005 to
- // avoid warning.
-#if defined(WINCE)
- len = _snprintf(buffer, sizeof(buffer), "%.16g", value);
-#else
- len = sprintf_s(buffer, sizeof(buffer), "%.16g", value);
-#endif
-#else
+ char formatString[15];
+ snprintf(formatString, sizeof(formatString), "%%.%dg", precision);
+
+ // Print into the buffer. We need not request the alternative representation
+ // that always has a decimal point because JSON doesn't distingish the
+ // concepts of reals and integers.
if (isfinite(value)) {
- len = snprintf(buffer, sizeof(buffer), "%.16g", value);
+ len = snprintf(buffer, sizeof(buffer), formatString, value);
+ fixNumericLocale(buffer, buffer + len);
+
+ // 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");
+ }
+
} else {
// IEEE standard states that NaN values will not compare to themselves
if (value != value) {
- len = snprintf(buffer, sizeof(buffer), "null");
+ len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "NaN" : "null");
} else if (value < 0) {
- len = snprintf(buffer, sizeof(buffer), "-1e+9999");
+ len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "-Infinity" : "-1e+9999");
} else {
- len = snprintf(buffer, sizeof(buffer), "1e+9999");
+ len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "Infinity" : "1e+9999");
}
- // For those, we do not need to call fixNumLoc, but it is fast.
}
-#endif
assert(len >= 0);
- fixNumericLocale(buffer, buffer + len);
return buffer;
}
+}
+
+JSONCPP_STRING valueToString(double value) { return valueToString(value, false, 17); }
-std::string valueToString(bool value) { return value ? "true" : "false"; }
+JSONCPP_STRING valueToString(bool value) { return value ? "true" : "false"; }
-std::string valueToQuotedString(const char* value) {
+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 std::string("\"") + value + "\"";
+ return JSONCPP_STRING("\"") + value + "\"";
// We have to walk value and escape any special characters.
- // Appending to std::string is not efficient, but this should be rare.
+ // Appending to JSONCPP_STRING is not efficient, but this should be rare.
// (Note: forward slashes are *not* rare, but I am not escaping them.)
- std::string::size_type maxsize =
+ JSONCPP_STRING::size_type maxsize =
strlen(value) * 2 + 3; // allescaped+quotes+NULL
- std::string result;
+ JSONCPP_STRING result;
result.reserve(maxsize); // to avoid lots of mallocs
result += "\"";
for (const char* c = value; *c != 0; ++c) {
@@ -190,7 +258,85 @@ std::string valueToQuotedString(const char* value) {
// sequence from occurring.
default:
if (isControlCharacter(*c)) {
- std::ostringstream oss;
+ 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;
+ }
+ }
+ result += "\"";
+ 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);
+
+ 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 JSONCPP_STRING valueToQuotedStringN(const char* value, unsigned length) {
+ if (value == NULL)
+ return "";
+ // Not sure how to handle unicode...
+ if (strnpbrk(value, "\"\\\b\f\n\r\t", length) == NULL &&
+ !containsControlCharacter0(value, length))
+ 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 =
+ length * 2 + 3; // allescaped+quotes+NULL
+ JSONCPP_STRING result;
+ result.reserve(maxsize); // to avoid lots of mallocs
+ result += "\"";
+ char const* end = value + length;
+ for (const char* c = value; c != end; ++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)) || (*c == 0)) {
+ JSONCPP_OSTRINGSTREAM oss;
oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
<< std::setw(4) << static_cast<int>(*c);
result += oss.str();
@@ -221,8 +367,8 @@ void FastWriter::dropNullPlaceholders() { dropNullPlaceholders_ = true; }
void FastWriter::omitEndingLineFeed() { omitEndingLineFeed_ = true; }
-std::string FastWriter::write(const Value& root) {
- document_ = "";
+JSONCPP_STRING FastWriter::write(const Value& root) {
+ document_.clear();
writeValue(root);
if (!omitEndingLineFeed_)
document_ += "\n";
@@ -245,15 +391,21 @@ void FastWriter::writeValue(const Value& value) {
document_ += valueToString(value.asDouble());
break;
case stringValue:
- document_ += valueToQuotedString(value.asCString());
+ {
+ // 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));
break;
+ }
case booleanValue:
document_ += valueToString(value.asBool());
break;
case arrayValue: {
document_ += '[';
- int size = value.size();
- for (int index = 0; index < size; ++index) {
+ ArrayIndex size = value.size();
+ for (ArrayIndex index = 0; index < size; ++index) {
if (index > 0)
document_ += ',';
writeValue(value[index]);
@@ -265,10 +417,10 @@ void FastWriter::writeValue(const Value& value) {
document_ += '{';
for (Value::Members::iterator it = members.begin(); it != members.end();
++it) {
- const std::string& name = *it;
+ const JSONCPP_STRING& name = *it;
if (it != members.begin())
document_ += ',';
- document_ += valueToQuotedString(name.c_str());
+ document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length()));
document_ += yamlCompatiblityEnabled_ ? ": " : ":";
writeValue(value[name]);
}
@@ -283,10 +435,10 @@ void FastWriter::writeValue(const Value& value) {
StyledWriter::StyledWriter()
: rightMargin_(74), indentSize_(3), addChildValues_() {}
-std::string StyledWriter::write(const Value& root) {
- document_ = "";
+JSONCPP_STRING StyledWriter::write(const Value& root) {
+ document_.clear();
addChildValues_ = false;
- indentString_ = "";
+ indentString_.clear();
writeCommentBeforeValue(root);
writeValue(root);
writeCommentAfterValueOnSameLine(root);
@@ -309,8 +461,15 @@ void StyledWriter::writeValue(const Value& value) {
pushValue(valueToString(value.asDouble()));
break;
case stringValue:
- pushValue(valueToQuotedString(value.asCString()));
+ {
+ // 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("");
break;
+ }
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
@@ -326,7 +485,7 @@ void StyledWriter::writeValue(const Value& value) {
indent();
Value::Members::iterator it = members.begin();
for (;;) {
- const std::string& name = *it;
+ const JSONCPP_STRING& name = *it;
const Value& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
@@ -390,23 +549,25 @@ void StyledWriter::writeArrayValue(const Value& value) {
}
bool StyledWriter::isMultineArray(const Value& value) {
- int size = value.size();
+ ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
- for (int index = 0; index < size && !isMultiLine; ++index) {
+ for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
const Value& childValue = value[index];
- isMultiLine =
- isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
+ isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0);
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
- int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
- for (int index = 0; index < size; ++index) {
+ ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
+ for (ArrayIndex index = 0; index < size; ++index) {
+ if (hasCommentForValue(value[index])) {
+ isMultiLine = true;
+ }
writeValue(value[index]);
- lineLength += int(childValues_[index].length());
+ lineLength += static_cast<ArrayIndex>(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
@@ -414,7 +575,7 @@ bool StyledWriter::isMultineArray(const Value& value) {
return isMultiLine;
}
-void StyledWriter::pushValue(const std::string& value) {
+void StyledWriter::pushValue(const JSONCPP_STRING& value) {
if (addChildValues_)
childValues_.push_back(value);
else
@@ -432,15 +593,15 @@ void StyledWriter::writeIndent() {
document_ += indentString_;
}
-void StyledWriter::writeWithIndent(const std::string& value) {
+void StyledWriter::writeWithIndent(const JSONCPP_STRING& value) {
writeIndent();
document_ += value;
}
-void StyledWriter::indent() { indentString_ += std::string(indentSize_, ' '); }
+void StyledWriter::indent() { indentString_ += JSONCPP_STRING(indentSize_, ' '); }
void StyledWriter::unindent() {
- assert(int(indentString_.size()) >= indentSize_);
+ assert(indentString_.size() >= indentSize_);
indentString_.resize(indentString_.size() - indentSize_);
}
@@ -450,26 +611,27 @@ void StyledWriter::writeCommentBeforeValue(const Value& root) {
document_ += "\n";
writeIndent();
- std::string normalizedComment = normalizeEOL(root.getComment(commentBefore));
- std::string::const_iterator iter = normalizedComment.begin();
- while (iter != normalizedComment.end()) {
+ const JSONCPP_STRING& comment = root.getComment(commentBefore);
+ JSONCPP_STRING::const_iterator iter = comment.begin();
+ while (iter != comment.end()) {
document_ += *iter;
- if (*iter == '\n' && *(iter + 1) == '/')
+ if (*iter == '\n' &&
+ (iter != comment.end() && *(iter + 1) == '/'))
writeIndent();
++iter;
}
- // Comments are stripped of newlines, so add one here
+ // Comments are stripped of trailing newlines, so add one here
document_ += "\n";
}
void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) {
if (root.hasComment(commentAfterOnSameLine))
- document_ += " " + normalizeEOL(root.getComment(commentAfterOnSameLine));
+ document_ += " " + root.getComment(commentAfterOnSameLine);
if (root.hasComment(commentAfter)) {
document_ += "\n";
- document_ += normalizeEOL(root.getComment(commentAfter));
+ document_ += root.getComment(commentAfter);
document_ += "\n";
}
}
@@ -480,37 +642,21 @@ bool StyledWriter::hasCommentForValue(const Value& value) {
value.hasComment(commentAfter);
}
-std::string StyledWriter::normalizeEOL(const std::string& text) {
- std::string normalized;
- normalized.reserve(text.length());
- const char* begin = text.c_str();
- const char* end = begin + text.length();
- const char* current = begin;
- while (current != end) {
- char c = *current++;
- if (c == '\r') // mac or dos EOL
- {
- if (*current == '\n') // convert dos EOL
- ++current;
- normalized += '\n';
- } else // handle unix EOL & other char
- normalized += c;
- }
- return normalized;
-}
-
// Class StyledStreamWriter
// //////////////////////////////////////////////////////////////////
-StyledStreamWriter::StyledStreamWriter(std::string indentation)
+StyledStreamWriter::StyledStreamWriter(JSONCPP_STRING indentation)
: document_(NULL), rightMargin_(74), indentation_(indentation),
addChildValues_() {}
-void StyledStreamWriter::write(std::ostream& out, const Value& root) {
+void StyledStreamWriter::write(JSONCPP_OSTREAM& out, const Value& root) {
document_ = &out;
addChildValues_ = false;
- indentString_ = "";
+ indentString_.clear();
+ indented_ = true;
writeCommentBeforeValue(root);
+ if (!indented_) writeIndent();
+ indented_ = true;
writeValue(root);
writeCommentAfterValueOnSameLine(root);
*document_ << "\n";
@@ -532,8 +678,15 @@ void StyledStreamWriter::writeValue(const Value& value) {
pushValue(valueToString(value.asDouble()));
break;
case stringValue:
- pushValue(valueToQuotedString(value.asCString()));
+ {
+ // 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("");
break;
+ }
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
@@ -549,7 +702,7 @@ void StyledStreamWriter::writeValue(const Value& value) {
indent();
Value::Members::iterator it = members.begin();
for (;;) {
- const std::string& name = *it;
+ const JSONCPP_STRING& name = *it;
const Value& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
@@ -586,8 +739,10 @@ void StyledStreamWriter::writeArrayValue(const Value& value) {
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
- writeIndent();
+ if (!indented_) writeIndent();
+ indented_ = true;
writeValue(childValue);
+ indented_ = false;
}
if (++index == size) {
writeCommentAfterValueOnSameLine(childValue);
@@ -613,23 +768,25 @@ void StyledStreamWriter::writeArrayValue(const Value& value) {
}
bool StyledStreamWriter::isMultineArray(const Value& value) {
- int size = value.size();
+ ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
- for (int index = 0; index < size && !isMultiLine; ++index) {
+ for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
const Value& childValue = value[index];
- isMultiLine =
- isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
+ isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0);
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
- int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
- for (int index = 0; index < size; ++index) {
+ ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
+ for (ArrayIndex index = 0; index < size; ++index) {
+ if (hasCommentForValue(value[index])) {
+ isMultiLine = true;
+ }
writeValue(value[index]);
- lineLength += int(childValues_[index].length());
+ lineLength += static_cast<ArrayIndex>(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
@@ -637,7 +794,7 @@ bool StyledStreamWriter::isMultineArray(const Value& value) {
return isMultiLine;
}
-void StyledStreamWriter::pushValue(const std::string& value) {
+void StyledStreamWriter::pushValue(const JSONCPP_STRING& value) {
if (addChildValues_)
childValues_.push_back(value);
else
@@ -645,24 +802,17 @@ void StyledStreamWriter::pushValue(const std::string& value) {
}
void StyledStreamWriter::writeIndent() {
- /*
- Some comments in this method would have been nice. ;-)
-
- if ( !document_.empty() )
- {
- char last = document_[document_.length()-1];
- if ( last == ' ' ) // already indented
- return;
- if ( last != '\n' ) // Comments may add new-line
- *document_ << '\n';
- }
- */
+ // blep intended this to look at the so-far-written string
+ // to determine whether we are already indented, but
+ // with a stream we cannot do that. So we rely on some saved state.
+ // The caller checks indented_.
*document_ << '\n' << indentString_;
}
-void StyledStreamWriter::writeWithIndent(const std::string& value) {
- writeIndent();
+void StyledStreamWriter::writeWithIndent(const JSONCPP_STRING& value) {
+ if (!indented_) writeIndent();
*document_ << value;
+ indented_ = false;
}
void StyledStreamWriter::indent() { indentString_ += indentation_; }
@@ -675,19 +825,30 @@ void StyledStreamWriter::unindent() {
void StyledStreamWriter::writeCommentBeforeValue(const Value& root) {
if (!root.hasComment(commentBefore))
return;
- *document_ << normalizeEOL(root.getComment(commentBefore));
- *document_ << "\n";
+
+ if (!indented_) writeIndent();
+ const JSONCPP_STRING& comment = root.getComment(commentBefore);
+ JSONCPP_STRING::const_iterator iter = comment.begin();
+ while (iter != comment.end()) {
+ *document_ << *iter;
+ if (*iter == '\n' &&
+ (iter != comment.end() && *(iter + 1) == '/'))
+ // writeIndent(); // would include newline
+ *document_ << indentString_;
+ ++iter;
+ }
+ indented_ = false;
}
void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) {
if (root.hasComment(commentAfterOnSameLine))
- *document_ << " " + normalizeEOL(root.getComment(commentAfterOnSameLine));
+ *document_ << ' ' << root.getComment(commentAfterOnSameLine);
if (root.hasComment(commentAfter)) {
- *document_ << "\n";
- *document_ << normalizeEOL(root.getComment(commentAfter));
- *document_ << "\n";
+ writeIndent();
+ *document_ << root.getComment(commentAfter);
}
+ indented_ = false;
}
bool StyledStreamWriter::hasCommentForValue(const Value& value) {
@@ -696,28 +857,400 @@ bool StyledStreamWriter::hasCommentForValue(const Value& value) {
value.hasComment(commentAfter);
}
-std::string StyledStreamWriter::normalizeEOL(const std::string& text) {
- std::string normalized;
- normalized.reserve(text.length());
- const char* begin = text.c_str();
- const char* end = begin + text.length();
- const char* current = begin;
- while (current != end) {
- char c = *current++;
- if (c == '\r') // mac or dos EOL
+//////////////////////////
+// BuiltStyledStreamWriter
+
+/// Scoped enums are not available until C++11.
+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.
+ };
+};
+
+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;
+private:
+ void writeValue(Value const& value);
+ void writeArrayValue(Value const& value);
+ bool isMultineArray(Value const& value);
+ void pushValue(JSONCPP_STRING const& value);
+ void writeIndent();
+ void writeWithIndent(JSONCPP_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;
+
+ ChildValues childValues_;
+ JSONCPP_STRING indentString_;
+ unsigned int rightMargin_;
+ JSONCPP_STRING indentation_;
+ CommentStyle::Enum cs_;
+ JSONCPP_STRING colonSymbol_;
+ JSONCPP_STRING nullSymbol_;
+ JSONCPP_STRING endingLineFeedSymbol_;
+ bool addChildValues_ : 1;
+ bool indented_ : 1;
+ bool useSpecialFloats_ : 1;
+ unsigned int precision_;
+};
+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)
+{
+ sout_ = sout;
+ addChildValues_ = false;
+ indented_ = true;
+ indentString_.clear();
+ writeCommentBeforeValue(root);
+ if (!indented_) writeIndent();
+ indented_ = true;
+ writeValue(root);
+ writeCommentAfterValueOnSameLine(root);
+ *sout_ << endingLineFeedSymbol_;
+ sout_ = NULL;
+ return 0;
+}
+void BuiltStyledStreamWriter::writeValue(Value const& value) {
+ switch (value.type()) {
+ case nullValue:
+ pushValue(nullSymbol_);
+ break;
+ case intValue:
+ pushValue(valueToString(value.asLargestInt()));
+ break;
+ case uintValue:
+ pushValue(valueToString(value.asLargestUInt()));
+ break;
+ case realValue:
+ pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_));
+ break;
+ 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("");
+ break;
+ }
+ case booleanValue:
+ pushValue(valueToString(value.asBool()));
+ break;
+ case arrayValue:
+ writeArrayValue(value);
+ break;
+ case objectValue: {
+ Value::Members members(value.getMemberNames());
+ if (members.empty())
+ pushValue("{}");
+ else {
+ writeWithIndent("{");
+ indent();
+ Value::Members::iterator it = members.begin();
+ for (;;) {
+ JSONCPP_STRING const& name = *it;
+ Value const& childValue = value[name];
+ writeCommentBeforeValue(childValue);
+ writeWithIndent(valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())));
+ *sout_ << colonSymbol_;
+ writeValue(childValue);
+ if (++it == members.end()) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ *sout_ << ",";
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("}");
+ }
+ } break;
+ }
+}
+
+void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
+ unsigned size = value.size();
+ if (size == 0)
+ pushValue("[]");
+ else {
+ bool isMultiLine = (cs_ == CommentStyle::All) || isMultineArray(value);
+ if (isMultiLine) {
+ writeWithIndent("[");
+ indent();
+ bool hasChildValue = !childValues_.empty();
+ unsigned index = 0;
+ for (;;) {
+ Value const& childValue = value[index];
+ writeCommentBeforeValue(childValue);
+ if (hasChildValue)
+ writeWithIndent(childValues_[index]);
+ else {
+ if (!indented_) writeIndent();
+ indented_ = true;
+ writeValue(childValue);
+ indented_ = false;
+ }
+ if (++index == size) {
+ writeCommentAfterValueOnSameLine(childValue);
+ break;
+ }
+ *sout_ << ",";
+ writeCommentAfterValueOnSameLine(childValue);
+ }
+ unindent();
+ writeWithIndent("]");
+ } else // output on a single line
{
- if (*current == '\n') // convert dos EOL
- ++current;
- normalized += '\n';
- } else // handle unix EOL & other char
- normalized += c;
+ assert(childValues_.size() == size);
+ *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_ << " ";
+ *sout_ << "]";
+ }
+ }
+}
+
+bool BuiltStyledStreamWriter::isMultineArray(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);
+ }
+ if (!isMultiLine) // check if line length > max line length
+ {
+ childValues_.reserve(size);
+ addChildValues_ = true;
+ ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
+ for (ArrayIndex index = 0; index < size; ++index) {
+ if (hasCommentForValue(value[index])) {
+ isMultiLine = true;
+ }
+ writeValue(value[index]);
+ lineLength += static_cast<ArrayIndex>(childValues_[index].length());
+ }
+ addChildValues_ = false;
+ isMultiLine = isMultiLine || lineLength >= rightMargin_;
+ }
+ return isMultiLine;
+}
+
+void BuiltStyledStreamWriter::pushValue(JSONCPP_STRING const& value) {
+ if (addChildValues_)
+ childValues_.push_back(value);
+ else
+ *sout_ << value;
+}
+
+void BuiltStyledStreamWriter::writeIndent() {
+ // blep intended this to look at the so-far-written string
+ // to determine whether we are already indented, but
+ // with a stream we cannot do that. So we rely on some saved state.
+ // The caller checks indented_.
+
+ if (!indentation_.empty()) {
+ // In this case, drop newlines too.
+ *sout_ << '\n' << indentString_;
+ }
+}
+
+void BuiltStyledStreamWriter::writeWithIndent(JSONCPP_STRING const& value) {
+ if (!indented_) writeIndent();
+ *sout_ << value;
+ indented_ = false;
+}
+
+void BuiltStyledStreamWriter::indent() { indentString_ += indentation_; }
+
+void BuiltStyledStreamWriter::unindent() {
+ assert(indentString_.size() >= indentation_.size());
+ indentString_.resize(indentString_.size() - indentation_.size());
+}
+
+void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) {
+ 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();
+ while (iter != comment.end()) {
+ *sout_ << *iter;
+ if (*iter == '\n' &&
+ (iter != comment.end() && *(iter + 1) == '/'))
+ // writeIndent(); // would write extra newline
+ *sout_ << indentString_;
+ ++iter;
}
- return normalized;
+ indented_ = false;
+}
+
+void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(Value const& root) {
+ if (cs_ == CommentStyle::None) return;
+ if (root.hasComment(commentAfterOnSameLine))
+ *sout_ << " " + root.getComment(commentAfterOnSameLine);
+
+ if (root.hasComment(commentAfter)) {
+ writeIndent();
+ *sout_ << root.getComment(commentAfter);
+ }
+}
+
+// static
+bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) {
+ return value.hasComment(commentBefore) ||
+ value.hasComment(commentAfterOnSameLine) ||
+ value.hasComment(commentAfter);
+}
+
+///////////////
+// 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();
+ unsigned int pre = settings_["precision"].asUInt();
+ CommentStyle::Enum cs = CommentStyle::All;
+ if (cs_str == "All") {
+ cs = CommentStyle::All;
+ } else if (cs_str == "None") {
+ cs = CommentStyle::None;
+ } else {
+ throwRuntimeError("commentStyle must be 'All' or 'None'");
+ }
+ JSONCPP_STRING colonSymbol = " : ";
+ if (eyc) {
+ colonSymbol = ": ";
+ } else if (indentation.empty()) {
+ colonSymbol = ":";
+ }
+ JSONCPP_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);
+}
+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];
+ }
+ }
+ return 0u == inv.size();
+}
+Value& StreamWriterBuilder::operator[](JSONCPP_STRING key)
+{
+ return settings_[key];
+}
+// static
+void StreamWriterBuilder::setDefaults(Json::Value* settings)
+{
+ //! [StreamWriterBuilderDefaults]
+ (*settings)["commentStyle"] = "All";
+ (*settings)["indentation"] = "\t";
+ (*settings)["enableYAMLCompatibility"] = false;
+ (*settings)["dropNullPlaceholders"] = false;
+ (*settings)["useSpecialFloats"] = false;
+ (*settings)["precision"] = 17;
+ //! [StreamWriterBuilderDefaults]
+}
+
+JSONCPP_STRING writeString(StreamWriter::Factory const& builder, Value const& root) {
+ JSONCPP_OSTRINGSTREAM sout;
+ StreamWriterPtr const writer(builder.newStreamWriter());
+ writer->write(root, &sout);
+ return sout.str();
}
-std::ostream& operator<<(std::ostream& sout, const Value& root) {
- Json::StyledStreamWriter writer;
- writer.write(sout, root);
+JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM& sout, Value const& root) {
+ StreamWriterBuilder builder;
+ StreamWriterPtr const writer(builder.newStreamWriter());
+ writer->write(root, &sout);
return sout;
}
diff --git a/Utilities/cmlibarchive/.gitattributes b/Utilities/cmlibarchive/.gitattributes
deleted file mode 100644
index 562b12e16..000000000
--- a/Utilities/cmlibarchive/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -whitespace
diff --git a/Utilities/cmlibarchive/CMakeLists.txt b/Utilities/cmlibarchive/CMakeLists.txt
index bfe6b131e..206f3c6a5 100644
--- a/Utilities/cmlibarchive/CMakeLists.txt
+++ b/Utilities/cmlibarchive/CMakeLists.txt
@@ -422,6 +422,7 @@ int main(void) { return FS_IOC_GETFLAGS; }" HAVE_WORKING_FS_IOC_GETFLAGS)
LA_CHECK_INCLUDE_FILE("linux/magic.h" HAVE_LINUX_MAGIC_H)
LA_CHECK_INCLUDE_FILE("locale.h" HAVE_LOCALE_H)
+LA_CHECK_INCLUDE_FILE("membership.h" HAVE_MEMBERSHIP_H)
LA_CHECK_INCLUDE_FILE("memory.h" HAVE_MEMORY_H)
LA_CHECK_INCLUDE_FILE("paths.h" HAVE_PATHS_H)
LA_CHECK_INCLUDE_FILE("poll.h" HAVE_POLL_H)
@@ -439,11 +440,13 @@ LA_CHECK_INCLUDE_FILE("string.h" HAVE_STRING_H)
LA_CHECK_INCLUDE_FILE("strings.h" HAVE_STRINGS_H)
LA_CHECK_INCLUDE_FILE("sys/acl.h" HAVE_SYS_ACL_H)
LA_CHECK_INCLUDE_FILE("sys/cdefs.h" HAVE_SYS_CDEFS_H)
+LA_CHECK_INCLUDE_FILE("sys/extattr.h" HAVE_SYS_EXTATTR_H)
LA_CHECK_INCLUDE_FILE("sys/ioctl.h" HAVE_SYS_IOCTL_H)
LA_CHECK_INCLUDE_FILE("sys/mkdev.h" HAVE_SYS_MKDEV_H)
LA_CHECK_INCLUDE_FILE("sys/mount.h" HAVE_SYS_MOUNT_H)
LA_CHECK_INCLUDE_FILE("sys/param.h" HAVE_SYS_PARAM_H)
LA_CHECK_INCLUDE_FILE("sys/poll.h" HAVE_SYS_POLL_H)
+LA_CHECK_INCLUDE_FILE("sys/richacl.h" HAVE_SYS_RICHACL_H)
LA_CHECK_INCLUDE_FILE("sys/select.h" HAVE_SYS_SELECT_H)
LA_CHECK_INCLUDE_FILE("sys/stat.h" HAVE_SYS_STAT_H)
LA_CHECK_INCLUDE_FILE("sys/statfs.h" HAVE_SYS_STATFS_H)
@@ -453,6 +456,7 @@ LA_CHECK_INCLUDE_FILE("sys/utime.h" HAVE_SYS_UTIME_H)
LA_CHECK_INCLUDE_FILE("sys/utsname.h" HAVE_SYS_UTSNAME_H)
LA_CHECK_INCLUDE_FILE("sys/vfs.h" HAVE_SYS_VFS_H)
LA_CHECK_INCLUDE_FILE("sys/wait.h" HAVE_SYS_WAIT_H)
+LA_CHECK_INCLUDE_FILE("sys/xattr.h" HAVE_SYS_XATTR_H)
LA_CHECK_INCLUDE_FILE("time.h" HAVE_TIME_H)
LA_CHECK_INCLUDE_FILE("unistd.h" HAVE_UNISTD_H)
LA_CHECK_INCLUDE_FILE("utime.h" HAVE_UTIME_H)
@@ -461,6 +465,9 @@ LA_CHECK_INCLUDE_FILE("wctype.h" HAVE_WCTYPE_H)
LA_CHECK_INCLUDE_FILE("windows.h" HAVE_WINDOWS_H)
IF(ENABLE_CNG)
LA_CHECK_INCLUDE_FILE("Bcrypt.h" HAVE_BCRYPT_H)
+ IF(HAVE_BCRYPT_H)
+ LIST(APPEND ADDITIONAL_LIBS "Bcrypt")
+ ENDIF(HAVE_BCRYPT_H)
ELSE(ENABLE_CNG)
UNSET(HAVE_BCRYPT_H CACHE)
ENDIF(ENABLE_CNG)
@@ -924,7 +931,6 @@ CHECK_FUNCTION_EXISTS_GLIBC(chflags HAVE_CHFLAGS)
CHECK_FUNCTION_EXISTS_GLIBC(chown HAVE_CHOWN)
CHECK_FUNCTION_EXISTS_GLIBC(chroot HAVE_CHROOT)
CHECK_FUNCTION_EXISTS_GLIBC(ctime_r HAVE_CTIME_R)
-CHECK_FUNCTION_EXISTS_GLIBC(dirfd HAVE_DIRFD)
CHECK_FUNCTION_EXISTS_GLIBC(fchdir HAVE_FCHDIR)
CHECK_FUNCTION_EXISTS_GLIBC(fchflags HAVE_FCHFLAGS)
CHECK_FUNCTION_EXISTS_GLIBC(fchmod HAVE_FCHMOD)
@@ -1024,6 +1030,10 @@ CHECK_C_SOURCE_COMPILES(
"#include <dirent.h>\nint main() {DIR *d = opendir(\".\"); struct dirent e,*r; return readdir_r(d,&e,&r);}"
HAVE_READDIR_R)
+# dirfd can be either a function or a macro.
+CHECK_C_SOURCE_COMPILES(
+ "#include <dirent.h>\nint main() {DIR *d = opendir(\".\"); return dirfd(d);}"
+ HAVE_DIRFD)
# Only detect readlinkat() if we also have AT_FDCWD in unistd.h.
# NOTE: linux requires fcntl.h for AT_FDCWD.
@@ -1256,60 +1266,105 @@ CHECK_FILE_OFFSET_BITS()
# Check for Extended Attribute libraries, headers, and functions
#
IF(ENABLE_XATTR)
- LA_CHECK_INCLUDE_FILE(attr/xattr.h HAVE_ATTR_XATTR_H)
- LA_CHECK_INCLUDE_FILE(sys/xattr.h HAVE_SYS_XATTR_H)
- LA_CHECK_INCLUDE_FILE(sys/extattr.h HAVE_SYS_EXTATTR_H)
CHECK_LIBRARY_EXISTS(attr "setxattr" "" HAVE_LIBATTR)
IF(HAVE_LIBATTR)
SET(CMAKE_REQUIRED_LIBRARIES "attr")
ENDIF(HAVE_LIBATTR)
CHECK_SYMBOL_EXISTS(EXTATTR_NAMESPACE_USER "sys/types.h;sys/extattr.h" HAVE_DECL_EXTATTR_NAMESPACE_USER)
- CHECK_FUNCTION_EXISTS_GLIBC(extattr_get_file HAVE_EXTATTR_GET_FILE)
- CHECK_FUNCTION_EXISTS_GLIBC(extattr_list_file HAVE_EXTATTR_LIST_FILE)
- CHECK_FUNCTION_EXISTS_GLIBC(extattr_set_fd HAVE_EXTATTR_SET_FD)
- CHECK_FUNCTION_EXISTS_GLIBC(extattr_set_file HAVE_EXTATTR_SET_FILE)
- CHECK_FUNCTION_EXISTS_GLIBC(fgetxattr HAVE_FGETXATTR)
- CHECK_FUNCTION_EXISTS_GLIBC(flistxattr HAVE_FLISTXATTR)
- CHECK_FUNCTION_EXISTS_GLIBC(fsetxattr HAVE_FSETXATTR)
- CHECK_FUNCTION_EXISTS_GLIBC(getxattr HAVE_GETXATTR)
- CHECK_FUNCTION_EXISTS_GLIBC(lgetxattr HAVE_LGETXATTR)
- CHECK_FUNCTION_EXISTS_GLIBC(listxattr HAVE_LISTXATTR)
- CHECK_FUNCTION_EXISTS_GLIBC(llistxattr HAVE_LLISTXATTR)
- CHECK_FUNCTION_EXISTS_GLIBC(lsetxattr HAVE_LSETXATTR)
- CHECK_FUNCTION_EXISTS_GLIBC(fgetea HAVE_FGETEA)
- CHECK_FUNCTION_EXISTS_GLIBC(flistea HAVE_FLISTEA)
- CHECK_FUNCTION_EXISTS_GLIBC(fsetea HAVE_FSETEA)
- CHECK_FUNCTION_EXISTS_GLIBC(getea HAVE_GETEA)
- CHECK_FUNCTION_EXISTS_GLIBC(lgetea HAVE_LGETEA)
- CHECK_FUNCTION_EXISTS_GLIBC(listea HAVE_LISTEA)
- CHECK_FUNCTION_EXISTS_GLIBC(llistea HAVE_LLISTEA)
- CHECK_FUNCTION_EXISTS_GLIBC(lsetea HAVE_LSETEA)
+ CHECK_SYMBOL_EXISTS(XATTR_NOFOLLOW "sys/xattr.h" HAVE_DECL_XATTR_NOFOLLOW)
+ IF(HAVE_SYS_XATTR_H AND HAVE_DECL_XATTR_NOFOLLOW)
+ CHECK_FUNCTION_EXISTS(fgetxattr HAVE_FGETXATTR)
+ CHECK_FUNCTION_EXISTS(flistxattr HAVE_FLISTXATTR)
+ CHECK_FUNCTION_EXISTS(fsetxattr HAVE_FSETXATTR)
+ CHECK_FUNCTION_EXISTS(getxattr HAVE_GETXATTR)
+ CHECK_FUNCTION_EXISTS(listxattr HAVE_LISTXATTR)
+ CHECK_FUNCTION_EXISTS(setxattr HAVE_SETXATTR)
+ IF(HAVE_FGETXATTR AND
+ HAVE_FLISTXATTR AND
+ HAVE_FSETXATTR AND
+ HAVE_GETXATTR AND
+ HAVE_LISTXATTR AND
+ HAVE_SETXATTR)
+ SET(ARCHIVE_XATTR_DARWIN TRUE)
+ ENDIF()
+ ELSEIF(HAVE_SYS_EXTATTR_H AND HAVE_DECL_EXTATTR_NAMESPACE_USER)
+ # FreeBSD xattr support
+ CHECK_FUNCTION_EXISTS(extattr_get_fd HAVE_EXTATTR_GET_FD)
+ CHECK_FUNCTION_EXISTS(extattr_get_file HAVE_EXTATTR_GET_FILE)
+ CHECK_FUNCTION_EXISTS(extattr_get_link HAVE_EXTATTR_GET_LINK)
+ CHECK_FUNCTION_EXISTS(extattr_list_fd HAVE_EXTATTR_LIST_FD)
+ CHECK_FUNCTION_EXISTS(extattr_list_file HAVE_EXTATTR_LIST_FILE)
+ CHECK_FUNCTION_EXISTS(extattr_list_link HAVE_EXTATTR_LIST_LINK)
+ CHECK_FUNCTION_EXISTS(extattr_set_fd HAVE_EXTATTR_SET_FD)
+ CHECK_FUNCTION_EXISTS(extattr_set_link HAVE_EXTATTR_SET_LINK)
+ IF(HAVE_EXTATTR_GET_FD AND
+ HAVE_EXTATTR_GET_FILE AND
+ HAVE_EXTATTR_GET_LINK AND
+ HAVE_EXTATTR_LIST_FD AND
+ HAVE_EXTATTR_LIST_FILE AND
+ HAVE_EXTATTR_LIST_LINK AND
+ HAVE_EXTATTR_SET_FD AND
+ HAVE_EXTATTR_SET_LINK)
+ SET(ARCHIVE_XATTR_FREEBSD TRUE)
+ ENDIF()
+ ELSEIF(HAVE_SYS_XATTR_H OR HAVE_ATTR_XATTR_H)
+ # Linux xattr support
+ CHECK_FUNCTION_EXISTS_GLIBC(fgetxattr HAVE_FGETXATTR)
+ CHECK_FUNCTION_EXISTS_GLIBC(flistxattr HAVE_FLISTXATTR)
+ CHECK_FUNCTION_EXISTS_GLIBC(fsetxattr HAVE_FSETXATTR)
+ CHECK_FUNCTION_EXISTS_GLIBC(getxattr HAVE_GETXATTR)
+ CHECK_FUNCTION_EXISTS_GLIBC(lgetxattr HAVE_LGETXATTR)
+ CHECK_FUNCTION_EXISTS_GLIBC(listxattr HAVE_LISTXATTR)
+ CHECK_FUNCTION_EXISTS_GLIBC(llistxattr HAVE_LLISTXATTR)
+ CHECK_FUNCTION_EXISTS_GLIBC(lsetxattr HAVE_LSETXATTR)
+ IF(HAVE_FGETXATTR AND
+ HAVE_FLISTXATTR AND
+ HAVE_FSETXATTR AND
+ HAVE_GETXATTR AND
+ HAVE_LGETXATTR AND
+ HAVE_LISTXATTR AND
+ HAVE_LLISTXATTR AND
+ HAVE_LSETXATTR)
+ SET(ARCHIVE_XATTR_LINUX TRUE)
+ ENDIF()
+ ELSEIF(HAVE_SYS_EA_H)
+ # AIX xattr support
+ CHECK_FUNCTION_EXISTS(fgetea HAVE_FGETEA)
+ CHECK_FUNCTION_EXISTS(flistea HAVE_FLISTEA)
+ CHECK_FUNCTION_EXISTS(fsetea HAVE_FSETEA)
+ CHECK_FUNCTION_EXISTS(getea HAVE_GETEA)
+ CHECK_FUNCTION_EXISTS(lgetea HAVE_LGETEA)
+ CHECK_FUNCTION_EXISTS(listea HAVE_LISTEA)
+ CHECK_FUNCTION_EXISTS(llistea HAVE_LLISTEA)
+ CHECK_FUNCTION_EXISTS(lsetea HAVE_LSETEA)
+ IF(HAVE_FGETEA AND
+ HAVE_FLISTEA AND
+ HAVE_FSETEA AND
+ HAVE_GETEA AND
+ HAVE_LGETEA AND
+ HAVE_LISTEA AND
+ HAVE_LLISTEA AND
+ HAVE_LSETEA)
+ SET(ARCHIVE_XATTR_AIX TRUE)
+ ENDIF()
+ ENDIF()
+
+ IF(ARCHIVE_XATTR_DARWIN)
+ MESSAGE(STATUS "Extended attributes support: Darwin")
+ ELSEIF(ARCHIVE_XATTR_FREEBSD)
+ MESSAGE(STATUS "Extended attributes support: FreeBSD")
+ ELSEIF(ARCHIVE_XATTR_LINUX)
+ MESSAGE(STATUS "Extended attributes support: Linux")
+ ELSEIF(ARCHIVE_XATTR_AIX)
+ MESSAGE(STATUS "Extended attributes support: AIX")
+ ELSE()
+ MESSAGE(STATUS "Extended attributes support: none")
+ ENDIF()
ELSE(ENABLE_XATTR)
- SET(HAVE_ATTR_LIB FALSE)
- SET(HAVE_ATTR_XATTR_H FALSE)
- SET(HAVE_DECL_EXTATTR_NAMESPACE_USER FALSE)
- SET(HAVE_EXTATTR_GET_FILE FALSE)
- SET(HAVE_EXTATTR_LIST_FILE FALSE)
- SET(HAVE_EXTATTR_SET_FD FALSE)
- SET(HAVE_EXTATTR_SET_FILE FALSE)
- SET(HAVE_FGETEA FALSE)
- SET(HAVE_FGETXATTR FALSE)
- SET(HAVE_FLISTEA FALSE)
- SET(HAVE_FLISTXATTR FALSE)
- SET(HAVE_FSETEA FALSE)
- SET(HAVE_FSETXATTR FALSE)
- SET(HAVE_GETEA FALSE)
- SET(HAVE_GETXATTR FALSE)
- SET(HAVE_LGETEA FALSE)
- SET(HAVE_LGETXATTR FALSE)
- SET(HAVE_LISTEA FALSE)
- SET(HAVE_LISTXATTR FALSE)
- SET(HAVE_LLISTEA FALSE)
- SET(HAVE_LLISTXATTR FALSE)
- SET(HAVE_LSETEA FALSE)
- SET(HAVE_LSETXATTR FALSE)
- SET(HAVE_SYS_EXTATTR_H FALSE)
- SET(HAVE_SYS_XATTR_H FALSE)
+ SET(ARCHIVE_XATTR_DARWIN FALSE)
+ SET(ARCHIVE_XATTR_FREEBSD FALSE)
+ SET(ARCHIVE_XATTR_LINUX FALSE)
+ SET(ARCHIVE_XATTR_AIX FALSE)
ENDIF(ENABLE_XATTR)
#
@@ -1321,78 +1376,212 @@ ENDIF(ENABLE_XATTR)
# which makes the following checks rather more complex than I would like.
#
IF(ENABLE_ACL)
+ # Solaris and derivates ACLs
+ CHECK_FUNCTION_EXISTS(acl HAVE_ACL)
+ CHECK_FUNCTION_EXISTS(facl HAVE_FACL)
+
+ # Libacl
CHECK_LIBRARY_EXISTS(acl "acl_get_file" "" HAVE_LIBACL)
IF(HAVE_LIBACL)
SET(CMAKE_REQUIRED_LIBRARIES "acl")
FIND_LIBRARY(ACL_LIBRARY NAMES acl)
LIST(APPEND ADDITIONAL_LIBS ${ACL_LIBRARY})
ENDIF(HAVE_LIBACL)
- #
- CHECK_FUNCTION_EXISTS_GLIBC(acl_create_entry HAVE_ACL_CREATE_ENTRY)
- CHECK_FUNCTION_EXISTS_GLIBC(acl_init HAVE_ACL_INIT)
- CHECK_FUNCTION_EXISTS_GLIBC(acl_set_fd HAVE_ACL_SET_FD)
- CHECK_FUNCTION_EXISTS_GLIBC(acl_set_fd_np HAVE_ACL_SET_FD_NP)
- CHECK_FUNCTION_EXISTS_GLIBC(acl_set_file HAVE_ACL_SET_FILE)
- CHECK_TYPE_EXISTS(acl_permset_t "${INCLUDES}" HAVE_ACL_PERMSET_T)
-
- # The "acl_get_perm()" function was omitted from the POSIX draft.
- # (It's a pretty obvious oversight; otherwise, there's no way to
- # test for specific permissions in a permset.) Linux uses the obvious
- # name, FreeBSD adds _np to mark it as "non-Posix extension."
- # Test for both as a double-check that we really have POSIX-style ACL support.
- CHECK_FUNCTION_EXISTS(acl_get_fd_np HAVE_ACL_GET_FD_NP)
- CHECK_FUNCTION_EXISTS(acl_get_perm HAVE_ACL_GET_PERM)
- CHECK_FUNCTION_EXISTS(acl_get_perm_np HAVE_ACL_GET_PERM_NP)
- CHECK_FUNCTION_EXISTS(acl_get_link HAVE_ACL_GET_LINK)
- CHECK_FUNCTION_EXISTS(acl_get_link_np HAVE_ACL_GET_LINK_NP)
- CHECK_FUNCTION_EXISTS(acl_is_trivial_np HAVE_ACL_IS_TRIVIAL_NP)
- CHECK_FUNCTION_EXISTS(acl_set_link_np HAVE_ACL_SET_LINK_NP)
- CHECK_SYMBOL_EXISTS(ACL_TYPE_NFS4 "${INCLUDES}" HAVE_ACL_TYPE_NFS4)
-
- # MacOS has an acl.h that isn't POSIX. It can be detected by
- # checking for ACL_USER
- CHECK_SYMBOL_EXISTS(ACL_USER "${INCLUDES}" HAVE_ACL_USER)
- CHECK_C_SOURCE_COMPILES("#include <sys/types.h>
+
+ CHECK_TYPE_EXISTS(acl_t "sys/types.h;sys/acl.h" HAVE_ACL_T)
+ CHECK_TYPE_EXISTS(acl_entry_t "sys/types.h;sys/acl.h" HAVE_ACL_ENTRY_T)
+ CHECK_TYPE_EXISTS(acl_permset_t "sys/types.h;sys/acl.h" HAVE_ACL_PERMSET_T)
+ CHECK_TYPE_EXISTS(acl_tag_t "sys/types.h;sys/acl.h" HAVE_ACL_TAG_T)
+
+ IF(HAVE_ACL AND HAVE_FACL)
+ CHECK_TYPE_EXISTS(aclent_t "sys/acl.h" HAVE_ACLENT_T)
+ IF(HAVE_ACLENT_T)
+ CHECK_SYMBOL_EXISTS(GETACL "sys/acl.h" HAVE_DECL_GETACL)
+ CHECK_SYMBOL_EXISTS(GETACLCNT "sys/acl.h" HAVE_DECL_GETACLCNT)
+ CHECK_SYMBOL_EXISTS(SETACL "sys/acl.h" HAVE_DECL_SETACL)
+ IF(HAVE_DECL_GETACL AND
+ HAVE_DECL_GETACLCNT AND
+ HAVE_DECL_SETACL)
+ SET(ARCHIVE_ACL_SUNOS TRUE)
+ ENDIF()
+ CHECK_TYPE_EXISTS(ace_t "sys/acl.h" HAVE_ACE_T)
+ IF(HAVE_ACE_T)
+ CHECK_SYMBOL_EXISTS(ACE_GETACL "sys/acl.h" HAVE_DECL_ACE_GETACL)
+ CHECK_SYMBOL_EXISTS(ACE_GETACLCNT "sys/acl.h" HAVE_DECL_ACE_GETACLCNT)
+ CHECK_SYMBOL_EXISTS(ACE_SETACL "sys/acl.h" HAVE_DECL_ACE_SETACL)
+ IF(HAVE_DECL_ACE_GETACL AND
+ HAVE_DECL_ACE_GETACLCNT AND
+ HAVE_DECL_ACE_SETACL)
+ SET(ARCHIVE_ACL_SUNOS_NFS4 TRUE)
+ ENDIF()
+ ENDIF(HAVE_ACE_T)
+ ENDIF(HAVE_ACLENT_T)
+ ENDIF(HAVE_ACL AND HAVE_FACL)
+
+ IF(HAVE_ACL_T AND HAVE_ACL_ENTRY_T AND HAVE_ACL_PERMSET_T AND HAVE_ACL_TAG_T)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_add_perm HAVE_ACL_ADD_PERM)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_clear_perms HAVE_ACL_CLEAR_PERMS)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_create_entry HAVE_ACL_CREATE_ENTRY)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_delete_def_file HAVE_ACL_DELETE_DEF_FILE)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_free HAVE_ACL_FREE)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_get_entry HAVE_ACL_GET_ENTRY)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_get_fd HAVE_ACL_GET_FD)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_get_file HAVE_ACL_GET_FILE)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_get_permset HAVE_ACL_GET_PERMSET)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_get_qualifier HAVE_ACL_GET_QUALIFIER)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_get_tag_type HAVE_ACL_GET_TAG_TYPE)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_init HAVE_ACL_INIT)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_set_fd HAVE_ACL_SET_FD)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_set_file HAVE_ACL_SET_FILE)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_set_qualifier HAVE_ACL_SET_QUALIFIER)
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_set_tag_type HAVE_ACL_SET_TAG_TYPE)
+ IF(HAVE_ACL_ADD_PERM AND
+ HAVE_ACL_CLEAR_PERMS AND
+ HAVE_ACL_CREATE_ENTRY AND
+ HAVE_ACL_DELETE_DEF_FILE AND
+ HAVE_ACL_FREE AND
+ HAVE_ACL_GET_ENTRY AND
+ HAVE_ACL_GET_FD AND
+ HAVE_ACL_GET_FILE AND
+ HAVE_ACL_GET_PERMSET AND
+ HAVE_ACL_GET_QUALIFIER AND
+ HAVE_ACL_GET_TAG_TYPE AND
+ HAVE_ACL_INIT AND
+ HAVE_ACL_SET_FD AND
+ HAVE_ACL_SET_FILE AND
+ HAVE_ACL_SET_QUALIFIER AND
+ HAVE_ACL_SET_TAG_TYPE)
+ SET(HAVE_POSIX_ACL_FUNCS 1)
+ ENDIF()
+
+ CHECK_FUNCTION_EXISTS_GLIBC(acl_get_perm HAVE_ACL_GET_PERM)
+
+ IF(HAVE_POSIX_ACL_FUNCS AND HAVE_ACL_LIBACL_H AND HAVE_LIBACL AND
+ HAVE_ACL_GET_PERM)
+ SET(ARCHIVE_ACL_LIBACL TRUE)
+ ELSE()
+ CHECK_FUNCTION_EXISTS(acl_add_flag_np HAVE_ACL_ADD_FLAG_NP)
+ CHECK_FUNCTION_EXISTS(acl_clear_flags_np HAVE_ACL_CLEAR_FLAGS_NP)
+ CHECK_FUNCTION_EXISTS(acl_get_brand_np HAVE_ACL_GET_BRAND_NP)
+ CHECK_FUNCTION_EXISTS(acl_get_entry_type_np HAVE_ACL_GET_ENTRY_TYPE_NP)
+ CHECK_FUNCTION_EXISTS(acl_get_flag_np HAVE_ACL_GET_FLAG_NP)
+ CHECK_FUNCTION_EXISTS(acl_get_flagset_np HAVE_ACL_GET_FLAGSET_NP)
+ CHECK_FUNCTION_EXISTS(acl_get_fd_np HAVE_ACL_GET_FD_NP)
+ CHECK_FUNCTION_EXISTS(acl_get_link_np HAVE_ACL_GET_LINK_NP)
+ CHECK_FUNCTION_EXISTS(acl_get_perm_np HAVE_ACL_GET_PERM_NP)
+ CHECK_FUNCTION_EXISTS(acl_is_trivial_np HAVE_ACL_IS_TRIVIAL_NP)
+ CHECK_FUNCTION_EXISTS(acl_set_entry_type_np HAVE_ACL_SET_ENTRY_TYPE_NP)
+ CHECK_FUNCTION_EXISTS(acl_set_fd_np HAVE_ACL_SET_FD_NP)
+ CHECK_FUNCTION_EXISTS(acl_set_link_np HAVE_ACL_SET_LINK_NP)
+ CHECK_FUNCTION_EXISTS(mbr_gid_to_uuid HAVE_MBR_GID_TO_UUID)
+ CHECK_FUNCTION_EXISTS(mbr_uid_to_uuid HAVE_MBR_UID_TO_UUID)
+ CHECK_FUNCTION_EXISTS(mbr_uuid_to_id HAVE_MBR_UUID_TO_ID)
+
+ CHECK_C_SOURCE_COMPILES("#include <sys/types.h>
#include <sys/acl.h>
-int main(void) { return ACL_TYPE_EXTENDED; }" HAVE_ACL_TYPE_EXTENDED)
+int main(void) { return ACL_TYPE_EXTENDED; }" HAVE_DECL_ACL_TYPE_EXTENDED)
+ CHECK_C_SOURCE_COMPILES("#include <sys/types.h>
+#include <sys/acl.h>
+int main(void) { return ACL_SYNCHRONIZE; }" HAVE_DECL_ACL_SYNCHRONIZE)
+ CHECK_SYMBOL_EXISTS(ACL_TYPE_NFS4 "sys/acl.h" HAVE_DECL_ACL_TYPE_NFS4)
+ CHECK_SYMBOL_EXISTS(ACL_USER "sys/acl.h" HAVE_DECL_ACL_USER)
+
+ IF(HAVE_POSIX_ACL_FUNCS AND
+ HAVE_ACL_GET_FD_NP AND
+ HAVE_ACL_GET_PERM_NP AND
+ NOT HAVE_ACL_GET_PERM AND
+ HAVE_ACL_SET_FD_NP)
+ IF(HAVE_DECL_ACL_USER)
+ SET(ARCHIVE_ACL_FREEBSD TRUE)
+ IF(HAVE_DECL_ACL_TYPE_NFS4 AND
+ HAVE_ACL_ADD_FLAG_NP AND
+ HAVE_ACL_CLEAR_FLAGS_NP AND
+ HAVE_ACL_GET_BRAND_NP AND
+ HAVE_ACL_GET_ENTRY_TYPE_NP AND
+ HAVE_ACL_GET_FLAGSET_NP AND
+ HAVE_ACL_SET_ENTRY_TYPE_NP)
+ SET(ARCHIVE_ACL_FREEBSD_NFS4 TRUE)
+ ENDIF()
+ ELSEIF(HAVE_DECL_ACL_TYPE_EXTENDED AND
+ HAVE_MEMBERSHIP_H AND
+ HAVE_ACL_ADD_FLAG_NP AND
+ HAVE_ACL_CLEAR_FLAGS_NP AND
+ HAVE_ACL_GET_FLAGSET_NP AND
+ HAVE_ACL_GET_LINK_NP AND
+ HAVE_ACL_SET_LINK_NP AND
+ HAVE_MBR_UID_TO_UUID AND
+ HAVE_MBR_GID_TO_UUID AND
+ HAVE_MBR_UUID_TO_ID)
+ SET(ARCHIVE_ACL_DARWIN TRUE)
+ ENDIF()
+ ENDIF()
+ ENDIF()
+ ENDIF(HAVE_ACL_T AND HAVE_ACL_ENTRY_T AND HAVE_ACL_PERMSET_T AND
+ HAVE_ACL_TAG_T)
+
+ # Richacl
+ CHECK_LIBRARY_EXISTS(richacl "richacl_get_file" "" HAVE_LIBRICHACL)
+ IF(HAVE_LIBRICHACL)
+ SET(CMAKE_REQUIRED_LIBRARIES "richacl")
+ FIND_LIBRARY(RICHACL_LIBRARY NAMES richacl)
+ LIST(APPEND ADDITIONAL_LIBS ${RICHACL_LIBRARY})
+ ENDIF(HAVE_LIBRICHACL)
+
+ CHECK_STRUCT_HAS_MEMBER("struct richace" e_type "sys/richacl.h"
+ HAVE_STRUCT_RICHACE)
+ CHECK_STRUCT_HAS_MEMBER("struct richacl" a_flags "sys/richacl.h"
+ HAVE_STRUCT_RICHACL)
+
+ IF(HAVE_LIBRICHACL AND HAVE_STRUCT_RICHACL AND HAVE_STRUCT_RICHACE)
+ CHECK_FUNCTION_EXISTS_GLIBC(richacl_alloc HAVE_RICHACL_ALLOC)
+ CHECK_FUNCTION_EXISTS_GLIBC(richacl_equiv_mode HAVE_RICHACL_EQUIV_MODE)
+ CHECK_FUNCTION_EXISTS_GLIBC(richacl_free HAVE_RICHACL_FREE)
+ CHECK_FUNCTION_EXISTS_GLIBC(richacl_get_fd HAVE_RICHACL_GET_FD)
+ CHECK_FUNCTION_EXISTS_GLIBC(richacl_get_file HAVE_RICHACL_GET_FILE)
+ CHECK_FUNCTION_EXISTS_GLIBC(richacl_set_fd HAVE_RICHACL_SET_FD)
+ CHECK_FUNCTION_EXISTS_GLIBC(richacl_set_file HAVE_RICHACL_SET_FILE)
+ IF(HAVE_RICHACL_ALLOC AND
+ HAVE_RICHACL_EQUIV_MODE AND
+ HAVE_RICHACL_FREE AND
+ HAVE_RICHACL_GET_FD AND
+ HAVE_RICHACL_GET_FILE AND
+ HAVE_RICHACL_SET_FD AND
+ HAVE_RICHACL_SET_FILE)
+ SET(ARCHIVE_ACL_LIBRICHACL TRUE)
+ ENDIF()
+ ENDIF(HAVE_LIBRICHACL AND HAVE_STRUCT_RICHACL AND HAVE_STRUCT_RICHACE)
+
+ IF(ARCHIVE_ACL_DARWIN)
+ MESSAGE(STATUS "ACL support: Darwin (limited NFSv4)")
+ ELSEIF(ARCHIVE_ACL_FREEBSD_NFS4)
+ MESSAGE(STATUS "ACL support: FreeBSD (POSIX.1e and NFSv4)")
+ ELSEIF(ARCHIVE_ACL_FREEBSD)
+ MESSAGE(STATUS "ACL support: FreeBSD (POSIX.1e)")
+ ELSEIF(ARCHIVE_ACL_LIBACL OR ARCHIVE_ACL_LIBRICHACL)
+ IF(ARCHIVE_ACL_LIBACL AND ARCHIVE_ACL_LIBRICHACL)
+ MESSAGE(STATUS "ACL support: libacl (POSIX.1e) + librichacl (NFSv4)")
+ ELSEIF(ARCHIVE_ACL_LIBRICHACL)
+ MESSAGE(STATUS "ACL support: librichacl (NFSv4)")
+ ELSE()
+ MESSAGE(STATUS "ACL support: libacl (POSIX.1e)")
+ ENDIF()
+ ELSEIF(ARCHIVE_ACL_SUNOS_NFS4)
+ MESSAGE(STATUS "ACL support: Solaris (POSIX.1e and NFSv4)")
+ ELSEIF(ARCHIVE_ACL_SUNOS)
+ MESSAGE(STATUS "ACL support: Solaris (POSIX.1e)")
+ ELSE()
+ MESSAGE(STATUS "ACL support: none")
+ ENDIF()
- # Solaris and derivates ACLs
- CHECK_LIBRARY_EXISTS(sec "acl_get" "" HAVE_LIBSEC)
- IF(HAVE_LIBSEC)
- SET(CMAKE_REQUIRED_LIBRARIES "sec")
- FIND_LIBRARY(SEC_LIBRARY NAMES sec)
- LIST(APPEND ADDITIONAL_LIBS ${SEC_LIBRARY})
- ENDIF(HAVE_LIBSEC)
- #
- CHECK_TYPE_EXISTS(aclent_t "${INCLUDES}" HAVE_ACLENT_T)
- CHECK_TYPE_EXISTS(ace_t "${INCLUDES}" HAVE_ACE_T)
- CHECK_FUNCTION_EXISTS(acl_get HAVE_FACL_GET)
- CHECK_FUNCTION_EXISTS(facl_get HAVE_FACL_GET)
- CHECK_FUNCTION_EXISTS(acl_set HAVE_FACL_SET)
- CHECK_FUNCTION_EXISTS(facl_set HAVE_FACL_SET)
ELSE(ENABLE_ACL)
# If someone runs cmake, then disables ACL support, we need
# to forcibly override the cached values for these.
- SET(HAVE_ACL_CREATE_ENTRY FALSE)
- SET(HAVE_ACL_GET_LINK FALSE)
- SET(HAVE_ACL_GET_LINK_NP FALSE)
- SET(HAVE_ACL_GET_PERM FALSE)
- SET(HAVE_ACL_GET_PERM_NP FALSE)
- SET(HAVE_ACL_INIT FALSE)
- SET(HAVE_ACL_LIB FALSE)
- SET(HAVE_ACL_PERMSET_T FALSE)
- SET(HAVE_ACL_SET_FD FALSE)
- SET(HAVE_ACL_SET_FD_NP FALSE)
- SET(HAVE_ACL_SET_FILE FALSE)
- SET(HAVE_ACL_TYPE_NFS4 FALSE)
- SET(HAVE_ACL_USER FALSE)
- SET(HAVE_ACL_TYPE_EXTENDED FALSE)
- SET(HAVE_ACL_GET FALSE)
- SET(HAVE_ACLENT_T FALSE)
- SET(HAVE_ACE_T FALSE)
- SET(HAVE_FACL_GET FALSE)
- SET(HAVE_ACL_SET FALSE)
- SET(HAVE_FACL_SET FALSE)
+ SET(ARCHIVE_ACL_DARWIN FALSE)
+ SET(ARCHIVE_ACL_FREEBSD FALSE)
+ SET(ARCHIVE_ACL_FREEBSD_NFS4 FALSE)
+ SET(ARCHIVE_ACL_LIBACL FALSE)
+ SET(ARCHIVE_ACL_SUNOS FALSE)
+ SET(ARCHIVE_ACL_SUNOS_NFS4 FALSE)
ENDIF(ENABLE_ACL)
#
diff --git a/Utilities/cmlibarchive/build/cmake/config.h.in b/Utilities/cmlibarchive/build/cmake/config.h.in
index 55e04b9af..368a451e2 100644
--- a/Utilities/cmlibarchive/build/cmake/config.h.in
+++ b/Utilities/cmlibarchive/build/cmake/config.h.in
@@ -182,6 +182,27 @@ typedef uint64_t uintmax_t;
/* Define ZLIB_WINAPI if zlib was built on Visual Studio. */
#cmakedefine ZLIB_WINAPI 1
+/* Darwin ACL support */
+#cmakedefine ARCHIVE_ACL_DARWIN 1
+
+/* FreeBSD ACL support */
+#cmakedefine ARCHIVE_ACL_FREEBSD 1
+
+/* FreeBSD NFSv4 ACL support */
+#cmakedefine ARCHIVE_ACL_FREEBSD_NFS4 1
+
+/* Linux POSIX.1e ACL support via libacl */
+#cmakedefine ARCHIVE_ACL_LIBACL 1
+
+/* Linux NFSv4 ACL support via librichacl */
+#cmakedefine ARCHIVE_ACL_LIBRICHACL 1
+
+/* Solaris ACL support */
+#cmakedefine ARCHIVE_ACL_SUNOS 1
+
+/* Solaris NFSv4 ACL support */
+#cmakedefine ARCHIVE_ACL_SUNOS_NFS4 1
+
/* MD5 via ARCHIVE_CRYPTO_MD5_LIBC supported. */
#cmakedefine ARCHIVE_CRYPTO_MD5_LIBC 1
@@ -284,6 +305,18 @@ typedef uint64_t uintmax_t;
/* SHA512 via ARCHIVE_CRYPTO_SHA512_WIN supported. */
#cmakedefine ARCHIVE_CRYPTO_SHA512_WIN 1
+/* AIX xattr support */
+#cmakedefine ARCHIVE_XATTR_AIX 1
+
+/* Darwin xattr support */
+#cmakedefine ARCHIVE_XATTR_DARWIN 1
+
+/* FreeBSD xattr support */
+#cmakedefine ARCHIVE_XATTR_FREEBSD 1
+
+/* Linux xattr support */
+#cmakedefine ARCHIVE_XATTR_LINUX 1
+
/* Version number of bsdcpio */
#cmakedefine BSDCPIO_VERSION_STRING "${BSDCPIO_VERSION_STRING}"
@@ -329,15 +362,6 @@ typedef uint64_t uintmax_t;
/* Define to 1 if you have the `acl_set_file' function. */
#cmakedefine HAVE_ACL_SET_FILE 1
-/* True for FreeBSD with NFSv4 ACL support */
-#cmakedefine HAVE_ACL_TYPE_NFS4 1
-
-/* True for MacOS ACL support */
-#cmakedefine HAVE_ACL_TYPE_EXTENDED 1
-
-/* True for systems with POSIX ACL support */
-#cmakedefine HAVE_ACL_USER 1
-
/* Define to 1 if you have the `arc4random_buf' function. */
#cmakedefine HAVE_ARC4RANDOM_BUF 1
@@ -374,6 +398,34 @@ typedef uint64_t uintmax_t;
/* Define to 1 if you have the `cygwin_conv_path' function. */
#cmakedefine HAVE_CYGWIN_CONV_PATH 1
+/* Define to 1 if you have the declaration of `ACE_GETACL', and to 0 if you
+ don't. */
+#cmakedefine HAVE_DECL_ACE_GETACL 1
+
+/* Define to 1 if you have the declaration of `ACE_GETACLCNT', and to 0 if you
+ don't. */
+#cmakedefine HAVE_DECL_ACE_GETACLCNT 1
+
+/* Define to 1 if you have the declaration of `ACE_SETACL', and to 0 if you
+ don't. */
+#cmakedefine HAVE_DECL_ACE_SETACL 1
+
+/* Define to 1 if you have the declaration of `ACL_SYNCHRONIZE', and to 0 if
+ you don't. */
+#cmakedefine HAVE_DECL_ACL_SYNCHRONIZE 1
+
+/* Define to 1 if you have the declaration of `ACL_TYPE_EXTENDED', and to 0 if
+ you don't. */
+#cmakedefine HAVE_DECL_ACL_TYPE_EXTENDED 1
+
+/* Define to 1 if you have the declaration of `ACL_TYPE_NFS4', and to 0 if you
+ don't. */
+#cmakedefine HAVE_DECL_ACL_TYPE_NFS4 1
+
+/* Define to 1 if you have the declaration of `ACL_USER', and to 0 if you
+ don't. */
+#cmakedefine HAVE_DECL_ACL_USER 1
+
/* Define to 1 if you have the declaration of `INT32_MAX', and to 0 if you
don't. */
#cmakedefine HAVE_DECL_INT32_MAX 1
@@ -398,6 +450,10 @@ typedef uint64_t uintmax_t;
don't. */
#cmakedefine HAVE_DECL_INTMAX_MIN 1
+/* Define to 1 if you have the declaration of `SETACL', and to 0 if you don't.
+ */
+#cmakedefine HAVE_DECL_SETACL 1
+
/* Define to 1 if you have the declaration of `SIZE_MAX', and to 0 if you
don't. */
#cmakedefine HAVE_DECL_SIZE_MAX 1
@@ -422,6 +478,10 @@ typedef uint64_t uintmax_t;
don't. */
#cmakedefine HAVE_DECL_UINTMAX_MAX 1
+/* Define to 1 if you have the declaration of `XATTR_NOFOLLOW', and to 0 if
+ you don't. */
+#cmakedefine HAVE_DECL_XATTR_NOFOLLOW 1
+
/* Define to 1 if you have the <direct.h> header file. */
#cmakedefine HAVE_DIRECT_H 1
@@ -471,6 +531,14 @@ typedef uint64_t uintmax_t;
/* Define to 1 if EXTATTR_NAMESPACE_USER is defined in sys/extattr.h. */
#cmakedefine HAVE_DECL_EXTATTR_NAMESPACE_USER 1
+/* Define to 1 if you have the declaration of `GETACL', and to 0 if you don't.
+ */
+#cmakedefine HAVE_DECL_GETACL 1
+
+/* Define to 1 if you have the declaration of `GETACLCNT', and to 0 if you
+ don't. */
+#cmakedefine HAVE_DECL_GETACLCNT 1
+
/* Define to 1 if you have the `fchdir' function. */
#cmakedefine HAVE_FCHDIR 1
@@ -748,6 +816,9 @@ typedef uint64_t uintmax_t;
/* Define to 1 if you have the `mbrtowc' function. */
#cmakedefine HAVE_MBRTOWC 1
+/* Define to 1 if you have the <membership.h> header file. */
+#cmakedefine HAVE_MEMBERSHIP_H 1
+
/* Define to 1 if you have the `memmove' function. */
#cmakedefine HAVE_MEMMOVE 1
@@ -985,6 +1056,9 @@ typedef uint64_t uintmax_t;
/* Define to 1 if you have the <sys/poll.h> header file. */
#cmakedefine HAVE_SYS_POLL_H 1
+/* Define to 1 if you have the <sys/richacl.h> header file. */
+#cmakedefine HAVE_SYS_RICHACL_H 1
+
/* Define to 1 if you have the <sys/select.h> header file. */
#cmakedefine HAVE_SYS_SELECT_H 1
diff --git a/Utilities/cmlibarchive/build/version b/Utilities/cmlibarchive/build/version
index ef8345726..2dd083974 100644
--- a/Utilities/cmlibarchive/build/version
+++ b/Utilities/cmlibarchive/build/version
@@ -1 +1 @@
-3003001
+3003002
diff --git a/Utilities/cmlibarchive/libarchive/CMakeLists.txt b/Utilities/cmlibarchive/libarchive/CMakeLists.txt
index d412c80dc..b02ae828e 100644
--- a/Utilities/cmlibarchive/libarchive/CMakeLists.txt
+++ b/Utilities/cmlibarchive/libarchive/CMakeLists.txt
@@ -14,6 +14,7 @@ SET(include_HEADERS
# Sources and private headers
SET(libarchive_SOURCES
archive_acl.c
+ archive_acl_private.h
archive_check_magic.c
archive_cmdline.c
archive_cmdline_private.h
@@ -47,6 +48,8 @@ SET(libarchive_SOURCES
archive_pathmatch.c
archive_pathmatch.h
archive_platform.h
+ archive_platform_acl.h
+ archive_platform_xattr.h
archive_ppmd_private.h
archive_ppmd7.c
archive_ppmd7_private.h
@@ -106,9 +109,9 @@ SET(libarchive_SOURCES
archive_string_composition.h
archive_string_sprintf.c
archive_util.c
+ archive_version_details.c
archive_virtual.c
archive_write.c
- archive_write_disk_acl.c
archive_write_disk_posix.c
archive_write_disk_private.h
archive_write_disk_set_standard_lookup.c
@@ -210,6 +213,16 @@ IF(WIN32 AND NOT CYGWIN)
LIST(APPEND libarchive_SOURCES filter_fork_windows.c)
ENDIF(WIN32 AND NOT CYGWIN)
+IF(ARCHIVE_ACL_DARWIN)
+ LIST(APPEND libarchive_SOURCES archive_disk_acl_darwin.c)
+ELSEIF(ARCHIVE_ACL_FREEBSD)
+ LIST(APPEND libarchive_SOURCES archive_disk_acl_freebsd.c)
+ELSEIF(ARCHIVE_ACL_LIBACL)
+ LIST(APPEND libarchive_SOURCES archive_disk_acl_linux.c)
+ELSEIF(ARCHIVE_ACL_SUNOS)
+ LIST(APPEND libarchive_SOURCES archive_disk_acl_sunos.c)
+ENDIF()
+
# CMake needs just one static "cmlibarchive" library.
ADD_LIBRARY(cmlibarchive STATIC ${libarchive_SOURCES} ${include_HEADERS})
TARGET_LINK_LIBRARIES(cmlibarchive ${ADDITIONAL_LIBS})
diff --git a/Utilities/cmlibarchive/libarchive/archive.h b/Utilities/cmlibarchive/libarchive/archive.h
index cfb5c48b2..0f94d2e6c 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 3003001
+#define ARCHIVE_VERSION_NUMBER 3003002
#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.3.1"
+#define ARCHIVE_VERSION_ONLY_STRING "3.3.2"
#define ARCHIVE_VERSION_STRING "libarchive " ARCHIVE_VERSION_ONLY_STRING
__LA_DECL const char * archive_version_string(void);
diff --git a/Utilities/cmlibarchive/libarchive/archive_check_magic.c b/Utilities/cmlibarchive/libarchive/archive_check_magic.c
index c695e582a..288ce2338 100644
--- a/Utilities/cmlibarchive/libarchive/archive_check_magic.c
+++ b/Utilities/cmlibarchive/libarchive/archive_check_magic.c
@@ -62,7 +62,7 @@ errmsg(const char *m)
}
}
-static void
+static __LA_DEAD void
diediedie(void)
{
#if defined(_WIN32) && !defined(__CYGWIN__) && defined(_DEBUG)
diff --git a/Utilities/cmlibarchive/libarchive/archive_disk_acl_darwin.c b/Utilities/cmlibarchive/libarchive/archive_disk_acl_darwin.c
new file mode 100644
index 000000000..48ad01651
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_disk_acl_darwin.c
@@ -0,0 +1,559 @@
+/*-
+ * Copyright (c) 2017 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"
+
+#if ARCHIVE_ACL_DARWIN
+
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#if HAVE_ERRNO_H
+#include <errno.h>
+#endif
+#if HAVE_MEMBERSHIP_H
+#include <membership.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_ACL_H
+#define _ACL_PRIVATE /* For debugging */
+#include <sys/acl.h>
+#endif
+
+#include "archive_entry.h"
+#include "archive_private.h"
+#include "archive_read_disk_private.h"
+#include "archive_write_disk_private.h"
+
+typedef struct {
+ const int a_perm; /* Libarchive permission or flag */
+ const int p_perm; /* Platform permission or flag */
+} acl_perm_map_t;
+
+static const acl_perm_map_t acl_nfs4_perm_map[] = {
+ {ARCHIVE_ENTRY_ACL_READ_DATA, ACL_READ_DATA},
+ {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, ACL_LIST_DIRECTORY},
+ {ARCHIVE_ENTRY_ACL_WRITE_DATA, ACL_WRITE_DATA},
+ {ARCHIVE_ENTRY_ACL_ADD_FILE, ACL_ADD_FILE},
+ {ARCHIVE_ENTRY_ACL_EXECUTE, ACL_EXECUTE},
+ {ARCHIVE_ENTRY_ACL_DELETE, ACL_DELETE},
+ {ARCHIVE_ENTRY_ACL_APPEND_DATA, ACL_APPEND_DATA},
+ {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, ACL_ADD_SUBDIRECTORY},
+ {ARCHIVE_ENTRY_ACL_DELETE_CHILD, ACL_DELETE_CHILD},
+ {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, ACL_READ_ATTRIBUTES},
+ {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, ACL_WRITE_ATTRIBUTES},
+ {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, ACL_READ_EXTATTRIBUTES},
+ {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, ACL_WRITE_EXTATTRIBUTES},
+ {ARCHIVE_ENTRY_ACL_READ_ACL, ACL_READ_SECURITY},
+ {ARCHIVE_ENTRY_ACL_WRITE_ACL, ACL_WRITE_SECURITY},
+ {ARCHIVE_ENTRY_ACL_WRITE_OWNER, ACL_CHANGE_OWNER},
+#if HAVE_DECL_ACL_SYNCHRONIZE
+ {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, ACL_SYNCHRONIZE}
+#endif
+};
+
+static const int acl_nfs4_perm_map_size =
+ (int)(sizeof(acl_nfs4_perm_map)/sizeof(acl_nfs4_perm_map[0]));
+
+static const acl_perm_map_t acl_nfs4_flag_map[] = {
+ {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACL_ENTRY_INHERITED},
+ {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, ACL_ENTRY_FILE_INHERIT},
+ {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, ACL_ENTRY_DIRECTORY_INHERIT},
+ {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, ACL_ENTRY_LIMIT_INHERIT},
+ {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, ACL_ENTRY_ONLY_INHERIT}
+};
+
+static const int acl_nfs4_flag_map_size =
+ (int)(sizeof(acl_nfs4_flag_map)/sizeof(acl_nfs4_flag_map[0]));
+
+static int translate_guid(struct archive *a, acl_entry_t acl_entry,
+ int *ae_id, int *ae_tag, const char **ae_name)
+{
+ void *q;
+ uid_t ugid;
+ int r, idtype;
+
+ q = acl_get_qualifier(acl_entry);
+ if (q == NULL)
+ return (1);
+ r = mbr_uuid_to_id((const unsigned char *)q, &ugid, &idtype);
+ if (r != 0) {
+ acl_free(q);
+ return (1);
+ }
+ if (idtype == ID_TYPE_UID) {
+ *ae_tag = ARCHIVE_ENTRY_ACL_USER;
+ *ae_id = ugid;
+ *ae_name = archive_read_disk_uname(a, *ae_id);
+ } else if (idtype == ID_TYPE_GID) {
+ *ae_tag = ARCHIVE_ENTRY_ACL_GROUP;
+ *ae_id = ugid;
+ *ae_name = archive_read_disk_gname(a, *ae_id);
+ } else
+ r = 1;
+
+ acl_free(q);
+ return (r);
+}
+
+static void
+add_trivial_nfs4_acl(struct archive_entry *entry)
+{
+ mode_t mode;
+ int i;
+ const int rperm = ARCHIVE_ENTRY_ACL_READ_DATA;
+ const int wperm = ARCHIVE_ENTRY_ACL_WRITE_DATA |
+ ARCHIVE_ENTRY_ACL_APPEND_DATA;
+ const int eperm = ARCHIVE_ENTRY_ACL_EXECUTE;
+ const int pubset = ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES |
+ ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS |
+ ARCHIVE_ENTRY_ACL_READ_ACL |
+ ARCHIVE_ENTRY_ACL_SYNCHRONIZE;
+ const int ownset = pubset | ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES |
+ ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS |
+ ARCHIVE_ENTRY_ACL_WRITE_ACL |
+ ARCHIVE_ENTRY_ACL_WRITE_OWNER;
+
+ struct {
+ const int type;
+ const int tag;
+ int permset;
+ } tacl_entry[] = {
+ {ARCHIVE_ENTRY_ACL_TYPE_ALLOW, ARCHIVE_ENTRY_ACL_USER_OBJ, 0},
+ {ARCHIVE_ENTRY_ACL_TYPE_DENY, ARCHIVE_ENTRY_ACL_USER_OBJ, 0},
+ {ARCHIVE_ENTRY_ACL_TYPE_DENY, ARCHIVE_ENTRY_ACL_GROUP_OBJ, 0},
+ {ARCHIVE_ENTRY_ACL_TYPE_ALLOW, ARCHIVE_ENTRY_ACL_USER_OBJ, ownset},
+ {ARCHIVE_ENTRY_ACL_TYPE_ALLOW, ARCHIVE_ENTRY_ACL_GROUP_OBJ, pubset},
+ {ARCHIVE_ENTRY_ACL_TYPE_ALLOW, ARCHIVE_ENTRY_ACL_EVERYONE, pubset}
+ };
+
+ mode = archive_entry_mode(entry);
+
+ /* Permissions for everyone@ */
+ if (mode & 0004)
+ tacl_entry[5].permset |= rperm;
+ if (mode & 0002)
+ tacl_entry[5].permset |= wperm;
+ if (mode & 0001)
+ tacl_entry[5].permset |= eperm;
+
+ /* Permissions for group@ */
+ if (mode & 0040)
+ tacl_entry[4].permset |= rperm;
+ else if (mode & 0004)
+ tacl_entry[2].permset |= rperm;
+ if (mode & 0020)
+ tacl_entry[4].permset |= wperm;
+ else if (mode & 0002)
+ tacl_entry[2].permset |= wperm;
+ if (mode & 0010)
+ tacl_entry[4].permset |= eperm;
+ else if (mode & 0001)
+ tacl_entry[2].permset |= eperm;
+
+ /* Permissions for owner@ */
+ if (mode & 0400) {
+ tacl_entry[3].permset |= rperm;
+ if (!(mode & 0040) && (mode & 0004))
+ tacl_entry[0].permset |= rperm;
+ } else if ((mode & 0040) || (mode & 0004))
+ tacl_entry[1].permset |= rperm;
+ if (mode & 0200) {
+ tacl_entry[3].permset |= wperm;
+ if (!(mode & 0020) && (mode & 0002))
+ tacl_entry[0].permset |= wperm;
+ } else if ((mode & 0020) || (mode & 0002))
+ tacl_entry[1].permset |= wperm;
+ if (mode & 0100) {
+ tacl_entry[3].permset |= eperm;
+ if (!(mode & 0010) && (mode & 0001))
+ tacl_entry[0].permset |= eperm;
+ } else if ((mode & 0010) || (mode & 0001))
+ tacl_entry[1].permset |= eperm;
+
+ for (i = 0; i < 6; i++) {
+ if (tacl_entry[i].permset != 0) {
+ archive_entry_acl_add_entry(entry,
+ tacl_entry[i].type, tacl_entry[i].permset,
+ tacl_entry[i].tag, -1, NULL);
+ }
+ }
+
+ return;
+}
+
+static int
+translate_acl(struct archive_read_disk *a,
+ struct archive_entry *entry, acl_t acl)
+{
+ acl_tag_t acl_tag;
+ acl_flagset_t acl_flagset;
+ acl_entry_t acl_entry;
+ acl_permset_t acl_permset;
+ int i, entry_acl_type;
+ int r, s, ae_id, ae_tag, ae_perm;
+ const char *ae_name;
+
+ s = acl_get_entry(acl, ACL_FIRST_ENTRY, &acl_entry);
+ if (s == -1) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get first ACL entry");
+ return (ARCHIVE_WARN);
+ }
+
+ while (s == 0) {
+ ae_id = -1;
+ ae_name = NULL;
+ ae_perm = 0;
+
+ if (acl_get_tag_type(acl_entry, &acl_tag) != 0) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get ACL tag type");
+ return (ARCHIVE_WARN);
+ }
+ switch (acl_tag) {
+ case ACL_EXTENDED_ALLOW:
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW;
+ r = translate_guid(&a->archive, acl_entry,
+ &ae_id, &ae_tag, &ae_name);
+ break;
+ case ACL_EXTENDED_DENY:
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DENY;
+ r = translate_guid(&a->archive, acl_entry,
+ &ae_id, &ae_tag, &ae_name);
+ break;
+ default:
+ /* Skip types that libarchive can't support. */
+ s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry);
+ continue;
+ }
+
+ /* Skip if translate_guid() above failed */
+ if (r != 0) {
+ s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry);
+ continue;
+ }
+
+ /*
+ * Libarchive stores "flag" (NFSv4 inheritance bits)
+ * in the ae_perm bitmap.
+ *
+ * acl_get_flagset_np() fails with non-NFSv4 ACLs
+ */
+ if (acl_get_flagset_np(acl_entry, &acl_flagset) != 0) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get flagset from a NFSv4 ACL entry");
+ return (ARCHIVE_WARN);
+ }
+ for (i = 0; i < acl_nfs4_flag_map_size; ++i) {
+ r = acl_get_flag_np(acl_flagset,
+ acl_nfs4_flag_map[i].p_perm);
+ if (r == -1) {
+ archive_set_error(&a->archive, errno,
+ "Failed to check flag in a NFSv4 "
+ "ACL flagset");
+ return (ARCHIVE_WARN);
+ } else if (r)
+ ae_perm |= acl_nfs4_flag_map[i].a_perm;
+ }
+
+ if (acl_get_permset(acl_entry, &acl_permset) != 0) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get ACL permission set");
+ return (ARCHIVE_WARN);
+ }
+
+ for (i = 0; i < acl_nfs4_perm_map_size; ++i) {
+ /*
+ * acl_get_perm() is spelled differently on different
+ * platforms; see above.
+ */
+ r = acl_get_perm_np(acl_permset,
+ acl_nfs4_perm_map[i].p_perm);
+ if (r == -1) {
+ archive_set_error(&a->archive, errno,
+ "Failed to check permission in an ACL "
+ "permission set");
+ return (ARCHIVE_WARN);
+ } else if (r)
+ ae_perm |= acl_nfs4_perm_map[i].a_perm;
+ }
+
+#if !HAVE_DECL_ACL_SYNCHRONIZE
+ /* On Mac OS X without ACL_SYNCHRONIZE assume it is set */
+ ae_perm |= ARCHIVE_ENTRY_ACL_SYNCHRONIZE;
+#endif
+
+ archive_entry_acl_add_entry(entry, entry_acl_type,
+ ae_perm, ae_tag,
+ ae_id, ae_name);
+
+ s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry);
+ }
+ return (ARCHIVE_OK);
+}
+
+static int
+set_acl(struct archive *a, int fd, const char *name,
+ struct archive_acl *abstract_acl,
+ int ae_requested_type, const char *tname)
+{
+ acl_t acl;
+ acl_entry_t acl_entry;
+ acl_permset_t acl_permset;
+ acl_flagset_t acl_flagset;
+ int ret;
+ int ae_type, ae_permset, ae_tag, ae_id;
+ uuid_t ae_uuid;
+ uid_t ae_uid;
+ gid_t ae_gid;
+ const char *ae_name;
+ int entries;
+ int i;
+
+ ret = ARCHIVE_OK;
+ entries = archive_acl_reset(abstract_acl, ae_requested_type);
+ if (entries == 0)
+ return (ARCHIVE_OK);
+
+ if (ae_requested_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
+ errno = ENOENT;
+ archive_set_error(a, errno, "Unsupported ACL type");
+ return (ARCHIVE_FAILED);
+ }
+
+ acl = acl_init(entries);
+ if (acl == (acl_t)NULL) {
+ archive_set_error(a, errno,
+ "Failed to initialize ACL working storage");
+ return (ARCHIVE_FAILED);
+ }
+
+ while (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type,
+ &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
+ /*
+ * Mac OS doesn't support NFSv4 ACLs for
+ * owner@, group@ and everyone@.
+ * We skip any of these ACLs found.
+ */
+ if (ae_tag == ARCHIVE_ENTRY_ACL_USER_OBJ ||
+ ae_tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ ||
+ ae_tag == ARCHIVE_ENTRY_ACL_EVERYONE)
+ continue;
+
+ if (acl_create_entry(&acl, &acl_entry) != 0) {
+ archive_set_error(a, errno,
+ "Failed to create a new ACL entry");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+ switch (ae_type) {
+ case ARCHIVE_ENTRY_ACL_TYPE_ALLOW:
+ acl_set_tag_type(acl_entry, ACL_EXTENDED_ALLOW);
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_DENY:
+ acl_set_tag_type(acl_entry, ACL_EXTENDED_DENY);
+ break;
+ default:
+ /* We don't support any other types on MacOS */
+ continue;
+ }
+
+ switch (ae_tag) {
+ case ARCHIVE_ENTRY_ACL_USER:
+ ae_uid = archive_write_disk_uid(a, ae_name, ae_id);
+ if (mbr_uid_to_uuid(ae_uid, ae_uuid) != 0)
+ continue;
+ if (acl_set_qualifier(acl_entry, &ae_uuid) != 0)
+ continue;
+ break;
+ case ARCHIVE_ENTRY_ACL_GROUP:
+ ae_gid = archive_write_disk_gid(a, ae_name, ae_id);
+ if (mbr_gid_to_uuid(ae_gid, ae_uuid) != 0)
+ continue;
+ if (acl_set_qualifier(acl_entry, &ae_uuid) != 0)
+ continue;
+ break;
+ default:
+ archive_set_error(a, ARCHIVE_ERRNO_MISC,
+ "Unsupported ACL tag");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+ if (acl_get_permset(acl_entry, &acl_permset) != 0) {
+ archive_set_error(a, errno,
+ "Failed to get ACL permission set");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+ if (acl_clear_perms(acl_permset) != 0) {
+ archive_set_error(a, errno,
+ "Failed to clear ACL permissions");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+ for (i = 0; i < acl_nfs4_perm_map_size; ++i) {
+ if (ae_permset & acl_nfs4_perm_map[i].a_perm) {
+ if (acl_add_perm(acl_permset,
+ acl_nfs4_perm_map[i].p_perm) != 0) {
+ archive_set_error(a, errno,
+ "Failed to add ACL permission");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+ }
+ }
+
+ /*
+ * acl_get_flagset_np() fails with non-NFSv4 ACLs
+ */
+ if (acl_get_flagset_np(acl_entry, &acl_flagset) != 0) {
+ archive_set_error(a, errno,
+ "Failed to get flagset from an NFSv4 ACL entry");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+ if (acl_clear_flags_np(acl_flagset) != 0) {
+ archive_set_error(a, errno,
+ "Failed to clear flags from an NFSv4 ACL flagset");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+ for (i = 0; i < acl_nfs4_flag_map_size; ++i) {
+ if (ae_permset & acl_nfs4_flag_map[i].a_perm) {
+ if (acl_add_flag_np(acl_flagset,
+ acl_nfs4_flag_map[i].p_perm) != 0) {
+ archive_set_error(a, errno,
+ "Failed to add flag to "
+ "NFSv4 ACL flagset");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+ }
+ }
+ }
+
+ if (fd >= 0) {
+ if (acl_set_fd_np(fd, acl, ACL_TYPE_EXTENDED) == 0)
+ ret = ARCHIVE_OK;
+ else {
+ if (errno == EOPNOTSUPP) {
+ /* Filesystem doesn't support ACLs */
+ ret = ARCHIVE_OK;
+ } else {
+ archive_set_error(a, errno,
+ "Failed to set acl on fd: %s", tname);
+ ret = ARCHIVE_WARN;
+ }
+ }
+ } else if (acl_set_link_np(name, ACL_TYPE_EXTENDED, acl) != 0) {
+ if (errno == EOPNOTSUPP) {
+ /* Filesystem doesn't support ACLs */
+ ret = ARCHIVE_OK;
+ } else {
+ archive_set_error(a, errno, "Failed to set acl: %s",
+ tname);
+ ret = ARCHIVE_WARN;
+ }
+ }
+exit_free:
+ acl_free(acl);
+ return (ret);
+}
+
+int
+archive_read_disk_entry_setup_acls(struct archive_read_disk *a,
+ struct archive_entry *entry, int *fd)
+{
+ const char *accpath;
+ acl_t acl;
+ int r;
+
+ accpath = NULL;
+
+ if (*fd < 0) {
+ accpath = archive_read_disk_entry_setup_path(a, entry, fd);
+ if (accpath == NULL)
+ return (ARCHIVE_WARN);
+ }
+
+ archive_entry_acl_clear(entry);
+
+ acl = NULL;
+
+ if (*fd >= 0)
+ acl = acl_get_fd_np(*fd, ACL_TYPE_EXTENDED);
+ else if (!a->follow_symlinks)
+ acl = acl_get_link_np(accpath, ACL_TYPE_EXTENDED);
+ else
+ acl = acl_get_file(accpath, ACL_TYPE_EXTENDED);
+
+ if (acl != NULL) {
+ r = translate_acl(a, entry, acl);
+ acl_free(acl);
+ acl = NULL;
+
+ if (r != ARCHIVE_OK) {
+ archive_set_error(&a->archive, errno,
+ "Couldn't translate NFSv4 ACLs");
+ }
+
+ /*
+ * Because Mac OS doesn't support owner@, group@ and everyone@
+ * ACLs we need to add NFSv4 ACLs mirroring the file mode to
+ * the archive entry. Otherwise extraction on non-Mac platforms
+ * would lead to an invalid file mode.
+ */
+ if ((archive_entry_acl_types(entry) &
+ ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0)
+ add_trivial_nfs4_acl(entry);
+
+ return (r);
+ }
+ return (ARCHIVE_OK);
+}
+
+int
+archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
+ struct archive_acl *abstract_acl, __LA_MODE_T mode)
+{
+ int ret = ARCHIVE_OK;
+
+ (void)mode; /* UNUSED */
+
+ if ((archive_acl_types(abstract_acl) &
+ ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) {
+ ret = set_acl(a, fd, name, abstract_acl,
+ ARCHIVE_ENTRY_ACL_TYPE_NFS4, "nfs4");
+ }
+ return (ret);
+}
+#endif /* ARCHIVE_ACL_DARWIN */
diff --git a/Utilities/cmlibarchive/libarchive/archive_disk_acl_freebsd.c b/Utilities/cmlibarchive/libarchive/archive_disk_acl_freebsd.c
new file mode 100644
index 000000000..07d08ff96
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_disk_acl_freebsd.c
@@ -0,0 +1,700 @@
+/*-
+ * Copyright (c) 2003-2009 Tim Kientzle
+ * Copyright (c) 2010-2012 Michihiro NAKAJIMA
+ * Copyright (c) 2017 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"
+
+#if ARCHIVE_ACL_FREEBSD
+
+#ifdef HAVE_ERRNO_H
+#include <errno.h>
+#endif
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_ACL_H
+#define _ACL_PRIVATE /* For debugging */
+#include <sys/acl.h>
+#endif
+
+#include "archive_entry.h"
+#include "archive_private.h"
+#include "archive_read_disk_private.h"
+#include "archive_write_disk_private.h"
+
+typedef struct {
+ const int a_perm; /* Libarchive permission or flag */
+ const int p_perm; /* Platform permission or flag */
+} acl_perm_map_t;
+
+static const acl_perm_map_t acl_posix_perm_map[] = {
+ {ARCHIVE_ENTRY_ACL_EXECUTE, ACL_EXECUTE},
+ {ARCHIVE_ENTRY_ACL_WRITE, ACL_WRITE},
+ {ARCHIVE_ENTRY_ACL_READ, ACL_READ},
+};
+
+static const int acl_posix_perm_map_size =
+ (int)(sizeof(acl_posix_perm_map)/sizeof(acl_posix_perm_map[0]));
+
+#if ARCHIVE_ACL_FREEBSD_NFS4
+static const acl_perm_map_t acl_nfs4_perm_map[] = {
+ {ARCHIVE_ENTRY_ACL_EXECUTE, ACL_EXECUTE},
+ {ARCHIVE_ENTRY_ACL_READ_DATA, ACL_READ_DATA},
+ {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, ACL_LIST_DIRECTORY},
+ {ARCHIVE_ENTRY_ACL_WRITE_DATA, ACL_WRITE_DATA},
+ {ARCHIVE_ENTRY_ACL_ADD_FILE, ACL_ADD_FILE},
+ {ARCHIVE_ENTRY_ACL_APPEND_DATA, ACL_APPEND_DATA},
+ {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, ACL_ADD_SUBDIRECTORY},
+ {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, ACL_READ_NAMED_ATTRS},
+ {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, ACL_WRITE_NAMED_ATTRS},
+ {ARCHIVE_ENTRY_ACL_DELETE_CHILD, ACL_DELETE_CHILD},
+ {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, ACL_READ_ATTRIBUTES},
+ {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, ACL_WRITE_ATTRIBUTES},
+ {ARCHIVE_ENTRY_ACL_DELETE, ACL_DELETE},
+ {ARCHIVE_ENTRY_ACL_READ_ACL, ACL_READ_ACL},
+ {ARCHIVE_ENTRY_ACL_WRITE_ACL, ACL_WRITE_ACL},
+ {ARCHIVE_ENTRY_ACL_WRITE_OWNER, ACL_WRITE_OWNER},
+ {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, ACL_SYNCHRONIZE}
+};
+
+static const int acl_nfs4_perm_map_size =
+ (int)(sizeof(acl_nfs4_perm_map)/sizeof(acl_nfs4_perm_map[0]));
+
+static const acl_perm_map_t acl_nfs4_flag_map[] = {
+ {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, ACL_ENTRY_FILE_INHERIT},
+ {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, ACL_ENTRY_DIRECTORY_INHERIT},
+ {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, ACL_ENTRY_NO_PROPAGATE_INHERIT},
+ {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, ACL_ENTRY_INHERIT_ONLY},
+ {ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS, ACL_ENTRY_SUCCESSFUL_ACCESS},
+ {ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS, ACL_ENTRY_FAILED_ACCESS},
+ {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACL_ENTRY_INHERITED}
+};
+
+static const int acl_nfs4_flag_map_size =
+ (int)(sizeof(acl_nfs4_flag_map)/sizeof(acl_nfs4_flag_map[0]));
+#endif /* ARCHIVE_ACL_FREEBSD_NFS4 */
+
+static int
+translate_acl(struct archive_read_disk *a,
+ struct archive_entry *entry, acl_t acl, int default_entry_acl_type)
+{
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ int brand;
+ acl_flagset_t acl_flagset;
+ acl_entry_type_t acl_type;
+#endif
+ acl_tag_t acl_tag;
+ acl_entry_t acl_entry;
+ acl_permset_t acl_permset;
+ int i, entry_acl_type, perm_map_size;
+ const acl_perm_map_t *perm_map;
+ int r, s, ae_id, ae_tag, ae_perm;
+ void *q;
+ const char *ae_name;
+
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ // FreeBSD "brands" ACLs as POSIX.1e or NFSv4
+ // Make sure the "brand" on this ACL is consistent
+ // with the default_entry_acl_type bits provided.
+ if (acl_get_brand_np(acl, &brand) != 0) {
+ archive_set_error(&a->archive, errno,
+ "Failed to read ACL brand");
+ return (ARCHIVE_WARN);
+ }
+ switch (brand) {
+ case ACL_BRAND_POSIX:
+ switch (default_entry_acl_type) {
+ case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
+ case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
+ break;
+ default:
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
+ "Invalid ACL entry type for POSIX.1e ACL");
+ return (ARCHIVE_WARN);
+ }
+ break;
+ case ACL_BRAND_NFS4:
+ if (default_entry_acl_type & ~ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
+ "Invalid ACL entry type for NFSv4 ACL");
+ return (ARCHIVE_WARN);
+ }
+ break;
+ default:
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
+ "Unknown ACL brand");
+ return (ARCHIVE_WARN);
+ }
+#endif
+
+ s = acl_get_entry(acl, ACL_FIRST_ENTRY, &acl_entry);
+ if (s == -1) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get first ACL entry");
+ return (ARCHIVE_WARN);
+ }
+
+ while (s == 1) {
+ ae_id = -1;
+ ae_name = NULL;
+ ae_perm = 0;
+
+ if (acl_get_tag_type(acl_entry, &acl_tag) != 0) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get ACL tag type");
+ return (ARCHIVE_WARN);
+ }
+ switch (acl_tag) {
+ case ACL_USER:
+ q = acl_get_qualifier(acl_entry);
+ if (q != NULL) {
+ ae_id = (int)*(uid_t *)q;
+ acl_free(q);
+ ae_name = archive_read_disk_uname(&a->archive,
+ ae_id);
+ }
+ ae_tag = ARCHIVE_ENTRY_ACL_USER;
+ break;
+ case ACL_GROUP:
+ q = acl_get_qualifier(acl_entry);
+ if (q != NULL) {
+ ae_id = (int)*(gid_t *)q;
+ acl_free(q);
+ ae_name = archive_read_disk_gname(&a->archive,
+ ae_id);
+ }
+ ae_tag = ARCHIVE_ENTRY_ACL_GROUP;
+ break;
+ case ACL_MASK:
+ ae_tag = ARCHIVE_ENTRY_ACL_MASK;
+ break;
+ case ACL_USER_OBJ:
+ ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
+ break;
+ case ACL_GROUP_OBJ:
+ ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
+ break;
+ case ACL_OTHER:
+ ae_tag = ARCHIVE_ENTRY_ACL_OTHER;
+ break;
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ case ACL_EVERYONE:
+ ae_tag = ARCHIVE_ENTRY_ACL_EVERYONE;
+ break;
+#endif
+ default:
+ /* Skip types that libarchive can't support. */
+ s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry);
+ continue;
+ }
+
+ // XXX acl_type maps to allow/deny/audit/YYYY bits
+ entry_acl_type = default_entry_acl_type;
+
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ if (default_entry_acl_type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
+ /*
+ * acl_get_entry_type_np() fails with non-NFSv4 ACLs
+ */
+ if (acl_get_entry_type_np(acl_entry, &acl_type) != 0) {
+ archive_set_error(&a->archive, errno, "Failed "
+ "to get ACL type from a NFSv4 ACL entry");
+ return (ARCHIVE_WARN);
+ }
+ switch (acl_type) {
+ case ACL_ENTRY_TYPE_ALLOW:
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW;
+ break;
+ case ACL_ENTRY_TYPE_DENY:
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DENY;
+ break;
+ case ACL_ENTRY_TYPE_AUDIT:
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT;
+ break;
+ case ACL_ENTRY_TYPE_ALARM:
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALARM;
+ break;
+ default:
+ archive_set_error(&a->archive, errno,
+ "Invalid NFSv4 ACL entry type");
+ return (ARCHIVE_WARN);
+ }
+
+ /*
+ * Libarchive stores "flag" (NFSv4 inheritance bits)
+ * in the ae_perm bitmap.
+ *
+ * acl_get_flagset_np() fails with non-NFSv4 ACLs
+ */
+ if (acl_get_flagset_np(acl_entry, &acl_flagset) != 0) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get flagset from a NFSv4 "
+ "ACL entry");
+ return (ARCHIVE_WARN);
+ }
+ for (i = 0; i < acl_nfs4_flag_map_size; ++i) {
+ r = acl_get_flag_np(acl_flagset,
+ acl_nfs4_flag_map[i].p_perm);
+ if (r == -1) {
+ archive_set_error(&a->archive, errno,
+ "Failed to check flag in a NFSv4 "
+ "ACL flagset");
+ return (ARCHIVE_WARN);
+ } else if (r)
+ ae_perm |= acl_nfs4_flag_map[i].a_perm;
+ }
+ }
+#endif
+
+ if (acl_get_permset(acl_entry, &acl_permset) != 0) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get ACL permission set");
+ return (ARCHIVE_WARN);
+ }
+
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ if (default_entry_acl_type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
+ perm_map_size = acl_nfs4_perm_map_size;
+ perm_map = acl_nfs4_perm_map;
+ } else {
+#endif
+ perm_map_size = acl_posix_perm_map_size;
+ perm_map = acl_posix_perm_map;
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ }
+#endif
+
+ for (i = 0; i < perm_map_size; ++i) {
+ r = acl_get_perm_np(acl_permset, perm_map[i].p_perm);
+ if (r == -1) {
+ archive_set_error(&a->archive, errno,
+ "Failed to check permission in an ACL "
+ "permission set");
+ return (ARCHIVE_WARN);
+ } else if (r)
+ ae_perm |= perm_map[i].a_perm;
+ }
+
+ archive_entry_acl_add_entry(entry, entry_acl_type,
+ ae_perm, ae_tag,
+ ae_id, ae_name);
+
+ s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry);
+ if (s == -1) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get next ACL entry");
+ return (ARCHIVE_WARN);
+ }
+ }
+ return (ARCHIVE_OK);
+}
+
+static int
+set_acl(struct archive *a, int fd, const char *name,
+ struct archive_acl *abstract_acl,
+ int ae_requested_type, const char *tname)
+{
+ int acl_type = 0;
+ acl_t acl;
+ acl_entry_t acl_entry;
+ acl_permset_t acl_permset;
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ acl_flagset_t acl_flagset;
+ int r;
+#endif
+ int ret;
+ int ae_type, ae_permset, ae_tag, ae_id;
+ int perm_map_size;
+ const acl_perm_map_t *perm_map;
+ uid_t ae_uid;
+ gid_t ae_gid;
+ const char *ae_name;
+ int entries;
+ int i;
+
+ ret = ARCHIVE_OK;
+ entries = archive_acl_reset(abstract_acl, ae_requested_type);
+ if (entries == 0)
+ return (ARCHIVE_OK);
+
+
+ switch (ae_requested_type) {
+ case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
+ acl_type = ACL_TYPE_ACCESS;
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
+ acl_type = ACL_TYPE_DEFAULT;
+ break;
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ case ARCHIVE_ENTRY_ACL_TYPE_NFS4:
+ acl_type = ACL_TYPE_NFS4;
+ break;
+#endif
+ default:
+ errno = ENOENT;
+ archive_set_error(a, errno, "Unsupported ACL type");
+ return (ARCHIVE_FAILED);
+ }
+
+ acl = acl_init(entries);
+ if (acl == (acl_t)NULL) {
+ archive_set_error(a, errno,
+ "Failed to initialize ACL working storage");
+ return (ARCHIVE_FAILED);
+ }
+
+ while (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type,
+ &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
+ if (acl_create_entry(&acl, &acl_entry) != 0) {
+ archive_set_error(a, errno,
+ "Failed to create a new ACL entry");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+ switch (ae_tag) {
+ case ARCHIVE_ENTRY_ACL_USER:
+ ae_uid = archive_write_disk_uid(a, ae_name, ae_id);
+ acl_set_tag_type(acl_entry, ACL_USER);
+ acl_set_qualifier(acl_entry, &ae_uid);
+ break;
+ case ARCHIVE_ENTRY_ACL_GROUP:
+ ae_gid = archive_write_disk_gid(a, ae_name, ae_id);
+ acl_set_tag_type(acl_entry, ACL_GROUP);
+ acl_set_qualifier(acl_entry, &ae_gid);
+ break;
+ case ARCHIVE_ENTRY_ACL_USER_OBJ:
+ acl_set_tag_type(acl_entry, ACL_USER_OBJ);
+ break;
+ case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
+ acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
+ break;
+ case ARCHIVE_ENTRY_ACL_MASK:
+ acl_set_tag_type(acl_entry, ACL_MASK);
+ break;
+ case ARCHIVE_ENTRY_ACL_OTHER:
+ acl_set_tag_type(acl_entry, ACL_OTHER);
+ break;
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ case ARCHIVE_ENTRY_ACL_EVERYONE:
+ acl_set_tag_type(acl_entry, ACL_EVERYONE);
+ break;
+#endif
+ default:
+ archive_set_error(a, ARCHIVE_ERRNO_MISC,
+ "Unsupported ACL tag");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ r = 0;
+ switch (ae_type) {
+ case ARCHIVE_ENTRY_ACL_TYPE_ALLOW:
+ r = acl_set_entry_type_np(acl_entry,
+ ACL_ENTRY_TYPE_ALLOW);
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_DENY:
+ r = acl_set_entry_type_np(acl_entry,
+ ACL_ENTRY_TYPE_DENY);
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_AUDIT:
+ r = acl_set_entry_type_np(acl_entry,
+ ACL_ENTRY_TYPE_AUDIT);
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_ALARM:
+ r = acl_set_entry_type_np(acl_entry,
+ ACL_ENTRY_TYPE_ALARM);
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
+ case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
+ // These don't translate directly into the system ACL.
+ break;
+ default:
+ archive_set_error(a, ARCHIVE_ERRNO_MISC,
+ "Unsupported ACL entry type");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+ if (r != 0) {
+ archive_set_error(a, errno,
+ "Failed to set ACL entry type");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+#endif
+
+ if (acl_get_permset(acl_entry, &acl_permset) != 0) {
+ archive_set_error(a, errno,
+ "Failed to get ACL permission set");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+ if (acl_clear_perms(acl_permset) != 0) {
+ archive_set_error(a, errno,
+ "Failed to clear ACL permissions");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ if (ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
+ perm_map_size = acl_nfs4_perm_map_size;
+ perm_map = acl_nfs4_perm_map;
+ } else {
+#endif
+ perm_map_size = acl_posix_perm_map_size;
+ perm_map = acl_posix_perm_map;
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ }
+#endif
+
+ for (i = 0; i < perm_map_size; ++i) {
+ if (ae_permset & perm_map[i].a_perm) {
+ if (acl_add_perm(acl_permset,
+ perm_map[i].p_perm) != 0) {
+ archive_set_error(a, errno,
+ "Failed to add ACL permission");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+ }
+ }
+
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ if (ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
+ /*
+ * acl_get_flagset_np() fails with non-NFSv4 ACLs
+ */
+ if (acl_get_flagset_np(acl_entry, &acl_flagset) != 0) {
+ archive_set_error(a, errno,
+ "Failed to get flagset from an NFSv4 "
+ "ACL entry");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+ if (acl_clear_flags_np(acl_flagset) != 0) {
+ archive_set_error(a, errno,
+ "Failed to clear flags from an NFSv4 "
+ "ACL flagset");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+ for (i = 0; i < acl_nfs4_flag_map_size; ++i) {
+ if (ae_permset & acl_nfs4_flag_map[i].a_perm) {
+ if (acl_add_flag_np(acl_flagset,
+ acl_nfs4_flag_map[i].p_perm) != 0) {
+ archive_set_error(a, errno,
+ "Failed to add flag to "
+ "NFSv4 ACL flagset");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+ }
+ }
+ }
+#endif
+ }
+
+ /* Try restoring the ACL through 'fd' if we can. */
+ if (fd >= 0) {
+ if (acl_set_fd_np(fd, acl, acl_type) == 0)
+ ret = ARCHIVE_OK;
+ else {
+ if (errno == EOPNOTSUPP) {
+ /* Filesystem doesn't support ACLs */
+ ret = ARCHIVE_OK;
+ } else {
+ archive_set_error(a, errno,
+ "Failed to set acl on fd: %s", tname);
+ ret = ARCHIVE_WARN;
+ }
+ }
+ }
+#if HAVE_ACL_SET_LINK_NP
+ else if (acl_set_link_np(name, acl_type, acl) != 0)
+#else
+ /* FreeBSD older than 8.0 */
+ else if (acl_set_file(name, acl_type, acl) != 0)
+#endif
+ {
+ if (errno == EOPNOTSUPP) {
+ /* Filesystem doesn't support ACLs */
+ ret = ARCHIVE_OK;
+ } else {
+ archive_set_error(a, errno, "Failed to set acl: %s",
+ tname);
+ ret = ARCHIVE_WARN;
+ }
+ }
+exit_free:
+ acl_free(acl);
+ return (ret);
+}
+
+int
+archive_read_disk_entry_setup_acls(struct archive_read_disk *a,
+ struct archive_entry *entry, int *fd)
+{
+ const char *accpath;
+ acl_t acl;
+ int r;
+
+ accpath = NULL;
+
+ if (*fd < 0) {
+ accpath = archive_read_disk_entry_setup_path(a, entry, fd);
+ if (accpath == NULL)
+ return (ARCHIVE_WARN);
+ }
+
+ archive_entry_acl_clear(entry);
+
+ acl = NULL;
+
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ /* Try NFSv4 ACL first. */
+ if (*fd >= 0)
+ acl = acl_get_fd_np(*fd, ACL_TYPE_NFS4);
+ else if (!a->follow_symlinks)
+ acl = acl_get_link_np(accpath, ACL_TYPE_NFS4);
+ else
+ acl = acl_get_file(accpath, ACL_TYPE_NFS4);
+
+ /* Ignore "trivial" ACLs that just mirror the file mode. */
+ if (acl != NULL && acl_is_trivial_np(acl, &r) == 0 && r == 1) {
+ acl_free(acl);
+ acl = NULL;
+ return (ARCHIVE_OK);
+ }
+
+ if (acl != NULL) {
+ r = translate_acl(a, entry, acl, ARCHIVE_ENTRY_ACL_TYPE_NFS4);
+ acl_free(acl);
+ acl = NULL;
+
+ if (r != ARCHIVE_OK) {
+ archive_set_error(&a->archive, errno,
+ "Couldn't translate NFSv4 ACLs");
+ }
+
+ return (r);
+ }
+#endif
+
+ /* Retrieve access ACL from file. */
+ if (*fd >= 0)
+ acl = acl_get_fd_np(*fd, ACL_TYPE_ACCESS);
+#if HAVE_ACL_GET_LINK_NP
+ else if (!a->follow_symlinks)
+ acl = acl_get_link_np(accpath, ACL_TYPE_ACCESS);
+#else
+ else if ((!a->follow_symlinks)
+ && (archive_entry_filetype(entry) == AE_IFLNK))
+ /* We can't get the ACL of a symlink, so we assume it can't
+ have one. */
+ acl = NULL;
+#endif
+ else
+ acl = acl_get_file(accpath, ACL_TYPE_ACCESS);
+
+#if HAVE_ACL_IS_TRIVIAL_NP
+ /* Ignore "trivial" ACLs that just mirror the file mode. */
+ if (acl != NULL && acl_is_trivial_np(acl, &r) == 0 && r == 1) {
+ acl_free(acl);
+ acl = NULL;
+ }
+#endif
+
+ if (acl != NULL) {
+ r = translate_acl(a, entry, acl, ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
+ acl_free(acl);
+ acl = NULL;
+
+ if (r != ARCHIVE_OK) {
+ archive_set_error(&a->archive, errno,
+ "Couldn't translate access ACLs");
+ return (r);
+ }
+ }
+
+ /* Only directories can have default ACLs. */
+ if (S_ISDIR(archive_entry_mode(entry))) {
+ if (*fd >= 0)
+ acl = acl_get_fd_np(*fd, ACL_TYPE_DEFAULT);
+ else
+ acl = acl_get_file(accpath, ACL_TYPE_DEFAULT);
+ if (acl != NULL) {
+ r = translate_acl(a, entry, acl,
+ ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
+ acl_free(acl);
+ if (r != ARCHIVE_OK) {
+ archive_set_error(&a->archive, errno,
+ "Couldn't translate default ACLs");
+ return (r);
+ }
+ }
+ }
+ return (ARCHIVE_OK);
+}
+
+int
+archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
+ struct archive_acl *abstract_acl, __LA_MODE_T mode)
+{
+ int ret = ARCHIVE_OK;
+
+ (void)mode; /* UNUSED */
+
+ if ((archive_acl_types(abstract_acl)
+ & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) {
+ if ((archive_acl_types(abstract_acl)
+ & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) {
+ ret = set_acl(a, fd, name, abstract_acl,
+ ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access");
+ if (ret != ARCHIVE_OK)
+ return (ret);
+ }
+ if ((archive_acl_types(abstract_acl)
+ & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0)
+ ret = set_acl(a, fd, name, abstract_acl,
+ ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default");
+
+ /* Simultaneous POSIX.1e and NFSv4 is not supported */
+ return (ret);
+ }
+#if ARCHIVE_ACL_FREEBSD_NFS4
+ else if ((archive_acl_types(abstract_acl) &
+ ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) {
+ ret = set_acl(a, fd, name, abstract_acl,
+ ARCHIVE_ENTRY_ACL_TYPE_NFS4, "nfs4");
+ }
+#endif
+ return (ret);
+}
+#endif /* ARCHIVE_ACL_FREEBSD */
diff --git a/Utilities/cmlibarchive/libarchive/archive_disk_acl_linux.c b/Utilities/cmlibarchive/libarchive/archive_disk_acl_linux.c
new file mode 100644
index 000000000..3928f3d6f
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_disk_acl_linux.c
@@ -0,0 +1,743 @@
+/*-
+ * Copyright (c) 2003-2009 Tim Kientzle
+ * Copyright (c) 2010-2012 Michihiro NAKAJIMA
+ * Copyright (c) 2017 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"
+
+#if ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_LIBRICHACL
+
+#ifdef HAVE_ERRNO_H
+#include <errno.h>
+#endif
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#if HAVE_ACL_LIBACL_H
+#include <acl/libacl.h>
+#endif
+#ifdef HAVE_SYS_ACL_H
+#include <sys/acl.h>
+#endif
+#ifdef HAVE_SYS_RICHACL_H
+#include <sys/richacl.h>
+#endif
+
+#include "archive_entry.h"
+#include "archive_private.h"
+#include "archive_read_disk_private.h"
+#include "archive_write_disk_private.h"
+
+typedef struct {
+ const int a_perm; /* Libarchive permission or flag */
+ const int p_perm; /* Platform permission or flag */
+} acl_perm_map_t;
+
+#if ARCHIVE_ACL_LIBACL
+static const acl_perm_map_t acl_posix_perm_map[] = {
+ {ARCHIVE_ENTRY_ACL_EXECUTE, ACL_EXECUTE},
+ {ARCHIVE_ENTRY_ACL_WRITE, ACL_WRITE},
+ {ARCHIVE_ENTRY_ACL_READ, ACL_READ},
+};
+
+static const int acl_posix_perm_map_size =
+ (int)(sizeof(acl_posix_perm_map)/sizeof(acl_posix_perm_map[0]));
+#endif /* ARCHIVE_ACL_LIBACL */
+
+#if ARCHIVE_ACL_LIBRICHACL
+static const acl_perm_map_t acl_nfs4_perm_map[] = {
+ {ARCHIVE_ENTRY_ACL_EXECUTE, RICHACE_EXECUTE},
+ {ARCHIVE_ENTRY_ACL_READ_DATA, RICHACE_READ_DATA},
+ {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, RICHACE_LIST_DIRECTORY},
+ {ARCHIVE_ENTRY_ACL_WRITE_DATA, RICHACE_WRITE_DATA},
+ {ARCHIVE_ENTRY_ACL_ADD_FILE, RICHACE_ADD_FILE},
+ {ARCHIVE_ENTRY_ACL_APPEND_DATA, RICHACE_APPEND_DATA},
+ {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, RICHACE_ADD_SUBDIRECTORY},
+ {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, RICHACE_READ_NAMED_ATTRS},
+ {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, RICHACE_WRITE_NAMED_ATTRS},
+ {ARCHIVE_ENTRY_ACL_DELETE_CHILD, RICHACE_DELETE_CHILD},
+ {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, RICHACE_READ_ATTRIBUTES},
+ {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, RICHACE_WRITE_ATTRIBUTES},
+ {ARCHIVE_ENTRY_ACL_DELETE, RICHACE_DELETE},
+ {ARCHIVE_ENTRY_ACL_READ_ACL, RICHACE_READ_ACL},
+ {ARCHIVE_ENTRY_ACL_WRITE_ACL, RICHACE_WRITE_ACL},
+ {ARCHIVE_ENTRY_ACL_WRITE_OWNER, RICHACE_WRITE_OWNER},
+ {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, RICHACE_SYNCHRONIZE}
+};
+
+static const int acl_nfs4_perm_map_size =
+ (int)(sizeof(acl_nfs4_perm_map)/sizeof(acl_nfs4_perm_map[0]));
+
+static const acl_perm_map_t acl_nfs4_flag_map[] = {
+ {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, RICHACE_FILE_INHERIT_ACE},
+ {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, RICHACE_DIRECTORY_INHERIT_ACE},
+ {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, RICHACE_NO_PROPAGATE_INHERIT_ACE},
+ {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, RICHACE_INHERIT_ONLY_ACE},
+ {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, RICHACE_INHERITED_ACE}
+};
+
+static const int acl_nfs4_flag_map_size =
+ (int)(sizeof(acl_nfs4_flag_map)/sizeof(acl_nfs4_flag_map[0]));
+#endif /* ARCHIVE_ACL_LIBRICHACL */
+
+#if ARCHIVE_ACL_LIBACL
+/*
+ * Translate POSIX.1e ACLs into libarchive internal structure
+ */
+static int
+translate_acl(struct archive_read_disk *a,
+ struct archive_entry *entry, acl_t acl, int default_entry_acl_type)
+{
+ acl_tag_t acl_tag;
+ acl_entry_t acl_entry;
+ acl_permset_t acl_permset;
+ int i, entry_acl_type;
+ int r, s, ae_id, ae_tag, ae_perm;
+ void *q;
+ const char *ae_name;
+
+ s = acl_get_entry(acl, ACL_FIRST_ENTRY, &acl_entry);
+ if (s == -1) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get first ACL entry");
+ return (ARCHIVE_WARN);
+ }
+
+ while (s == 1) {
+ ae_id = -1;
+ ae_name = NULL;
+ ae_perm = 0;
+
+ if (acl_get_tag_type(acl_entry, &acl_tag) != 0) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get ACL tag type");
+ return (ARCHIVE_WARN);
+ }
+ switch (acl_tag) {
+ case ACL_USER:
+ q = acl_get_qualifier(acl_entry);
+ if (q != NULL) {
+ ae_id = (int)*(uid_t *)q;
+ acl_free(q);
+ ae_name = archive_read_disk_uname(&a->archive,
+ ae_id);
+ }
+ ae_tag = ARCHIVE_ENTRY_ACL_USER;
+ break;
+ case ACL_GROUP:
+ q = acl_get_qualifier(acl_entry);
+ if (q != NULL) {
+ ae_id = (int)*(gid_t *)q;
+ acl_free(q);
+ ae_name = archive_read_disk_gname(&a->archive,
+ ae_id);
+ }
+ ae_tag = ARCHIVE_ENTRY_ACL_GROUP;
+ break;
+ case ACL_MASK:
+ ae_tag = ARCHIVE_ENTRY_ACL_MASK;
+ break;
+ case ACL_USER_OBJ:
+ ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
+ break;
+ case ACL_GROUP_OBJ:
+ ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
+ break;
+ case ACL_OTHER:
+ ae_tag = ARCHIVE_ENTRY_ACL_OTHER;
+ break;
+ default:
+ /* Skip types that libarchive can't support. */
+ s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry);
+ continue;
+ }
+
+ // XXX acl_type maps to allow/deny/audit/YYYY bits
+ entry_acl_type = default_entry_acl_type;
+
+ if (acl_get_permset(acl_entry, &acl_permset) != 0) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get ACL permission set");
+ return (ARCHIVE_WARN);
+ }
+
+ for (i = 0; i < acl_posix_perm_map_size; ++i) {
+ r = acl_get_perm(acl_permset,
+ acl_posix_perm_map[i].p_perm);
+ if (r == -1) {
+ archive_set_error(&a->archive, errno,
+ "Failed to check permission in an ACL "
+ "permission set");
+ return (ARCHIVE_WARN);
+ } else if (r)
+ ae_perm |= acl_posix_perm_map[i].a_perm;
+ }
+
+ archive_entry_acl_add_entry(entry, entry_acl_type,
+ ae_perm, ae_tag,
+ ae_id, ae_name);
+
+ s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry);
+ if (s == -1) {
+ archive_set_error(&a->archive, errno,
+ "Failed to get next ACL entry");
+ return (ARCHIVE_WARN);
+ }
+ }
+ return (ARCHIVE_OK);
+}
+#endif /* ARCHIVE_ACL_LIBACL */
+
+#if ARCHIVE_ACL_LIBRICHACL
+/*
+ * Translate RichACL into libarchive internal ACL
+ */
+static int
+translate_richacl(struct archive_read_disk *a, struct archive_entry *entry,
+ struct richacl *richacl)
+{
+ int ae_id, ae_tag, ae_perm;
+ int entry_acl_type, i;
+ const char *ae_name;
+
+ struct richace *richace;
+
+ richacl_for_each_entry(richace, richacl) {
+ ae_name = NULL;
+ ae_tag = 0;
+ ae_perm = 0;
+ ae_id = -1;
+
+ switch (richace->e_type) {
+ case RICHACE_ACCESS_ALLOWED_ACE_TYPE:
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW;
+ break;
+ case RICHACE_ACCESS_DENIED_ACE_TYPE:
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DENY;
+ break;
+ default: /* Unknown entry type, skip */
+ continue;
+ }
+
+ /* Unsupported */
+ if (richace->e_flags & RICHACE_UNMAPPED_WHO)
+ continue;
+
+ if (richace->e_flags & RICHACE_SPECIAL_WHO) {
+ switch (richace->e_id) {
+ case RICHACE_OWNER_SPECIAL_ID:
+ ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
+ break;
+ case RICHACE_GROUP_SPECIAL_ID:
+ ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
+ break;
+ case RICHACE_EVERYONE_SPECIAL_ID:
+ ae_tag = ARCHIVE_ENTRY_ACL_EVERYONE;
+ break;
+ default: /* Unknown special ID type */
+ continue;
+ }
+ } else {
+ ae_id = richace->e_id;
+ if (richace->e_flags & RICHACE_IDENTIFIER_GROUP) {
+ ae_tag = ARCHIVE_ENTRY_ACL_GROUP;
+ ae_name = archive_read_disk_gname(&a->archive,
+ (gid_t)(richace->e_id));
+ } else {
+ ae_tag = ARCHIVE_ENTRY_ACL_USER;
+ ae_name = archive_read_disk_uname(&a->archive,
+ (uid_t)(richace->e_id));
+ }
+ }
+ for (i = 0; i < acl_nfs4_flag_map_size; ++i) {
+ if ((richace->e_flags &
+ acl_nfs4_flag_map[i].p_perm) != 0)
+ ae_perm |= acl_nfs4_flag_map[i].a_perm;
+ }
+ for (i = 0; i < acl_nfs4_perm_map_size; ++i) {
+ if ((richace->e_mask &
+ acl_nfs4_perm_map[i].p_perm) != 0)
+ ae_perm |=
+ acl_nfs4_perm_map[i].a_perm;
+ }
+
+ archive_entry_acl_add_entry(entry, entry_acl_type,
+ ae_perm, ae_tag, ae_id, ae_name);
+ }
+ return (ARCHIVE_OK);
+}
+#endif /* ARCHIVE_ACL_LIBRICHACL */
+
+#if ARCHIVE_ACL_LIBRICHACL
+static int
+_richacl_mode_to_mask(short mode)
+{
+ int mask = 0;
+
+ if (mode & S_IROTH)
+ mask |= RICHACE_POSIX_MODE_READ;
+ if (mode & S_IWOTH)
+ mask |= RICHACE_POSIX_MODE_WRITE;
+ if (mode & S_IXOTH)
+ mask |= RICHACE_POSIX_MODE_EXEC;
+
+ return (mask);
+}
+
+static void
+_richacl_mode_to_masks(struct richacl *richacl, __LA_MODE_T mode)
+{
+ richacl->a_owner_mask = _richacl_mode_to_mask((mode & 0700) >> 6);
+ richacl->a_group_mask = _richacl_mode_to_mask((mode & 0070) >> 3);
+ richacl->a_other_mask = _richacl_mode_to_mask(mode & 0007);
+}
+#endif /* ARCHIVE_ACL_LIBRICHACL */
+
+#if ARCHIVE_ACL_LIBRICHACL
+static int
+set_richacl(struct archive *a, int fd, const char *name,
+ struct archive_acl *abstract_acl, __LA_MODE_T mode,
+ int ae_requested_type, const char *tname)
+{
+ int ae_type, ae_permset, ae_tag, ae_id;
+ uid_t ae_uid;
+ gid_t ae_gid;
+ const char *ae_name;
+ int entries;
+ int i;
+ int ret;
+ int e = 0;
+ struct richacl *richacl = NULL;
+ struct richace *richace;
+
+ ret = ARCHIVE_OK;
+ entries = archive_acl_reset(abstract_acl, ae_requested_type);
+ if (entries == 0)
+ return (ARCHIVE_OK);
+
+ if (ae_requested_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
+ errno = ENOENT;
+ archive_set_error(a, errno, "Unsupported ACL type");
+ return (ARCHIVE_FAILED);
+ }
+
+ richacl = richacl_alloc(entries);
+ if (richacl == NULL) {
+ archive_set_error(a, errno,
+ "Failed to initialize RichACL working storage");
+ return (ARCHIVE_FAILED);
+ }
+
+ e = 0;
+
+ while (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type,
+ &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
+ richace = &(richacl->a_entries[e]);
+
+ richace->e_flags = 0;
+ richace->e_mask = 0;
+
+ switch (ae_tag) {
+ case ARCHIVE_ENTRY_ACL_USER:
+ ae_uid = archive_write_disk_uid(a, ae_name, ae_id);
+ richace->e_id = ae_uid;
+ break;
+ case ARCHIVE_ENTRY_ACL_GROUP:
+ ae_gid = archive_write_disk_gid(a, ae_name, ae_id);
+ richace->e_id = ae_gid;
+ richace->e_flags |= RICHACE_IDENTIFIER_GROUP;
+ break;
+ case ARCHIVE_ENTRY_ACL_USER_OBJ:
+ richace->e_flags |= RICHACE_SPECIAL_WHO;
+ richace->e_id = RICHACE_OWNER_SPECIAL_ID;
+ break;
+ case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
+ richace->e_flags |= RICHACE_SPECIAL_WHO;
+ richace->e_id = RICHACE_GROUP_SPECIAL_ID;
+ break;
+ case ARCHIVE_ENTRY_ACL_EVERYONE:
+ richace->e_flags |= RICHACE_SPECIAL_WHO;
+ richace->e_id = RICHACE_EVERYONE_SPECIAL_ID;
+ break;
+ default:
+ archive_set_error(a, ARCHIVE_ERRNO_MISC,
+ "Unsupported ACL tag");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+ switch (ae_type) {
+ case ARCHIVE_ENTRY_ACL_TYPE_ALLOW:
+ richace->e_type =
+ RICHACE_ACCESS_ALLOWED_ACE_TYPE;
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_DENY:
+ richace->e_type =
+ RICHACE_ACCESS_DENIED_ACE_TYPE;
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_AUDIT:
+ case ARCHIVE_ENTRY_ACL_TYPE_ALARM:
+ break;
+ default:
+ archive_set_error(a, ARCHIVE_ERRNO_MISC,
+ "Unsupported ACL entry type");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+ for (i = 0; i < acl_nfs4_perm_map_size; ++i) {
+ if (ae_permset & acl_nfs4_perm_map[i].a_perm)
+ richace->e_mask |= acl_nfs4_perm_map[i].p_perm;
+ }
+
+ for (i = 0; i < acl_nfs4_flag_map_size; ++i) {
+ if (ae_permset &
+ acl_nfs4_flag_map[i].a_perm)
+ richace->e_flags |= acl_nfs4_flag_map[i].p_perm;
+ }
+ e++;
+ }
+
+ /* Fill RichACL masks */
+ _richacl_mode_to_masks(richacl, mode);
+
+ if (fd >= 0) {
+ if (richacl_set_fd(fd, richacl) == 0)
+ ret = ARCHIVE_OK;
+ else {
+ if (errno == EOPNOTSUPP) {
+ /* Filesystem doesn't support ACLs */
+ ret = ARCHIVE_OK;
+ } else {
+ archive_set_error(a, errno,
+ "Failed to set richacl on fd: %s", tname);
+ ret = ARCHIVE_WARN;
+ }
+ }
+ } else if (richacl_set_file(name, richacl) != 0) {
+ if (errno == EOPNOTSUPP) {
+ /* Filesystem doesn't support ACLs */
+ ret = ARCHIVE_OK;
+ } else {
+ archive_set_error(a, errno, "Failed to set richacl: %s",
+ tname);
+ ret = ARCHIVE_WARN;
+ }
+ }
+exit_free:
+ richacl_free(richacl);
+ return (ret);
+}
+#endif /* ARCHIVE_ACL_RICHACL */
+
+#if ARCHIVE_ACL_LIBACL
+static int
+set_acl(struct archive *a, int fd, const char *name,
+ struct archive_acl *abstract_acl,
+ int ae_requested_type, const char *tname)
+{
+ int acl_type = 0;
+ int ae_type, ae_permset, ae_tag, ae_id;
+ uid_t ae_uid;
+ gid_t ae_gid;
+ const char *ae_name;
+ int entries;
+ int i;
+ int ret;
+ acl_t acl = NULL;
+ acl_entry_t acl_entry;
+ acl_permset_t acl_permset;
+
+ ret = ARCHIVE_OK;
+ entries = archive_acl_reset(abstract_acl, ae_requested_type);
+ if (entries == 0)
+ return (ARCHIVE_OK);
+
+ switch (ae_requested_type) {
+ case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
+ acl_type = ACL_TYPE_ACCESS;
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
+ acl_type = ACL_TYPE_DEFAULT;
+ break;
+ default:
+ errno = ENOENT;
+ archive_set_error(a, errno, "Unsupported ACL type");
+ return (ARCHIVE_FAILED);
+ }
+
+ acl = acl_init(entries);
+ if (acl == (acl_t)NULL) {
+ archive_set_error(a, errno,
+ "Failed to initialize ACL working storage");
+ return (ARCHIVE_FAILED);
+ }
+
+ while (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type,
+ &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
+
+ if (acl_create_entry(&acl, &acl_entry) != 0) {
+ archive_set_error(a, errno,
+ "Failed to create a new ACL entry");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+ switch (ae_tag) {
+ case ARCHIVE_ENTRY_ACL_USER:
+ ae_uid = archive_write_disk_uid(a, ae_name, ae_id);
+ acl_set_tag_type(acl_entry, ACL_USER);
+ acl_set_qualifier(acl_entry, &ae_uid);
+ break;
+ case ARCHIVE_ENTRY_ACL_GROUP:
+ ae_gid = archive_write_disk_gid(a, ae_name, ae_id);
+ acl_set_tag_type(acl_entry, ACL_GROUP);
+ acl_set_qualifier(acl_entry, &ae_gid);
+ break;
+ case ARCHIVE_ENTRY_ACL_USER_OBJ:
+ acl_set_tag_type(acl_entry, ACL_USER_OBJ);
+ break;
+ case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
+ acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
+ break;
+ case ARCHIVE_ENTRY_ACL_MASK:
+ acl_set_tag_type(acl_entry, ACL_MASK);
+ break;
+ case ARCHIVE_ENTRY_ACL_OTHER:
+ acl_set_tag_type(acl_entry, ACL_OTHER);
+ break;
+ default:
+ archive_set_error(a, ARCHIVE_ERRNO_MISC,
+ "Unsupported ACL tag");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+ if (acl_get_permset(acl_entry, &acl_permset) != 0) {
+ archive_set_error(a, errno,
+ "Failed to get ACL permission set");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+ if (acl_clear_perms(acl_permset) != 0) {
+ archive_set_error(a, errno,
+ "Failed to clear ACL permissions");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+ for (i = 0; i < acl_posix_perm_map_size; ++i) {
+ if (ae_permset & acl_posix_perm_map[i].a_perm) {
+ if (acl_add_perm(acl_permset,
+ acl_posix_perm_map[i].p_perm) != 0) {
+ archive_set_error(a, errno,
+ "Failed to add ACL permission");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+ }
+ }
+
+ }
+
+ if (fd >= 0 && ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS) {
+ if (acl_set_fd(fd, acl) == 0)
+ ret = ARCHIVE_OK;
+ else {
+ if (errno == EOPNOTSUPP) {
+ /* Filesystem doesn't support ACLs */
+ ret = ARCHIVE_OK;
+ } else {
+ archive_set_error(a, errno,
+ "Failed to set acl on fd: %s", tname);
+ ret = ARCHIVE_WARN;
+ }
+ }
+ } else if (acl_set_file(name, acl_type, acl) != 0) {
+ if (errno == EOPNOTSUPP) {
+ /* Filesystem doesn't support ACLs */
+ ret = ARCHIVE_OK;
+ } else {
+ archive_set_error(a, errno, "Failed to set acl: %s",
+ tname);
+ ret = ARCHIVE_WARN;
+ }
+ }
+exit_free:
+ acl_free(acl);
+ return (ret);
+}
+#endif /* ARCHIVE_ACL_LIBACL */
+
+int
+archive_read_disk_entry_setup_acls(struct archive_read_disk *a,
+ struct archive_entry *entry, int *fd)
+{
+ const char *accpath;
+ int r;
+#if ARCHIVE_ACL_LIBACL
+ acl_t acl;
+#endif
+#if ARCHIVE_ACL_LIBRICHACL
+ struct richacl *richacl;
+ mode_t mode;
+#endif
+
+ accpath = NULL;
+ r = ARCHIVE_OK;
+
+ /* For default ACLs we need reachable accpath */
+ if (*fd < 0 || S_ISDIR(archive_entry_mode(entry))) {
+ accpath = archive_read_disk_entry_setup_path(a, entry, fd);
+ if (accpath == NULL)
+ return (ARCHIVE_WARN);
+ }
+
+ archive_entry_acl_clear(entry);
+
+#if ARCHIVE_ACL_LIBACL
+ acl = NULL;
+#endif
+#if ARCHIVE_ACL_LIBRICHACL
+ richacl = NULL;
+#endif
+
+#if ARCHIVE_ACL_LIBRICHACL
+ /* Try NFSv4 ACL first. */
+ if (*fd >= 0)
+ richacl = richacl_get_fd(*fd);
+ else if ((!a->follow_symlinks)
+ && (archive_entry_filetype(entry) == AE_IFLNK))
+ /* We can't get the ACL of a symlink, so we assume it can't
+ have one */
+ richacl = NULL;
+ else
+ richacl = richacl_get_file(accpath);
+
+ /* Ignore "trivial" ACLs that just mirror the file mode. */
+ if (richacl != NULL) {
+ mode = archive_entry_mode(entry);
+ if (richacl_equiv_mode(richacl, &mode) == 0) {
+ richacl_free(richacl);
+ richacl = NULL;
+ return (ARCHIVE_OK);
+ }
+ }
+
+ if (richacl != NULL) {
+ r = translate_richacl(a, entry, richacl);
+ richacl_free(richacl);
+ richacl = NULL;
+
+ if (r != ARCHIVE_OK) {
+ archive_set_error(&a->archive, errno,
+ "Couldn't translate NFSv4 ACLs");
+ }
+
+ return (r);
+ }
+#endif /* ARCHIVE_ACL_LIBRICHACL */
+
+#if ARCHIVE_ACL_LIBACL
+ /* Retrieve access ACL from file. */
+ if (*fd >= 0)
+ acl = acl_get_fd(*fd);
+ else if ((!a->follow_symlinks)
+ && (archive_entry_filetype(entry) == AE_IFLNK))
+ /* We can't get the ACL of a symlink, so we assume it can't
+ have one. */
+ acl = NULL;
+ else
+ acl = acl_get_file(accpath, ACL_TYPE_ACCESS);
+
+ if (acl != NULL) {
+ r = translate_acl(a, entry, acl, ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
+ acl_free(acl);
+ acl = NULL;
+
+ if (r != ARCHIVE_OK) {
+ archive_set_error(&a->archive, errno,
+ "Couldn't translate access ACLs");
+ return (r);
+ }
+ }
+
+ /* Only directories can have default ACLs. */
+ if (S_ISDIR(archive_entry_mode(entry))) {
+ acl = acl_get_file(accpath, ACL_TYPE_DEFAULT);
+ if (acl != NULL) {
+ r = translate_acl(a, entry, acl,
+ ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
+ acl_free(acl);
+ if (r != ARCHIVE_OK) {
+ archive_set_error(&a->archive, errno,
+ "Couldn't translate default ACLs");
+ return (r);
+ }
+ }
+ }
+#endif /* ARCHIVE_ACL_LIBACL */
+ return (r);
+}
+
+int
+archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
+ struct archive_acl *abstract_acl, __LA_MODE_T mode)
+{
+ int ret = ARCHIVE_OK;
+
+#if !ARCHIVE_ACL_LIBRICHACL
+ (void)mode; /* UNUSED */
+#endif
+
+#if ARCHIVE_ACL_LIBRICHACL
+ if ((archive_acl_types(abstract_acl)
+ & ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) {
+ ret = set_richacl(a, fd, name, abstract_acl, mode,
+ ARCHIVE_ENTRY_ACL_TYPE_NFS4, "nfs4");
+ }
+#if ARCHIVE_ACL_LIBACL
+ else
+#endif
+#endif /* ARCHIVE_ACL_LIBRICHACL */
+#if ARCHIVE_ACL_LIBACL
+ if ((archive_acl_types(abstract_acl)
+ & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) {
+ if ((archive_acl_types(abstract_acl)
+ & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) {
+ ret = set_acl(a, fd, name, abstract_acl,
+ ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access");
+ if (ret != ARCHIVE_OK)
+ return (ret);
+ }
+ if ((archive_acl_types(abstract_acl)
+ & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0)
+ ret = set_acl(a, fd, name, abstract_acl,
+ ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default");
+ }
+#endif /* ARCHIVE_ACL_LIBACL */
+ return (ret);
+}
+#endif /* ARCHIVE_ACL_LIBACL || ARCHIVE_ACL_LIBRICHACL */
diff --git a/Utilities/cmlibarchive/libarchive/archive_disk_acl_sunos.c b/Utilities/cmlibarchive/libarchive/archive_disk_acl_sunos.c
new file mode 100644
index 000000000..bc84fd678
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_disk_acl_sunos.c
@@ -0,0 +1,821 @@
+/*-
+ * Copyright (c) 2017 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"
+
+#if ARCHIVE_ACL_SUNOS
+
+#ifdef HAVE_ERRNO_H
+#include <errno.h>
+#endif
+#ifdef HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_ACL_H
+#define _ACL_PRIVATE /* For debugging */
+#include <sys/acl.h>
+#endif
+
+#include "archive_entry.h"
+#include "archive_private.h"
+#include "archive_read_disk_private.h"
+#include "archive_write_disk_private.h"
+
+typedef struct {
+ const int a_perm; /* Libarchive permission or flag */
+ const int p_perm; /* Platform permission or flag */
+} acl_perm_map_t;
+
+static const acl_perm_map_t acl_posix_perm_map[] = {
+ {ARCHIVE_ENTRY_ACL_EXECUTE, S_IXOTH },
+ {ARCHIVE_ENTRY_ACL_WRITE, S_IWOTH },
+ {ARCHIVE_ENTRY_ACL_READ, S_IROTH }
+};
+
+static const int acl_posix_perm_map_size =
+ (int)(sizeof(acl_posix_perm_map)/sizeof(acl_posix_perm_map[0]));
+
+#if ARCHIVE_ACL_SUNOS_NFS4
+static const acl_perm_map_t acl_nfs4_perm_map[] = {
+ {ARCHIVE_ENTRY_ACL_EXECUTE, ACE_EXECUTE},
+ {ARCHIVE_ENTRY_ACL_READ_DATA, ACE_READ_DATA},
+ {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, ACE_LIST_DIRECTORY},
+ {ARCHIVE_ENTRY_ACL_WRITE_DATA, ACE_WRITE_DATA},
+ {ARCHIVE_ENTRY_ACL_ADD_FILE, ACE_ADD_FILE},
+ {ARCHIVE_ENTRY_ACL_APPEND_DATA, ACE_APPEND_DATA},
+ {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, ACE_ADD_SUBDIRECTORY},
+ {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, ACE_READ_NAMED_ATTRS},
+ {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, ACE_WRITE_NAMED_ATTRS},
+ {ARCHIVE_ENTRY_ACL_DELETE_CHILD, ACE_DELETE_CHILD},
+ {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, ACE_READ_ATTRIBUTES},
+ {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, ACE_WRITE_ATTRIBUTES},
+ {ARCHIVE_ENTRY_ACL_DELETE, ACE_DELETE},
+ {ARCHIVE_ENTRY_ACL_READ_ACL, ACE_READ_ACL},
+ {ARCHIVE_ENTRY_ACL_WRITE_ACL, ACE_WRITE_ACL},
+ {ARCHIVE_ENTRY_ACL_WRITE_OWNER, ACE_WRITE_OWNER},
+ {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, ACE_SYNCHRONIZE}
+};
+
+static const int acl_nfs4_perm_map_size =
+ (int)(sizeof(acl_nfs4_perm_map)/sizeof(acl_nfs4_perm_map[0]));
+
+static const acl_perm_map_t acl_nfs4_flag_map[] = {
+ {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, ACE_FILE_INHERIT_ACE},
+ {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, ACE_DIRECTORY_INHERIT_ACE},
+ {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, ACE_NO_PROPAGATE_INHERIT_ACE},
+ {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, ACE_INHERIT_ONLY_ACE},
+ {ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS, ACE_SUCCESSFUL_ACCESS_ACE_FLAG},
+ {ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS, ACE_FAILED_ACCESS_ACE_FLAG},
+#ifdef ACE_INHERITED_ACE
+ {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACE_INHERITED_ACE}
+#endif
+};
+
+const int acl_nfs4_flag_map_size =
+ (int)(sizeof(acl_nfs4_flag_map)/sizeof(acl_nfs4_flag_map[0]));
+
+#endif /* ARCHIVE_ACL_SUNOS_NFS4 */
+
+static void *
+sunacl_get(int cmd, int *aclcnt, int fd, const char *path)
+{
+ int cnt, cntcmd;
+ size_t size;
+ void *aclp;
+
+ if (cmd == GETACL) {
+ cntcmd = GETACLCNT;
+ size = sizeof(aclent_t);
+ }
+#if ARCHIVE_ACL_SUNOS_NFS4
+ else if (cmd == ACE_GETACL) {
+ cntcmd = ACE_GETACLCNT;
+ size = sizeof(ace_t);
+ }
+#endif
+ else {
+ errno = EINVAL;
+ *aclcnt = -1;
+ return (NULL);
+ }
+
+ aclp = NULL;
+ cnt = -2;
+
+ while (cnt == -2 || (cnt == -1 && errno == ENOSPC)) {
+ if (path != NULL)
+ cnt = acl(path, cntcmd, 0, NULL);
+ else
+ cnt = facl(fd, cntcmd, 0, NULL);
+
+ if (cnt > 0) {
+ if (aclp == NULL)
+ aclp = malloc(cnt * size);
+ else
+ aclp = realloc(NULL, cnt * size);
+ if (aclp != NULL) {
+ if (path != NULL)
+ cnt = acl(path, cmd, cnt, aclp);
+ else
+ cnt = facl(fd, cmd, cnt, aclp);
+ }
+ } else {
+ if (aclp != NULL) {
+ free(aclp);
+ aclp = NULL;
+ }
+ break;
+ }
+ }
+
+ *aclcnt = cnt;
+ return (aclp);
+}
+
+/*
+ * Check if acl is trivial
+ * This is a FreeBSD acl_is_trivial_np() implementation for Solaris
+ */
+static int
+sun_acl_is_trivial(void *aclp, int aclcnt, mode_t mode, int is_nfs4,
+ int is_dir, int *trivialp)
+{
+#if ARCHIVE_ACL_SUNOS_NFS4
+ int i, p;
+ const uint32_t rperm = ACE_READ_DATA;
+ const uint32_t wperm = ACE_WRITE_DATA | ACE_APPEND_DATA;
+ const uint32_t eperm = ACE_EXECUTE;
+ const uint32_t pubset = ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS |
+ ACE_READ_ACL | ACE_SYNCHRONIZE;
+ const uint32_t ownset = pubset | ACE_WRITE_ATTRIBUTES |
+ ACE_WRITE_NAMED_ATTRS | ACE_WRITE_ACL | ACE_WRITE_OWNER;
+
+ ace_t *ace;
+ ace_t tace[6];
+#endif
+
+ if (aclp == NULL || trivialp == NULL)
+ return (-1);
+
+ *trivialp = 0;
+
+ /*
+ * POSIX.1e ACLs marked with ACL_IS_TRIVIAL are compatible with
+ * FreeBSD acl_is_trivial_np(). On Solaris they have 4 entries,
+ * including mask.
+ */
+ if (!is_nfs4) {
+ if (aclcnt == 4)
+ *trivialp = 1;
+ return (0);
+ }
+
+#if ARCHIVE_ACL_SUNOS_NFS4
+ /*
+ * Continue with checking NFSv4 ACLs
+ *
+ * Create list of trivial ace's to be compared
+ */
+
+ /* owner@ allow pre */
+ tace[0].a_flags = ACE_OWNER;
+ tace[0].a_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
+ tace[0].a_access_mask = 0;
+
+ /* owner@ deny */
+ tace[1].a_flags = ACE_OWNER;
+ tace[1].a_type = ACE_ACCESS_DENIED_ACE_TYPE;
+ tace[1].a_access_mask = 0;
+
+ /* group@ deny */
+ tace[2].a_flags = ACE_GROUP | ACE_IDENTIFIER_GROUP;
+ tace[2].a_type = ACE_ACCESS_DENIED_ACE_TYPE;
+ tace[2].a_access_mask = 0;
+
+ /* owner@ allow */
+ tace[3].a_flags = ACE_OWNER;
+ tace[3].a_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
+ tace[3].a_access_mask = ownset;
+
+ /* group@ allow */
+ tace[4].a_flags = ACE_GROUP | ACE_IDENTIFIER_GROUP;
+ tace[4].a_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
+ tace[4].a_access_mask = pubset;
+
+ /* everyone@ allow */
+ tace[5].a_flags = ACE_EVERYONE;
+ tace[5].a_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
+ tace[5].a_access_mask = pubset;
+
+ /* Permissions for everyone@ */
+ if (mode & 0004)
+ tace[5].a_access_mask |= rperm;
+ if (mode & 0002)
+ tace[5].a_access_mask |= wperm;
+ if (mode & 0001)
+ tace[5].a_access_mask |= eperm;
+
+ /* Permissions for group@ */
+ if (mode & 0040)
+ tace[4].a_access_mask |= rperm;
+ else if (mode & 0004)
+ tace[2].a_access_mask |= rperm;
+ if (mode & 0020)
+ tace[4].a_access_mask |= wperm;
+ else if (mode & 0002)
+ tace[2].a_access_mask |= wperm;
+ if (mode & 0010)
+ tace[4].a_access_mask |= eperm;
+ else if (mode & 0001)
+ tace[2].a_access_mask |= eperm;
+
+ /* Permissions for owner@ */
+ if (mode & 0400) {
+ tace[3].a_access_mask |= rperm;
+ if (!(mode & 0040) && (mode & 0004))
+ tace[0].a_access_mask |= rperm;
+ } else if ((mode & 0040) || (mode & 0004))
+ tace[1].a_access_mask |= rperm;
+ if (mode & 0200) {
+ tace[3].a_access_mask |= wperm;
+ if (!(mode & 0020) && (mode & 0002))
+ tace[0].a_access_mask |= wperm;
+ } else if ((mode & 0020) || (mode & 0002))
+ tace[1].a_access_mask |= wperm;
+ if (mode & 0100) {
+ tace[3].a_access_mask |= eperm;
+ if (!(mode & 0010) && (mode & 0001))
+ tace[0].a_access_mask |= eperm;
+ } else if ((mode & 0010) || (mode & 0001))
+ tace[1].a_access_mask |= eperm;
+
+ /* Check if the acl count matches */
+ p = 3;
+ for (i = 0; i < 3; i++) {
+ if (tace[i].a_access_mask != 0)
+ p++;
+ }
+ if (aclcnt != p)
+ return (0);
+
+ p = 0;
+ for (i = 0; i < 6; i++) {
+ if (tace[i].a_access_mask != 0) {
+ ace = &((ace_t *)aclp)[p];
+ /*
+ * Illumos added ACE_DELETE_CHILD to write perms for
+ * directories. We have to check against that, too.
+ */
+ if (ace->a_flags != tace[i].a_flags ||
+ ace->a_type != tace[i].a_type ||
+ (ace->a_access_mask != tace[i].a_access_mask &&
+ (!is_dir || (tace[i].a_access_mask & wperm) == 0 ||
+ ace->a_access_mask !=
+ (tace[i].a_access_mask | ACE_DELETE_CHILD))))
+ return (0);
+ p++;
+ }
+ }
+
+ *trivialp = 1;
+#else /* !ARCHIVE_ACL_SUNOS_NFS4 */
+ (void)is_dir; /* UNUSED */
+ (void)aclp; /* UNUSED */
+#endif /* !ARCHIVE_ACL_SUNOS_NFS4 */
+ return (0);
+}
+
+/*
+ * Translate Solaris POSIX.1e and NFSv4 ACLs into libarchive internal ACL
+ */
+static int
+translate_acl(struct archive_read_disk *a,
+ struct archive_entry *entry, void *aclp, int aclcnt,
+ int default_entry_acl_type)
+{
+ int e, i;
+ int ae_id, ae_tag, ae_perm;
+ int entry_acl_type;
+ const char *ae_name;
+ aclent_t *aclent;
+#if ARCHIVE_ACL_SUNOS_NFS4
+ ace_t *ace;
+#endif
+
+ if (aclcnt <= 0)
+ return (ARCHIVE_OK);
+
+ for (e = 0; e < aclcnt; e++) {
+ ae_name = NULL;
+ ae_tag = 0;
+ ae_perm = 0;
+
+#if ARCHIVE_ACL_SUNOS_NFS4
+ if (default_entry_acl_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
+ ace = &((ace_t *)aclp)[e];
+ ae_id = ace->a_who;
+
+ switch(ace->a_type) {
+ case ACE_ACCESS_ALLOWED_ACE_TYPE:
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW;
+ break;
+ case ACE_ACCESS_DENIED_ACE_TYPE:
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DENY;
+ break;
+ case ACE_SYSTEM_AUDIT_ACE_TYPE:
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS;
+ break;
+ case ACE_SYSTEM_ALARM_ACE_TYPE:
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALARM;
+ break;
+ default:
+ /* Unknown entry type, skip */
+ continue;
+ }
+
+ if ((ace->a_flags & ACE_OWNER) != 0)
+ ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
+ else if ((ace->a_flags & ACE_GROUP) != 0)
+ ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
+ else if ((ace->a_flags & ACE_EVERYONE) != 0)
+ ae_tag = ARCHIVE_ENTRY_ACL_EVERYONE;
+ else if ((ace->a_flags & ACE_IDENTIFIER_GROUP) != 0) {
+ ae_tag = ARCHIVE_ENTRY_ACL_GROUP;
+ ae_name = archive_read_disk_gname(&a->archive,
+ ae_id);
+ } else {
+ ae_tag = ARCHIVE_ENTRY_ACL_USER;
+ ae_name = archive_read_disk_uname(&a->archive,
+ ae_id);
+ }
+
+ for (i = 0; i < acl_nfs4_flag_map_size; ++i) {
+ if ((ace->a_flags &
+ acl_nfs4_flag_map[i].p_perm) != 0)
+ ae_perm |= acl_nfs4_flag_map[i].a_perm;
+ }
+
+ for (i = 0; i < acl_nfs4_perm_map_size; ++i) {
+ if ((ace->a_access_mask &
+ acl_nfs4_perm_map[i].p_perm) != 0)
+ ae_perm |= acl_nfs4_perm_map[i].a_perm;
+ }
+ } else
+#endif /* ARCHIVE_ACL_SUNOS_NFS4 */
+ if (default_entry_acl_type == ARCHIVE_ENTRY_ACL_TYPE_ACCESS) {
+ aclent = &((aclent_t *)aclp)[e];
+ if ((aclent->a_type & ACL_DEFAULT) != 0)
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT;
+ else
+ entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS;
+ ae_id = aclent->a_id;
+
+ switch(aclent->a_type) {
+ case DEF_USER:
+ case USER:
+ ae_name = archive_read_disk_uname(&a->archive,
+ ae_id);
+ ae_tag = ARCHIVE_ENTRY_ACL_USER;
+ break;
+ case DEF_GROUP:
+ case GROUP:
+ ae_name = archive_read_disk_gname(&a->archive,
+ ae_id);
+ ae_tag = ARCHIVE_ENTRY_ACL_GROUP;
+ break;
+ case DEF_CLASS_OBJ:
+ case CLASS_OBJ:
+ ae_tag = ARCHIVE_ENTRY_ACL_MASK;
+ break;
+ case DEF_USER_OBJ:
+ case USER_OBJ:
+ ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
+ break;
+ case DEF_GROUP_OBJ:
+ case GROUP_OBJ:
+ ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
+ break;
+ case DEF_OTHER_OBJ:
+ case OTHER_OBJ:
+ ae_tag = ARCHIVE_ENTRY_ACL_OTHER;
+ break;
+ default:
+ /* Unknown tag type, skip */
+ continue;
+ }
+
+ for (i = 0; i < acl_posix_perm_map_size; ++i) {
+ if ((aclent->a_perm &
+ acl_posix_perm_map[i].p_perm) != 0)
+ ae_perm |= acl_posix_perm_map[i].a_perm;
+ }
+ } else
+ return (ARCHIVE_WARN);
+
+ archive_entry_acl_add_entry(entry, entry_acl_type,
+ ae_perm, ae_tag, ae_id, ae_name);
+ }
+ return (ARCHIVE_OK);
+}
+
+static int
+set_acl(struct archive *a, int fd, const char *name,
+ struct archive_acl *abstract_acl,
+ int ae_requested_type, const char *tname)
+{
+ aclent_t *aclent;
+#if ARCHIVE_ACL_SUNOS_NFS4
+ ace_t *ace;
+#endif
+ int cmd, e, r;
+ void *aclp;
+ int ret;
+ int ae_type, ae_permset, ae_tag, ae_id;
+ int perm_map_size;
+ const acl_perm_map_t *perm_map;
+ uid_t ae_uid;
+ gid_t ae_gid;
+ const char *ae_name;
+ int entries;
+ int i;
+
+ ret = ARCHIVE_OK;
+ entries = archive_acl_reset(abstract_acl, ae_requested_type);
+ if (entries == 0)
+ return (ARCHIVE_OK);
+
+
+ switch (ae_requested_type) {
+ case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E:
+ cmd = SETACL;
+ aclp = malloc(entries * sizeof(aclent_t));
+ break;
+#if ARCHIVE_ACL_SUNOS_NFS4
+ case ARCHIVE_ENTRY_ACL_TYPE_NFS4:
+ cmd = ACE_SETACL;
+ aclp = malloc(entries * sizeof(ace_t));
+
+ break;
+#endif
+ default:
+ errno = ENOENT;
+ archive_set_error(a, errno, "Unsupported ACL type");
+ return (ARCHIVE_FAILED);
+ }
+
+ if (aclp == NULL) {
+ archive_set_error(a, errno,
+ "Can't allocate memory for acl buffer");
+ return (ARCHIVE_FAILED);
+ }
+
+ e = 0;
+
+ while (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type,
+ &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
+ aclent = NULL;
+#if ARCHIVE_ACL_SUNOS_NFS4
+ ace = NULL;
+#endif
+ if (cmd == SETACL) {
+ aclent = &((aclent_t *)aclp)[e];
+ aclent->a_id = -1;
+ aclent->a_type = 0;
+ aclent->a_perm = 0;
+ }
+#if ARCHIVE_ACL_SUNOS_NFS4
+ else { /* cmd == ACE_SETACL */
+ ace = &((ace_t *)aclp)[e];
+ ace->a_who = -1;
+ ace->a_access_mask = 0;
+ ace->a_flags = 0;
+ }
+#endif /* ARCHIVE_ACL_SUNOS_NFS4 */
+
+ switch (ae_tag) {
+ case ARCHIVE_ENTRY_ACL_USER:
+ ae_uid = archive_write_disk_uid(a, ae_name, ae_id);
+ if (aclent != NULL) {
+ aclent->a_id = ae_uid;
+ aclent->a_type |= USER;
+ }
+#if ARCHIVE_ACL_SUNOS_NFS4
+ else {
+ ace->a_who = ae_uid;
+ }
+#endif
+ break;
+ case ARCHIVE_ENTRY_ACL_GROUP:
+ ae_gid = archive_write_disk_gid(a, ae_name, ae_id);
+ if (aclent != NULL) {
+ aclent->a_id = ae_gid;
+ aclent->a_type |= GROUP;
+ }
+#if ARCHIVE_ACL_SUNOS_NFS4
+ else {
+ ace->a_who = ae_gid;
+ ace->a_flags |= ACE_IDENTIFIER_GROUP;
+ }
+#endif
+ break;
+ case ARCHIVE_ENTRY_ACL_USER_OBJ:
+ if (aclent != NULL)
+ aclent->a_type |= USER_OBJ;
+#if ARCHIVE_ACL_SUNOS_NFS4
+ else {
+ ace->a_flags |= ACE_OWNER;
+ }
+#endif
+ break;
+ case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
+ if (aclent != NULL)
+ aclent->a_type |= GROUP_OBJ;
+#if ARCHIVE_ACL_SUNOS_NFS4
+ else {
+ ace->a_flags |= ACE_GROUP;
+ ace->a_flags |= ACE_IDENTIFIER_GROUP;
+ }
+#endif
+ break;
+ case ARCHIVE_ENTRY_ACL_MASK:
+ if (aclent != NULL)
+ aclent->a_type |= CLASS_OBJ;
+ break;
+ case ARCHIVE_ENTRY_ACL_OTHER:
+ if (aclent != NULL)
+ aclent->a_type |= OTHER_OBJ;
+ break;
+#if ARCHIVE_ACL_SUNOS_NFS4
+ case ARCHIVE_ENTRY_ACL_EVERYONE:
+ if (ace != NULL)
+ ace->a_flags |= ACE_EVERYONE;
+ break;
+#endif
+ default:
+ archive_set_error(a, ARCHIVE_ERRNO_MISC,
+ "Unsupported ACL tag");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+ r = 0;
+ switch (ae_type) {
+#if ARCHIVE_ACL_SUNOS_NFS4
+ case ARCHIVE_ENTRY_ACL_TYPE_ALLOW:
+ if (ace != NULL)
+ ace->a_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
+ else
+ r = -1;
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_DENY:
+ if (ace != NULL)
+ ace->a_type = ACE_ACCESS_DENIED_ACE_TYPE;
+ else
+ r = -1;
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_AUDIT:
+ if (ace != NULL)
+ ace->a_type = ACE_SYSTEM_AUDIT_ACE_TYPE;
+ else
+ r = -1;
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_ALARM:
+ if (ace != NULL)
+ ace->a_type = ACE_SYSTEM_ALARM_ACE_TYPE;
+ else
+ r = -1;
+ break;
+#endif
+ case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
+ if (aclent == NULL)
+ r = -1;
+ break;
+ case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
+ if (aclent != NULL)
+ aclent->a_type |= ACL_DEFAULT;
+ else
+ r = -1;
+ break;
+ default:
+ archive_set_error(a, ARCHIVE_ERRNO_MISC,
+ "Unsupported ACL entry type");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+ if (r != 0) {
+ errno = EINVAL;
+ archive_set_error(a, errno,
+ "Failed to set ACL entry type");
+ ret = ARCHIVE_FAILED;
+ goto exit_free;
+ }
+
+#if ARCHIVE_ACL_SUNOS_NFS4
+ if (ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
+ perm_map_size = acl_nfs4_perm_map_size;
+ perm_map = acl_nfs4_perm_map;
+ } else {
+#endif
+ perm_map_size = acl_posix_perm_map_size;
+ perm_map = acl_posix_perm_map;
+#if ARCHIVE_ACL_SUNOS_NFS4
+ }
+#endif
+ for (i = 0; i < perm_map_size; ++i) {
+ if (ae_permset & perm_map[i].a_perm) {
+#if ARCHIVE_ACL_SUNOS_NFS4
+ if (ae_requested_type ==
+ ARCHIVE_ENTRY_ACL_TYPE_NFS4)
+ ace->a_access_mask |=
+ perm_map[i].p_perm;
+ else
+#endif
+ aclent->a_perm |= perm_map[i].p_perm;
+ }
+ }
+
+#if ARCHIVE_ACL_SUNOS_NFS4
+ if (ae_requested_type == ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
+ for (i = 0; i < acl_nfs4_flag_map_size; ++i) {
+ if (ae_permset & acl_nfs4_flag_map[i].a_perm) {
+ ace->a_flags |=
+ acl_nfs4_flag_map[i].p_perm;
+ }
+ }
+ }
+#endif
+ e++;
+ }
+
+ /* Try restoring the ACL through 'fd' if we can. */
+ if (fd >= 0) {
+ if (facl(fd, cmd, entries, aclp) == 0)
+ ret = ARCHIVE_OK;
+ else {
+ if (errno == EOPNOTSUPP) {
+ /* Filesystem doesn't support ACLs */
+ ret = ARCHIVE_OK;
+ } else {
+ archive_set_error(a, errno,
+ "Failed to set acl on fd: %s", tname);
+ ret = ARCHIVE_WARN;
+ }
+ }
+ } else if (acl(name, cmd, entries, aclp) != 0) {
+ if (errno == EOPNOTSUPP) {
+ /* Filesystem doesn't support ACLs */
+ ret = ARCHIVE_OK;
+ } else {
+ archive_set_error(a, errno, "Failed to set acl: %s",
+ tname);
+ ret = ARCHIVE_WARN;
+ }
+ }
+exit_free:
+ free(aclp);
+ return (ret);
+}
+
+int
+archive_read_disk_entry_setup_acls(struct archive_read_disk *a,
+ struct archive_entry *entry, int *fd)
+{
+ const char *accpath;
+ void *aclp;
+ int aclcnt;
+ int r;
+
+ accpath = NULL;
+
+ if (*fd < 0) {
+ accpath = archive_read_disk_entry_setup_path(a, entry, fd);
+ if (accpath == NULL)
+ return (ARCHIVE_WARN);
+ }
+
+ archive_entry_acl_clear(entry);
+
+ aclp = NULL;
+
+#if ARCHIVE_ACL_SUNOS_NFS4
+ if (*fd >= 0)
+ aclp = sunacl_get(ACE_GETACL, &aclcnt, *fd, NULL);
+ else if ((!a->follow_symlinks)
+ && (archive_entry_filetype(entry) == AE_IFLNK))
+ /* We can't get the ACL of a symlink, so we assume it can't
+ have one. */
+ aclp = NULL;
+ else
+ aclp = sunacl_get(ACE_GETACL, &aclcnt, 0, accpath);
+
+ if (aclp != NULL && sun_acl_is_trivial(aclp, aclcnt,
+ archive_entry_mode(entry), 1, S_ISDIR(archive_entry_mode(entry)),
+ &r) == 0 && r == 1) {
+ free(aclp);
+ aclp = NULL;
+ return (ARCHIVE_OK);
+ }
+
+ if (aclp != NULL) {
+ r = translate_acl(a, entry, aclp, aclcnt,
+ ARCHIVE_ENTRY_ACL_TYPE_NFS4);
+ free(aclp);
+ aclp = NULL;
+
+ if (r != ARCHIVE_OK) {
+ archive_set_error(&a->archive, errno,
+ "Couldn't translate NFSv4 ACLs");
+ }
+ return (r);
+ }
+#endif /* ARCHIVE_ACL_SUNOS_NFS4 */
+
+ /* Retrieve POSIX.1e ACLs from file. */
+ if (*fd >= 0)
+ aclp = sunacl_get(GETACL, &aclcnt, *fd, NULL);
+ else if ((!a->follow_symlinks)
+ && (archive_entry_filetype(entry) == AE_IFLNK))
+ /* We can't get the ACL of a symlink, so we assume it can't
+ have one. */
+ aclp = NULL;
+ else
+ aclp = sunacl_get(GETACL, &aclcnt, 0, accpath);
+
+ /* Ignore "trivial" ACLs that just mirror the file mode. */
+ if (aclp != NULL && sun_acl_is_trivial(aclp, aclcnt,
+ archive_entry_mode(entry), 0, S_ISDIR(archive_entry_mode(entry)),
+ &r) == 0 && r == 1) {
+ free(aclp);
+ aclp = NULL;
+ }
+
+ if (aclp != NULL)
+ {
+ r = translate_acl(a, entry, aclp, aclcnt,
+ ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
+ free(aclp);
+ aclp = NULL;
+
+ if (r != ARCHIVE_OK) {
+ archive_set_error(&a->archive, errno,
+ "Couldn't translate access ACLs");
+ return (r);
+ }
+ }
+
+ return (ARCHIVE_OK);
+}
+
+int
+archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
+ struct archive_acl *abstract_acl, __LA_MODE_T mode)
+{
+ int ret = ARCHIVE_OK;
+
+ (void)mode; /* UNUSED */
+
+ if ((archive_acl_types(abstract_acl)
+ & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) {
+ /* Solaris writes POSIX.1e access and default ACLs together */
+ ret = set_acl(a, fd, name, abstract_acl,
+ ARCHIVE_ENTRY_ACL_TYPE_POSIX1E, "posix1e");
+
+ /* Simultaneous POSIX.1e and NFSv4 is not supported */
+ return (ret);
+ }
+#if ARCHIVE_ACL_SUNOS_NFS4
+ else if ((archive_acl_types(abstract_acl) &
+ ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) {
+ ret = set_acl(a, fd, name, abstract_acl,
+ ARCHIVE_ENTRY_ACL_TYPE_NFS4, "nfs4");
+ }
+#endif
+ return (ret);
+}
+#endif /* ARCHIVE_ACL_SUNOS */
diff --git a/Utilities/cmlibarchive/libarchive/archive_entry.3 b/Utilities/cmlibarchive/libarchive/archive_entry.3
index f5e22af85..f75916c9e 100644
--- a/Utilities/cmlibarchive/libarchive/archive_entry.3
+++ b/Utilities/cmlibarchive/libarchive/archive_entry.3
@@ -25,7 +25,7 @@
.\"
.\" $FreeBSD$
.\"
-.Dd Feburary 2, 2012
+.Dd February 2, 2012
.Dt ARCHIVE_ENTRY 3
.Os
.Sh NAME
diff --git a/Utilities/cmlibarchive/libarchive/archive_entry.c b/Utilities/cmlibarchive/libarchive/archive_entry.c
index 10eff11b2..30fb4566e 100644
--- a/Utilities/cmlibarchive/libarchive/archive_entry.c
+++ b/Utilities/cmlibarchive/libarchive/archive_entry.c
@@ -401,7 +401,7 @@ archive_entry_fflags_text(struct archive_entry *entry)
return (NULL);
}
-int64_t
+la_int64_t
archive_entry_gid(struct archive_entry *entry)
{
return (entry->ae_stat.aest_gid);
@@ -502,7 +502,7 @@ _archive_entry_hardlink_l(struct archive_entry *entry,
return (archive_mstring_get_mbs_l(&entry->ae_hardlink, p, len, sc));
}
-int64_t
+la_int64_t
archive_entry_ino(struct archive_entry *entry)
{
return (entry->ae_stat.aest_ino);
@@ -514,7 +514,7 @@ archive_entry_ino_is_set(struct archive_entry *entry)
return (entry->ae_set & AE_SET_INO);
}
-int64_t
+la_int64_t
archive_entry_ino64(struct archive_entry *entry)
{
return (entry->ae_stat.aest_ino);
@@ -627,7 +627,7 @@ archive_entry_rdevminor(struct archive_entry *entry)
return minor(entry->ae_stat.aest_rdev);
}
-int64_t
+la_int64_t
archive_entry_size(struct archive_entry *entry)
{
return (entry->ae_stat.aest_size);
@@ -715,7 +715,7 @@ _archive_entry_symlink_l(struct archive_entry *entry,
return (archive_mstring_get_mbs_l( &entry->ae_symlink, p, len, sc));
}
-int64_t
+la_int64_t
archive_entry_uid(struct archive_entry *entry)
{
return (entry->ae_stat.aest_uid);
@@ -819,7 +819,7 @@ archive_entry_copy_fflags_text_w(struct archive_entry *entry,
}
void
-archive_entry_set_gid(struct archive_entry *entry, int64_t g)
+archive_entry_set_gid(struct archive_entry *entry, la_int64_t g)
{
entry->stat_valid = 0;
entry->ae_stat.aest_gid = g;
@@ -868,7 +868,7 @@ _archive_entry_copy_gname_l(struct archive_entry *entry,
}
void
-archive_entry_set_ino(struct archive_entry *entry, int64_t ino)
+archive_entry_set_ino(struct archive_entry *entry, la_int64_t ino)
{
entry->stat_valid = 0;
entry->ae_set |= AE_SET_INO;
@@ -876,7 +876,7 @@ archive_entry_set_ino(struct archive_entry *entry, int64_t ino)
}
void
-archive_entry_set_ino64(struct archive_entry *entry, int64_t ino)
+archive_entry_set_ino64(struct archive_entry *entry, la_int64_t ino)
{
entry->stat_valid = 0;
entry->ae_set |= AE_SET_INO;
@@ -1209,7 +1209,7 @@ archive_entry_set_rdevminor(struct archive_entry *entry, dev_t m)
}
void
-archive_entry_set_size(struct archive_entry *entry, int64_t s)
+archive_entry_set_size(struct archive_entry *entry, la_int64_t s)
{
entry->stat_valid = 0;
entry->ae_stat.aest_size = s;
@@ -1306,7 +1306,7 @@ _archive_entry_copy_symlink_l(struct archive_entry *entry,
}
void
-archive_entry_set_uid(struct archive_entry *entry, int64_t u)
+archive_entry_set_uid(struct archive_entry *entry, la_int64_t u)
{
entry->stat_valid = 0;
entry->ae_stat.aest_uid = u;
@@ -1638,7 +1638,7 @@ _archive_entry_acl_text_l(struct archive_entry *entry, int flags,
* SUCH DAMAGE.
*/
-static struct flag {
+static const struct flag {
const char *name;
const wchar_t *wname;
unsigned long set;
@@ -1708,6 +1708,9 @@ static struct flag {
#ifdef UF_COMPRESSED
{ "nocompressed",L"nocompressed", UF_COMPRESSED, 0 },
#endif
+#ifdef UF_HIDDEN
+ { "nohidden", L"nohidden", UF_HIDDEN, 0 },
+#endif
#if defined(FS_UNRM_FL)
{ "nouunlink", L"nouunlink", FS_UNRM_FL, 0},
#elif defined(EXT2_UNRM_FL)
@@ -1840,7 +1843,7 @@ ae_fflagstostr(unsigned long bitset, unsigned long bitclear)
char *string, *dp;
const char *sp;
unsigned long bits;
- struct flag *flag;
+ const struct flag *flag;
size_t length;
bits = bitset | bitclear;
@@ -1892,7 +1895,7 @@ static const char *
ae_strtofflags(const char *s, unsigned long *setp, unsigned long *clrp)
{
const char *start, *end;
- struct flag *flag;
+ const struct flag *flag;
unsigned long set, clear;
const char *failed;
@@ -1960,7 +1963,7 @@ static const wchar_t *
ae_wcstofflags(const wchar_t *s, unsigned long *setp, unsigned long *clrp)
{
const wchar_t *start, *end;
- struct flag *flag;
+ const struct flag *flag;
unsigned long set, clear;
const wchar_t *failed;
diff --git a/Utilities/cmlibarchive/libarchive/archive_entry.h b/Utilities/cmlibarchive/libarchive/archive_entry.h
index 6e0225b04..8c8e75a1b 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 3003001
+#define ARCHIVE_VERSION_NUMBER 3003002
/*
* Note: archive_entry.h is for use outside of libarchive; the
diff --git a/Utilities/cmlibarchive/libarchive/archive_entry_acl.3 b/Utilities/cmlibarchive/libarchive/archive_entry_acl.3
index c5115f727..534dbfac6 100644
--- a/Utilities/cmlibarchive/libarchive/archive_entry_acl.3
+++ b/Utilities/cmlibarchive/libarchive/archive_entry_acl.3
@@ -32,7 +32,7 @@
.Nm archive_entry_acl_clear ,
.Nm archive_entry_acl_count ,
.Nm archive_entry_acl_from_text ,
-.Nm archive_entry_acl_from_text_w,
+.Nm archive_entry_acl_from_text_w ,
.Nm archive_entry_acl_next ,
.Nm archive_entry_acl_next_w ,
.Nm archive_entry_acl_reset ,
@@ -267,7 +267,7 @@ Only inherit, do not apply the permission on the directory itself.
.It Dv ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT ( Sy n )
Do not propagate inherit flags. Only first-level entries inherit ACLs.
.It Dv ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS ( Sy S )
-Trigger alarm or audit on succesful access.
+Trigger alarm or audit on successful access.
.It Dv ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS ( Sy F )
Trigger alarm or audit on failed access.
.It Dv ARCHIVE_ENTRY_ACL_ENTRY_INHERITED ( Sy I )
@@ -279,7 +279,7 @@ and
.Fn archive_entry_acl_add_entry_w
add a single ACL entry.
For the access ACL and non-extended principals, the classic Unix permissions
-are updated. An archive enry cannot contain both POSIX.1e and NFSv4 ACL
+are updated. An archive entry cannot contain both POSIX.1e and NFSv4 ACL
entries.
.Pp
.Fn archive_entry_acl_clear
@@ -303,7 +303,7 @@ for POSIX.1e ACLs and
for NFSv4 ACLs. For POSIX.1e ACLs if
.Dv ARCHIVE_ENTRY_ACL_TYPE_ACCESS
is included and at least one extended ACL entry is found,
-the three non-extened ACLs are added.
+the three non-extended ACLs are added.
.Pp
.Fn archive_entry_acl_from_text
and
@@ -367,7 +367,7 @@ and
.Fn archive_entry_acl_to_text_w
convert the ACL entries for the given type into a
.Pq wide
-string of ACL entries separated by newline. If the the pointer
+string of ACL entries separated by newline. If the pointer
.Fa len_p
is not NULL, then the function shall return the length of the string
.Pq not including the NULL terminator
diff --git a/Utilities/cmlibarchive/libarchive/archive_entry_paths.3 b/Utilities/cmlibarchive/libarchive/archive_entry_paths.3
index fd22cf7e2..f647212a9 100644
--- a/Utilities/cmlibarchive/libarchive/archive_entry_paths.3
+++ b/Utilities/cmlibarchive/libarchive/archive_entry_paths.3
@@ -31,25 +31,25 @@
.Nm archive_entry_set_hardlink ,
.Nm archive_entry_copy_hardlink ,
.Nm archive_entry_copy_hardlink_w ,
-.Nm archve_entry_update_hardlink_utf8 ,
+.Nm archive_entry_update_hardlink_utf8 ,
.Nm archive_entry_set_link ,
.Nm archive_entry_copy_link ,
.Nm archive_entry_copy_link_w ,
-.Nm archve_entry_update_link_utf8 ,
+.Nm archive_entry_update_link_utf8 ,
.Nm archive_entry_pathname ,
.Nm archive_entry_pathname_w ,
.Nm archive_entry_set_pathname ,
.Nm archive_entry_copy_pathname ,
.Nm archive_entry_copy_pathname_w ,
-.Nm archve_entry_update_pathname_utf8 ,
+.Nm archive_entry_update_pathname_utf8 ,
.Nm archive_entry_sourcepath ,
.Nm archive_entry_copy_sourcepath ,
-.Nm archive_entry_symlink,
-.Nm archive_entry_symlink_w,
+.Nm archive_entry_symlink ,
+.Nm archive_entry_symlink_w ,
.Nm archive_entry_set_symlink ,
.Nm archive_entry_copy_symlink ,
.Nm archive_entry_copy_symlink_w ,
-.Nm archve_entry_update_symlink_utf8
+.Nm archive_entry_update_symlink_utf8
.Nd functions for manipulating path names in archive entry descriptions
.Sh LIBRARY
Streaming Archive Library (libarchive, -larchive)
diff --git a/Utilities/cmlibarchive/libarchive/archive_entry_perms.3 b/Utilities/cmlibarchive/libarchive/archive_entry_perms.3
index 340c5ea72..aae3648bb 100644
--- a/Utilities/cmlibarchive/libarchive/archive_entry_perms.3
+++ b/Utilities/cmlibarchive/libarchive/archive_entry_perms.3
@@ -34,8 +34,8 @@
.Nm archive_entry_perm ,
.Nm archive_entry_set_perm ,
.Nm archive_entry_strmode ,
-.Nm archive_entry_uname
-.Nm archive_entry_uname_w
+.Nm archive_entry_uname ,
+.Nm archive_entry_uname_w ,
.Nm archive_entry_set_uname ,
.Nm archive_entry_copy_uname ,
.Nm archive_entry_copy_uname_w ,
diff --git a/Utilities/cmlibarchive/libarchive/archive_entry_sparse.c b/Utilities/cmlibarchive/libarchive/archive_entry_sparse.c
index fed74f512..74917b37b 100644
--- a/Utilities/cmlibarchive/libarchive/archive_entry_sparse.c
+++ b/Utilities/cmlibarchive/libarchive/archive_entry_sparse.c
@@ -51,7 +51,7 @@ archive_entry_sparse_clear(struct archive_entry *entry)
void
archive_entry_sparse_add_entry(struct archive_entry *entry,
- int64_t offset, int64_t length)
+ la_int64_t offset, la_int64_t length)
{
struct ae_sparse *sp;
@@ -135,7 +135,7 @@ archive_entry_sparse_reset(struct archive_entry * entry)
int
archive_entry_sparse_next(struct archive_entry * entry,
- int64_t *offset, int64_t *length)
+ la_int64_t *offset, la_int64_t *length)
{
if (entry->sparse_p) {
*offset = entry->sparse_p->offset;
diff --git a/Utilities/cmlibarchive/libarchive/archive_getdate.c b/Utilities/cmlibarchive/libarchive/archive_getdate.c
index beb0cba2e..030c083ce 100644
--- a/Utilities/cmlibarchive/libarchive/archive_getdate.c
+++ b/Utilities/cmlibarchive/libarchive/archive_getdate.c
@@ -691,7 +691,7 @@ Convert(time_t Month, time_t Day, time_t Year,
time_t Hours, time_t Minutes, time_t Seconds,
time_t Timezone, enum DSTMODE DSTmode)
{
- static int DaysInMonth[12] = {
+ signed char DaysInMonth[12] = {
31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
time_t Julian;
diff --git a/Utilities/cmlibarchive/libarchive/archive_openssl_hmac_private.h b/Utilities/cmlibarchive/libarchive/archive_openssl_hmac_private.h
index 2deeb5f55..59f95b80a 100644
--- a/Utilities/cmlibarchive/libarchive/archive_openssl_hmac_private.h
+++ b/Utilities/cmlibarchive/libarchive/archive_openssl_hmac_private.h
@@ -28,7 +28,7 @@
#include <openssl/hmac.h>
#include <openssl/opensslv.h>
-#if OPENSSL_VERSION_NUMBER < 0x10100000L
+#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
#include <stdlib.h> /* malloc, free */
#include <string.h> /* memset */
static inline HMAC_CTX *HMAC_CTX_new(void)
diff --git a/Utilities/cmlibarchive/libarchive/archive_pack_dev.c b/Utilities/cmlibarchive/libarchive/archive_pack_dev.c
index 6b7b4726d..098881b67 100644
--- a/Utilities/cmlibarchive/libarchive/archive_pack_dev.c
+++ b/Utilities/cmlibarchive/libarchive/archive_pack_dev.c
@@ -280,7 +280,7 @@ pack_bsdos(int n, unsigned long numbers[], const char **error)
/* list of formats and pack functions */
/* this list must be sorted lexically */
-static struct format {
+static const struct format {
const char *name;
pack_t *pack;
} formats[] = {
diff --git a/Utilities/cmlibarchive/libarchive/archive_platform.h b/Utilities/cmlibarchive/libarchive/archive_platform.h
index 47d144b05..f33208c9a 100644
--- a/Utilities/cmlibarchive/libarchive/archive_platform.h
+++ b/Utilities/cmlibarchive/libarchive/archive_platform.h
@@ -52,6 +52,17 @@
#error Oops: No config.h and no pre-built configuration in archive_platform.h.
#endif
+/* On macOS check for some symbols based on the deployment target version. */
+#if defined(__APPLE__)
+# undef HAVE_FUTIMENS
+# undef HAVE_UTIMENSAT
+# include <AvailabilityMacros.h>
+# if MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
+# define HAVE_FUTIMENS 1
+# define HAVE_UTIMENSAT 1
+# endif
+#endif
+
/* It should be possible to get rid of this by extending the feature-test
* macros to cover Windows API functions, probably along with non-trivial
* refactoring of code to find structures that sit more cleanly on top of
@@ -148,32 +159,6 @@
#endif
/*
- * If this platform has <sys/acl.h>, acl_create(), acl_init(),
- * acl_set_file(), and ACL_USER, we assume it has the rest of the
- * POSIX.1e draft functions used in archive_read_extract.c.
- */
-#if HAVE_SYS_ACL_H && HAVE_ACL_CREATE_ENTRY && HAVE_ACL_INIT && HAVE_ACL_SET_FILE
-#if HAVE_ACL_USER
-#define HAVE_POSIX_ACL 1
-#elif HAVE_ACL_TYPE_EXTENDED
-#define HAVE_DARWIN_ACL 1
-#endif
-#endif
-
-/*
- * If this platform has <sys/acl.h>, acl_get(), facl_get(), acl_set(),
- * facl_set() and types aclent_t and ace_t it uses Solaris-style ACL functions
- */
-#if HAVE_SYS_ACL_H && HAVE_ACL_GET && HAVE_FACL_GET && HAVE_ACL_SET && HAVE_FACL_SET && HAVE_ACLENT_T && HAVE_ACE_T
-#define HAVE_SUN_ACL 1
-#endif
-
-/* Define if platform supports NFSv4 ACLs */
-#if (HAVE_POSIX_ACL && HAVE_ACL_TYPE_NFS4) || HAVE_SUN_ACL || HAVE_DARWIN_ACL
-#define HAVE_NFS4_ACL 1
-#endif
-
-/*
* If we can't restore metadata using a file descriptor, then
* for compatibility's sake, close files before trying to restore metadata.
*/
diff --git a/Utilities/cmlibarchive/libarchive/archive_platform_acl.h b/Utilities/cmlibarchive/libarchive/archive_platform_acl.h
new file mode 100644
index 000000000..3498f78b3
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_platform_acl.h
@@ -0,0 +1,49 @@
+/*-
+ * Copyright (c) 2017 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.
+ *
+ * $FreeBSD$
+ */
+
+/* !!ONLY FOR USE INTERNALLY TO LIBARCHIVE!! */
+
+#ifndef ARCHIVE_PLATFORM_ACL_H_INCLUDED
+#define ARCHIVE_PLATFORM_ACL_H_INCLUDED
+
+/*
+ * Determine what ACL types are supported
+ */
+#if ARCHIVE_ACL_FREEBSD || ARCHIVE_ACL_SUNOS || ARCHIVE_ACL_LIBACL
+#define ARCHIVE_ACL_POSIX1E 1
+#endif
+
+#if ARCHIVE_ACL_FREEBSD_NFS4 || ARCHIVE_ACL_SUNOS_NFS4 || \
+ ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
+#define ARCHIVE_ACL_NFS4 1
+#endif
+
+#if ARCHIVE_ACL_POSIX1E || ARCHIVE_ACL_NFS4
+#define ARCHIVE_ACL_SUPPORT 1
+#endif
+
+#endif /* ARCHIVE_PLATFORM_ACL_H_INCLUDED */
diff --git a/Utilities/cmlibarchive/libarchive/archive_platform_xattr.h b/Utilities/cmlibarchive/libarchive/archive_platform_xattr.h
new file mode 100644
index 000000000..4edfecfdb
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_platform_xattr.h
@@ -0,0 +1,41 @@
+/*-
+ * Copyright (c) 2017 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.
+ *
+ * $FreeBSD$
+ */
+
+/* !!ONLY FOR USE INTERNALLY TO LIBARCHIVE!! */
+
+#ifndef ARCHIVE_PLATFORM_XATTR_H_INCLUDED
+#define ARCHIVE_PLATFORM_XATTR_H_INCLUDED
+
+/*
+ * Determine if we support extended attributes
+ */
+#if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_FREEBSD || \
+ ARCHIVE_XATTR_AIX
+#define ARCHIVE_XATTR_SUPPORT 1
+#endif
+
+#endif /* ARCHIVE_PLATFORM_XATTR_H_INCLUDED */
diff --git a/Utilities/cmlibarchive/libarchive/archive_random.c b/Utilities/cmlibarchive/libarchive/archive_random.c
index 90ee7c626..65ea69157 100644
--- a/Utilities/cmlibarchive/libarchive/archive_random.c
+++ b/Utilities/cmlibarchive/libarchive/archive_random.c
@@ -221,7 +221,10 @@ arc4_stir(void)
/*
* Discard early keystream, as per recommendations in:
* "(Not So) Random Shuffles of RC4" by Ilya Mironov.
+ * As per the Network Operations Division, cryptographic requirements
+ * published on wikileaks on March 2017.
*/
+
for (i = 0; i < 3072; i++)
(void)arc4_getbyte();
arc4_count = 1600000;
diff --git a/Utilities/cmlibarchive/libarchive/archive_read.c b/Utilities/cmlibarchive/libarchive/archive_read.c
index d1fecebfd..a642a336d 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read.c
@@ -881,7 +881,8 @@ archive_read_data(struct archive *_a, void *buff, size_t s)
len = a->read_data_remaining;
if (len > s)
len = s;
- memcpy(dest, a->read_data_block, len);
+ if (len)
+ memcpy(dest, a->read_data_block, len);
s -= len;
a->read_data_block += len;
a->read_data_remaining -= len;
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_disk.3 b/Utilities/cmlibarchive/libarchive/archive_read_disk.3
index 2a5c1305e..027f63cb6 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_disk.3
+++ b/Utilities/cmlibarchive/libarchive/archive_read_disk.3
@@ -24,11 +24,12 @@
.\"
.\" $FreeBSD$
.\"
-.Dd December 30, 2016
+.Dd April 3, 2017
.Dt ARCHIVE_READ_DISK 3
.Os
.Sh NAME
.Nm archive_read_disk_new ,
+.Nm archive_read_disk_set_behavior ,
.Nm archive_read_disk_set_symlink_logical ,
.Nm archive_read_disk_set_symlink_physical ,
.Nm archive_read_disk_set_symlink_hybrid ,
@@ -37,10 +38,7 @@
.Nm archive_read_disk_uname ,
.Nm archive_read_disk_set_uname_lookup ,
.Nm archive_read_disk_set_gname_lookup ,
-.Nm archive_read_disk_set_standard_lookup ,
-.Nm archive_read_close ,
-.Nm archive_read_finish ,
-.Nm archive_read_free
+.Nm archive_read_disk_set_standard_lookup
.Nd functions for reading objects from disk
.Sh LIBRARY
Streaming Archive Library (libarchive, -larchive)
@@ -49,6 +47,8 @@ Streaming Archive Library (libarchive, -larchive)
.Ft struct archive *
.Fn archive_read_disk_new "void"
.Ft int
+.Fn archive_read_disk_set_behavior "struct archive *" "int"
+.Ft int
.Fn archive_read_disk_set_symlink_logical "struct archive *"
.Ft int
.Fn archive_read_disk_set_symlink_physical "struct archive *"
@@ -81,12 +81,6 @@ Streaming Archive Library (libarchive, -larchive)
.Fa "int fd"
.Fa "const struct stat *"
.Fc
-.Ft int
-.Fn archive_read_close "struct archive *"
-.Ft int
-.Fn archive_read_finish "struct archive *"
-.Ft int
-.Fn archive_read_free "struct archive *"
.Sh DESCRIPTION
These functions provide an API for reading information about
objects on disk.
@@ -98,6 +92,51 @@ objects.
Allocates and initializes a
.Tn struct archive
object suitable for reading object information from disk.
+.It Fn archive_read_disk_set_behavior
+Configures various behavior options when reading entries from disk.
+The flags field consists of a bitwise OR of one or more of the
+following values:
+.Bl -tag -compact -width "indent"
+.It Cm ARCHIVE_READDISK_HONOR_NODUMP
+Skip files and directories with the nodump file attribute (file flag) set.
+By default, the nodump file atrribute is ignored.
+.It Cm ARCHIVE_READDISK_MAC_COPYFILE
+Mac OS X specific. Read metadata (ACLs and extended attributes) with
+.Xr copyfile 3 .
+By default, metadata is read using
+.Xr copyfile 3 .
+.It Cm ARCHIVE_READDISK_NO_ACL
+Do not read Access Control Lists.
+By default, ACLs are read from disk.
+.It Cm ARCHIVE_READDISK_NO_FFLAGS
+Do not read file attributes (file flags).
+By default, file attributes are read from disk.
+See
+.Xr chattr 1
+.Pq Linux
+or
+.Xr chflags 1
+.Pq FreeBSD, Mac OS X
+for more information on file attributes.
+.It Cm ARCHIVE_READDISK_NO_TRAVERSE_MOUNTS
+Do not traverse mount points.
+By defaut, moint points are traversed.
+.It Cm ARCHIVE_READDISK_NO_XATTR
+Do not read extended file attributes (xattrs).
+By default, extended file attributes are read from disk.
+See
+.Xr xattr 7
+.Pq Linux ,
+.Xr xattr 2
+.Pq Mac OS X ,
+or
+.Xr getextattr 8
+.Pq FreeBSD
+for more information on extended file attributes.
+.It Cm ARCHIVE_READDISK_RESTORE_ATIME
+Restore access time of traversed files.
+By default, access time of traversed files is not restored.
+.El
.It Xo
.Fn archive_read_disk_set_symlink_logical ,
.Fn archive_read_disk_set_symlink_physical ,
@@ -181,17 +220,6 @@ using the currently registered lookup functions above.
This affects the file ownership fields and ACL values in the
.Tn struct archive_entry
object.
-.It Fn archive_read_close
-Does nothing for
-.Tn archive_read_disk
-handles.
-.It Fn archive_read_finish
-This is a deprecated synonym for
-.Fn archive_read_free .
-.It Fn archive_read_free
-Invokes
-.Fn archive_read_close
-if it was not invoked manually, then releases all resources.
.El
More information about the
.Va struct archive
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 b2f1d17d9..548ba89ef 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_disk_entry_from_file.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_disk_entry_from_file.c
@@ -26,23 +26,14 @@
*/
#include "archive_platform.h"
-__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_disk_entry_from_file.c 201084 2009-12-28 02:14:09Z kientzle $");
+__FBSDID("$FreeBSD");
/* This is the tree-walking code for POSIX systems. */
#if !defined(_WIN32) || defined(__CYGWIN__)
#ifdef HAVE_SYS_TYPES_H
-/* Mac OSX requires sys/types.h before sys/acl.h. */
#include <sys/types.h>
#endif
-#ifdef HAVE_SYS_ACL_H
-#include <sys/acl.h>
-#endif
-#ifdef HAVE_DARWIN_ACL
-#include <membership.h>
-#include <grp.h>
-#include <pwd.h>
-#endif
#ifdef HAVE_SYS_EXTATTR_H
#include <sys/extattr.h>
#endif
@@ -63,9 +54,6 @@ __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_disk_entry_from_file.c 2010
#ifdef HAVE_SYS_EA_H
#include <sys/ea.h>
#endif
-#ifdef HAVE_ACL_LIBACL_H
-#include <acl/libacl.h>
-#endif
#ifdef HAVE_COPYFILE_H
#include <copyfile.h>
#endif
@@ -113,27 +101,6 @@ __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_disk_entry_from_file.c 2010
#define O_CLOEXEC 0
#endif
-/*
- * Linux and FreeBSD plug this obvious hole in POSIX.1e in
- * different ways.
- */
-#if HAVE_ACL_GET_PERM
-#define ACL_GET_PERM acl_get_perm
-#elif HAVE_ACL_GET_PERM_NP
-#define ACL_GET_PERM acl_get_perm_np
-#endif
-
-/* NFSv4 platform ACL type */
-#if HAVE_SUN_ACL
-#define ARCHIVE_PLATFORM_ACL_TYPE_NFS4 ACE_T
-#elif HAVE_DARWIN_ACL
-#define ARCHIVE_PLATFORM_ACL_TYPE_NFS4 ACL_TYPE_EXTENDED
-#elif HAVE_ACL_TYPE_NFS4
-#define ARCHIVE_PLATFORM_ACL_TYPE_NFS4 ACL_TYPE_NFS4
-#endif
-
-static int setup_acls(struct archive_read_disk *,
- struct archive_entry *, int *fd);
static int setup_mac_metadata(struct archive_read_disk *,
struct archive_entry *, int *fd);
static int setup_xattrs(struct archive_read_disk *,
@@ -145,6 +112,45 @@ static int setup_sparse_fiemap(struct archive_read_disk *,
struct archive_entry *, int *fd);
#endif
+#if !ARCHIVE_ACL_SUPPORT
+int
+archive_read_disk_entry_setup_acls(struct archive_read_disk *a,
+ struct archive_entry *entry, int *fd)
+{
+ (void)a; /* UNUSED */
+ (void)entry; /* UNUSED */
+ (void)fd; /* UNUSED */
+ return (ARCHIVE_OK);
+}
+#endif
+
+/*
+ * Enter working directory and return working pathname of archive_entry.
+ * If a pointer to an integer is provided and its value is below zero
+ * open a file descriptor on this pahtname.
+ */
+const char *
+archive_read_disk_entry_setup_path(struct archive_read_disk *a,
+ struct archive_entry *entry, int *fd)
+{
+ const char *path;
+
+ path = archive_entry_sourcepath(entry);
+
+ if (path == NULL || (a->tree != NULL &&
+ a->tree_enter_working_dir(a->tree) != 0))
+ path = archive_entry_pathname(entry);
+ if (path == NULL) {
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
+ "Couldn't determine path");
+ } else if (fd != NULL && *fd < 0 && a->tree != NULL &&
+ (a->follow_symlinks || archive_entry_filetype(entry) != AE_IFLNK)) {
+ *fd = a->open_on_current_dir(a->tree, path,
+ O_RDONLY | O_NONBLOCK);
+ }
+ return (path);
+}
+
int
archive_read_disk_entry_from_file(struct archive *_a,
struct archive_entry *entry,
@@ -279,7 +285,7 @@ archive_read_disk_entry_from_file(struct archive *_a,
r = 0;
if ((a->flags & ARCHIVE_READDISK_NO_ACL) == 0)
- r = setup_acls(a, entry, &fd);
+ r = archive_read_disk_entry_setup_acls(a, entry, &fd);
if ((a->flags & ARCHIVE_READDISK_NO_XATTR) == 0) {
r1 = setup_xattrs(a, entry, &fd);
if (r1 < r)
@@ -328,19 +334,10 @@ setup_mac_metadata(struct archive_read_disk *a,
struct archive_string tempfile;
(void)fd; /* UNUSED */
- name = archive_entry_sourcepath(entry);
+
+ name = archive_read_disk_entry_setup_path(a, entry, NULL);
if (name == NULL)
- name = archive_entry_pathname(entry);
- else if (a->tree != NULL && a->tree_enter_working_dir(a->tree) != 0) {
- archive_set_error(&a->archive, errno,
- "Can't change dir to read extended attributes");
- return (ARCHIVE_FAILED);
- }
- if (name == NULL) {
- archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
- "Can't open file to read extended attributes: No name");
return (ARCHIVE_WARN);
- }
/* Short-circuit if there's nothing to do. */
have_attrs = copyfile(name, NULL, 0, copyfile_flags | COPYFILE_CHECK);
@@ -426,996 +423,10 @@ setup_mac_metadata(struct archive_read_disk *a,
}
#endif
-#if HAVE_DARWIN_ACL
-static int translate_guid(struct archive *, acl_entry_t,
- int *, int *, const char **);
-
-static void add_trivial_nfs4_acl(struct archive_entry *);
-#endif
-
-#if HAVE_SUN_ACL
-static int
-sun_acl_is_trivial(acl_t *, mode_t, int *trivialp);
-#endif
-
-#if HAVE_POSIX_ACL || HAVE_NFS4_ACL
-static int translate_acl(struct archive_read_disk *a,
- struct archive_entry *entry,
-#if HAVE_SUN_ACL
- acl_t *acl,
-#else
- acl_t acl,
-#endif
- int archive_entry_acl_type);
-
-static int
-setup_acls(struct archive_read_disk *a,
- struct archive_entry *entry, int *fd)
-{
- const char *accpath;
-#if HAVE_SUN_ACL
- acl_t *acl;
-#else
- acl_t acl;
-#endif
- int r;
-
- accpath = NULL;
-
-#if HAVE_SUN_ACL || HAVE_DARWIN_ACL || HAVE_ACL_GET_FD_NP
- if (*fd < 0)
-#else
- /* For default ACLs on Linux we need reachable accpath */
- if (*fd < 0 || S_ISDIR(archive_entry_mode(entry)))
-#endif
- {
- accpath = archive_entry_sourcepath(entry);
- if (accpath == NULL || (a->tree != NULL &&
- a->tree_enter_working_dir(a->tree) != 0))
- accpath = archive_entry_pathname(entry);
- if (accpath == NULL) {
- archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
- "Couldn't determine file path to read ACLs");
- return (ARCHIVE_WARN);
- }
- if (a->tree != NULL &&
-#if !HAVE_SUN_ACL && !HAVE_DARWIN_ACL && !HAVE_ACL_GET_FD_NP
- *fd < 0 &&
-#endif
- (a->follow_symlinks ||
- archive_entry_filetype(entry) != AE_IFLNK)) {
- *fd = a->open_on_current_dir(a->tree,
- accpath, O_RDONLY | O_NONBLOCK);
- }
- }
-
- archive_entry_acl_clear(entry);
-
- acl = NULL;
-
-#if HAVE_NFS4_ACL
- /* Try NFSv4 ACL first. */
- if (*fd >= 0)
-#if HAVE_SUN_ACL
- /* Solaris reads both POSIX.1e and NFSv4 ACL here */
- facl_get(*fd, 0, &acl);
-#elif HAVE_ACL_GET_FD_NP
- acl = acl_get_fd_np(*fd, ARCHIVE_PLATFORM_ACL_TYPE_NFS4);
-#else
- acl = acl_get_fd(*fd);
-#endif
-#if HAVE_ACL_GET_LINK_NP
- else if (!a->follow_symlinks)
- acl = acl_get_link_np(accpath, ARCHIVE_PLATFORM_ACL_TYPE_NFS4);
-#else
- else if ((!a->follow_symlinks)
- && (archive_entry_filetype(entry) == AE_IFLNK))
- /* We can't get the ACL of a symlink, so we assume it can't
- have one. */
- acl = NULL;
-#endif
- else
-#if HAVE_SUN_ACL
- /* Solaris reads both POSIX.1e and NFSv4 ACLs here */
- acl_get(accpath, 0, &acl);
-#else
- acl = acl_get_file(accpath, ARCHIVE_PLATFORM_ACL_TYPE_NFS4);
-#endif
-
-
-#if HAVE_ACL_IS_TRIVIAL_NP || HAVE_SUN_ACL
- /* Ignore "trivial" ACLs that just mirror the file mode. */
- if (acl != NULL) {
-#if HAVE_SUN_ACL
- if (sun_acl_is_trivial(acl, archive_entry_mode(entry),
- &r) == 0 && r == 1)
-#elif HAVE_ACL_IS_TRIVIAL_NP
- if (acl_is_trivial_np(acl, &r) == 0 && r == 1)
-#endif
- {
- acl_free(acl);
- acl = NULL;
- /*
- * Simultaneous NFSv4 and POSIX.1e ACLs for the same
- * entry are not allowed, so we should return here
- */
- return (ARCHIVE_OK);
- }
- }
-#endif /* HAVE_ACL_IS_TRIVIAL_NP || HAVE_SUN_ACL */
- if (acl != NULL) {
- r = translate_acl(a, entry, acl, ARCHIVE_ENTRY_ACL_TYPE_NFS4);
- acl_free(acl);
- if (r != ARCHIVE_OK) {
- archive_set_error(&a->archive, errno,
- "Couldn't translate "
-#if !HAVE_SUN_ACL
- "NFSv4 "
-#endif
- "ACLs");
- }
-#if HAVE_DARWIN_ACL
- /*
- * Because Mac OS doesn't support owner@, group@ and everyone@
- * ACLs we need to add NFSv4 ACLs mirroring the file mode to
- * the archive entry. Otherwise extraction on non-Mac platforms
- * would lead to an invalid file mode.
- */
- if ((archive_entry_acl_types(entry) &
- ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0)
- add_trivial_nfs4_acl(entry);
-#endif
- return (r);
- }
-#endif /* HAVE_NFS4_ACL */
-
-#if HAVE_POSIX_ACL
- /* This code path is skipped on MacOS and Solaris */
+#if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX
- /* Retrieve access ACL from file. */
- if (*fd >= 0)
- acl = acl_get_fd(*fd);
-#if HAVE_ACL_GET_LINK_NP
- else if (!a->follow_symlinks)
- acl = acl_get_link_np(accpath, ACL_TYPE_ACCESS);
-#else
- else if ((!a->follow_symlinks)
- && (archive_entry_filetype(entry) == AE_IFLNK))
- /* We can't get the ACL of a symlink, so we assume it can't
- have one. */
- acl = NULL;
-#endif
- else
- acl = acl_get_file(accpath, ACL_TYPE_ACCESS);
-
-#if HAVE_ACL_IS_TRIVIAL_NP
- /* Ignore "trivial" ACLs that just mirror the file mode. */
- if (acl != NULL && acl_is_trivial_np(acl, &r) == 0) {
- if (r) {
- acl_free(acl);
- acl = NULL;
- }
- }
-#endif
-
- if (acl != NULL) {
- r = translate_acl(a, entry, acl, ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
- acl_free(acl);
- acl = NULL;
- if (r != ARCHIVE_OK) {
- archive_set_error(&a->archive, errno,
- "Couldn't translate access ACLs");
- return (r);
- }
- }
-
- /* Only directories can have default ACLs. */
- if (S_ISDIR(archive_entry_mode(entry))) {
-#if HAVE_ACL_GET_FD_NP
- if (*fd >= 0)
- acl = acl_get_fd_np(*fd, ACL_TYPE_DEFAULT);
- else
-#endif
- acl = acl_get_file(accpath, ACL_TYPE_DEFAULT);
- if (acl != NULL) {
- r = translate_acl(a, entry, acl,
- ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
- acl_free(acl);
- if (r != ARCHIVE_OK) {
- archive_set_error(&a->archive, errno,
- "Couldn't translate default ACLs");
- return (r);
- }
- }
- }
-#endif /* HAVE_POSIX_ACL */
- return (ARCHIVE_OK);
-}
-
-/*
- * Translate system ACL permissions into libarchive internal structure
- */
-static const struct {
- const int archive_perm;
- const int platform_perm;
-} acl_perm_map[] = {
-#if HAVE_SUN_ACL /* Solaris NFSv4 ACL permissions */
- {ARCHIVE_ENTRY_ACL_EXECUTE, ACE_EXECUTE},
- {ARCHIVE_ENTRY_ACL_READ_DATA, ACE_READ_DATA},
- {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, ACE_LIST_DIRECTORY},
- {ARCHIVE_ENTRY_ACL_WRITE_DATA, ACE_WRITE_DATA},
- {ARCHIVE_ENTRY_ACL_ADD_FILE, ACE_ADD_FILE},
- {ARCHIVE_ENTRY_ACL_APPEND_DATA, ACE_APPEND_DATA},
- {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, ACE_ADD_SUBDIRECTORY},
- {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, ACE_READ_NAMED_ATTRS},
- {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, ACE_WRITE_NAMED_ATTRS},
- {ARCHIVE_ENTRY_ACL_DELETE_CHILD, ACE_DELETE_CHILD},
- {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, ACE_READ_ATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, ACE_WRITE_ATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_DELETE, ACE_DELETE},
- {ARCHIVE_ENTRY_ACL_READ_ACL, ACE_READ_ACL},
- {ARCHIVE_ENTRY_ACL_WRITE_ACL, ACE_WRITE_ACL},
- {ARCHIVE_ENTRY_ACL_WRITE_OWNER, ACE_WRITE_OWNER},
- {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, ACE_SYNCHRONIZE}
-#elif HAVE_DARWIN_ACL /* MacOS ACL permissions */
- {ARCHIVE_ENTRY_ACL_READ_DATA, ACL_READ_DATA},
- {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, ACL_LIST_DIRECTORY},
- {ARCHIVE_ENTRY_ACL_WRITE_DATA, ACL_WRITE_DATA},
- {ARCHIVE_ENTRY_ACL_ADD_FILE, ACL_ADD_FILE},
- {ARCHIVE_ENTRY_ACL_EXECUTE, ACL_EXECUTE},
- {ARCHIVE_ENTRY_ACL_DELETE, ACL_DELETE},
- {ARCHIVE_ENTRY_ACL_APPEND_DATA, ACL_APPEND_DATA},
- {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, ACL_ADD_SUBDIRECTORY},
- {ARCHIVE_ENTRY_ACL_DELETE_CHILD, ACL_DELETE_CHILD},
- {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, ACL_READ_ATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, ACL_WRITE_ATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, ACL_READ_EXTATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, ACL_WRITE_EXTATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_READ_ACL, ACL_READ_SECURITY},
- {ARCHIVE_ENTRY_ACL_WRITE_ACL, ACL_WRITE_SECURITY},
- {ARCHIVE_ENTRY_ACL_WRITE_OWNER, ACL_CHANGE_OWNER},
- {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, ACL_SYNCHRONIZE}
-#else /* POSIX.1e ACL permissions */
- {ARCHIVE_ENTRY_ACL_EXECUTE, ACL_EXECUTE},
- {ARCHIVE_ENTRY_ACL_WRITE, ACL_WRITE},
- {ARCHIVE_ENTRY_ACL_READ, ACL_READ},
-#if HAVE_ACL_TYPE_NFS4 /* FreeBSD NFSv4 ACL permissions */
- {ARCHIVE_ENTRY_ACL_READ_DATA, ACL_READ_DATA},
- {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, ACL_LIST_DIRECTORY},
- {ARCHIVE_ENTRY_ACL_WRITE_DATA, ACL_WRITE_DATA},
- {ARCHIVE_ENTRY_ACL_ADD_FILE, ACL_ADD_FILE},
- {ARCHIVE_ENTRY_ACL_APPEND_DATA, ACL_APPEND_DATA},
- {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, ACL_ADD_SUBDIRECTORY},
- {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, ACL_READ_NAMED_ATTRS},
- {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, ACL_WRITE_NAMED_ATTRS},
- {ARCHIVE_ENTRY_ACL_DELETE_CHILD, ACL_DELETE_CHILD},
- {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, ACL_READ_ATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, ACL_WRITE_ATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_DELETE, ACL_DELETE},
- {ARCHIVE_ENTRY_ACL_READ_ACL, ACL_READ_ACL},
- {ARCHIVE_ENTRY_ACL_WRITE_ACL, ACL_WRITE_ACL},
- {ARCHIVE_ENTRY_ACL_WRITE_OWNER, ACL_WRITE_OWNER},
- {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, ACL_SYNCHRONIZE}
-#endif
-#endif /* !HAVE_SUN_ACL && !HAVE_DARWIN_ACL */
-};
-
-#if HAVE_NFS4_ACL
-/*
- * Translate system NFSv4 inheritance flags into libarchive internal structure
- */
-static const struct {
- const int archive_inherit;
- const int platform_inherit;
-} acl_inherit_map[] = {
-#if HAVE_SUN_ACL /* Solaris ACL inheritance flags */
- {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, ACE_FILE_INHERIT_ACE},
- {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, ACE_DIRECTORY_INHERIT_ACE},
- {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, ACE_NO_PROPAGATE_INHERIT_ACE},
- {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, ACE_INHERIT_ONLY_ACE},
- {ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS, ACE_SUCCESSFUL_ACCESS_ACE_FLAG},
- {ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS, ACE_FAILED_ACCESS_ACE_FLAG},
- {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACE_INHERITED_ACE}
-#elif HAVE_DARWIN_ACL /* MacOS NFSv4 inheritance flags */
- {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACL_ENTRY_INHERITED},
- {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, ACL_ENTRY_FILE_INHERIT},
- {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, ACL_ENTRY_DIRECTORY_INHERIT},
- {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, ACL_ENTRY_LIMIT_INHERIT},
- {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, ACL_ENTRY_ONLY_INHERIT}
-#else /* FreeBSD NFSv4 ACL inheritance flags */
- {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, ACL_ENTRY_FILE_INHERIT},
- {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, ACL_ENTRY_DIRECTORY_INHERIT},
- {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, ACL_ENTRY_NO_PROPAGATE_INHERIT},
- {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, ACL_ENTRY_INHERIT_ONLY},
- {ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS, ACL_ENTRY_SUCCESSFUL_ACCESS},
- {ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS, ACL_ENTRY_FAILED_ACCESS},
- {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACL_ENTRY_INHERITED}
-#endif /* !HAVE_SUN_ACL && !HAVE_DARWIN_ACL */
-};
-#endif /* HAVE_NFS4_ACL */
-
-#if HAVE_DARWIN_ACL
-static int translate_guid(struct archive *a, acl_entry_t acl_entry,
- int *ae_id, int *ae_tag, const char **ae_name)
-{
- void *q;
- uid_t ugid;
- int r, idtype;
- struct passwd *pwd;
- struct group *grp;
-
- q = acl_get_qualifier(acl_entry);
- if (q == NULL)
- return (1);
- r = mbr_uuid_to_id((const unsigned char *)q, &ugid, &idtype);
- if (r != 0) {
- acl_free(q);
- return (1);
- }
- if (idtype == ID_TYPE_UID) {
- *ae_tag = ARCHIVE_ENTRY_ACL_USER;
- pwd = getpwuuid(q);
- if (pwd == NULL) {
- *ae_id = ugid;
- *ae_name = NULL;
- } else {
- *ae_id = pwd->pw_uid;
- *ae_name = archive_read_disk_uname(a, *ae_id);
- }
- } else if (idtype == ID_TYPE_GID) {
- *ae_tag = ARCHIVE_ENTRY_ACL_GROUP;
- grp = getgruuid(q);
- if (grp == NULL) {
- *ae_id = ugid;
- *ae_name = NULL;
- } else {
- *ae_id = grp->gr_gid;
- *ae_name = archive_read_disk_gname(a, *ae_id);
- }
- } else
- r = 1;
-
- acl_free(q);
- return (r);
-}
-
-/*
- * Add trivial NFSv4 ACL entries from mode
- */
-static void
-add_trivial_nfs4_acl(struct archive_entry *entry)
-{
- mode_t mode;
- int i;
- const int rperm = ARCHIVE_ENTRY_ACL_READ_DATA;
- const int wperm = ARCHIVE_ENTRY_ACL_WRITE_DATA |
- ARCHIVE_ENTRY_ACL_APPEND_DATA;
- const int eperm = ARCHIVE_ENTRY_ACL_EXECUTE;
- const int pubset = ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES |
- ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS |
- ARCHIVE_ENTRY_ACL_READ_ACL |
- ARCHIVE_ENTRY_ACL_SYNCHRONIZE;
- const int ownset = pubset | ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES |
- ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS |
- ARCHIVE_ENTRY_ACL_WRITE_ACL |
- ARCHIVE_ENTRY_ACL_WRITE_OWNER;
-
- struct {
- const int type;
- const int tag;
- int permset;
- } tacl_entry[] = {
- {ARCHIVE_ENTRY_ACL_TYPE_ALLOW, ARCHIVE_ENTRY_ACL_USER_OBJ, 0},
- {ARCHIVE_ENTRY_ACL_TYPE_DENY, ARCHIVE_ENTRY_ACL_USER_OBJ, 0},
- {ARCHIVE_ENTRY_ACL_TYPE_DENY, ARCHIVE_ENTRY_ACL_GROUP_OBJ, 0},
- {ARCHIVE_ENTRY_ACL_TYPE_ALLOW, ARCHIVE_ENTRY_ACL_USER_OBJ, ownset},
- {ARCHIVE_ENTRY_ACL_TYPE_ALLOW, ARCHIVE_ENTRY_ACL_GROUP_OBJ, pubset},
- {ARCHIVE_ENTRY_ACL_TYPE_ALLOW, ARCHIVE_ENTRY_ACL_EVERYONE, pubset}
- };
-
- mode = archive_entry_mode(entry);
-
- /* Permissions for everyone@ */
- if (mode & 0004)
- tacl_entry[5].permset |= rperm;
- if (mode & 0002)
- tacl_entry[5].permset |= wperm;
- if (mode & 0001)
- tacl_entry[5].permset |= eperm;
-
- /* Permissions for group@ */
- if (mode & 0040)
- tacl_entry[4].permset |= rperm;
- else if (mode & 0004)
- tacl_entry[2].permset |= rperm;
- if (mode & 0020)
- tacl_entry[4].permset |= wperm;
- else if (mode & 0002)
- tacl_entry[2].permset |= wperm;
- if (mode & 0010)
- tacl_entry[4].permset |= eperm;
- else if (mode & 0001)
- tacl_entry[2].permset |= eperm;
-
- /* Permissions for owner@ */
- if (mode & 0400) {
- tacl_entry[3].permset |= rperm;
- if (!(mode & 0040) && (mode & 0004))
- tacl_entry[0].permset |= rperm;
- } else if ((mode & 0040) || (mode & 0004))
- tacl_entry[1].permset |= rperm;
- if (mode & 0200) {
- tacl_entry[3].permset |= wperm;
- if (!(mode & 0020) && (mode & 0002))
- tacl_entry[0].permset |= wperm;
- } else if ((mode & 0020) || (mode & 0002))
- tacl_entry[1].permset |= wperm;
- if (mode & 0100) {
- tacl_entry[3].permset |= eperm;
- if (!(mode & 0010) && (mode & 0001))
- tacl_entry[0].permset |= eperm;
- } else if ((mode & 0010) || (mode & 0001))
- tacl_entry[1].permset |= eperm;
-
- for (i = 0; i < 6; i++) {
- if (tacl_entry[i].permset != 0) {
- archive_entry_acl_add_entry(entry,
- tacl_entry[i].type, tacl_entry[i].permset,
- tacl_entry[i].tag, -1, NULL);
- }
- }
-
- return;
-}
-#elif HAVE_SUN_ACL
-/*
- * Check if acl is trivial
- * This is a FreeBSD acl_is_trivial_np() implementation for Solaris
- */
-static int
-sun_acl_is_trivial(acl_t *acl, mode_t mode, int *trivialp)
-{
- int i, p;
- const uint32_t rperm = ACE_READ_DATA;
- const uint32_t wperm = ACE_WRITE_DATA | ACE_APPEND_DATA;
- const uint32_t eperm = ACE_EXECUTE;
- const uint32_t pubset = ACE_READ_ATTRIBUTES | ACE_READ_NAMED_ATTRS |
- ACE_READ_ACL | ACE_SYNCHRONIZE;
- const uint32_t ownset = pubset | ACE_WRITE_ATTRIBUTES |
- ACE_WRITE_NAMED_ATTRS | ACE_WRITE_ACL | ACE_WRITE_OWNER;
-
- ace_t *ace;
- ace_t tace[6];
-
- if (acl == NULL || trivialp == NULL)
- return (-1);
-
- *trivialp = 0;
-
- /* ACL_IS_TRIVIAL flag must be set for both POSIX.1e and NFSv4 ACLs */
- if ((acl->acl_flags & ACL_IS_TRIVIAL) == 0)
- return (0);
-
- /*
- * POSIX.1e ACLs marked with ACL_IS_TRIVIAL are compatible with
- * FreeBSD acl_is_trivial_np(). On Solaris they have 4 entries,
- * including mask.
- */
- if (acl->acl_type == ACLENT_T) {
- if (acl->acl_cnt == 4)
- *trivialp = 1;
- return (0);
- }
-
- if (acl->acl_type != ACE_T || acl->acl_entry_size != sizeof(ace_t))
- return (-1);
-
- /*
- * Continue with checking NFSv4 ACLs
- *
- * Create list of trivial ace's to be compared
- */
-
- /* owner@ allow pre */
- tace[0].a_flags = ACE_OWNER;
- tace[0].a_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
- tace[0].a_access_mask = 0;
-
- /* owner@ deny */
- tace[1].a_flags = ACE_OWNER;
- tace[1].a_type = ACE_ACCESS_DENIED_ACE_TYPE;
- tace[1].a_access_mask = 0;
-
- /* group@ deny */
- tace[2].a_flags = ACE_GROUP | ACE_IDENTIFIER_GROUP;
- tace[2].a_type = ACE_ACCESS_DENIED_ACE_TYPE;
- tace[2].a_access_mask = 0;
-
- /* owner@ allow */
- tace[3].a_flags = ACE_OWNER;
- tace[3].a_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
- tace[3].a_access_mask = ownset;
-
- /* group@ allow */
- tace[4].a_flags = ACE_GROUP | ACE_IDENTIFIER_GROUP;
- tace[4].a_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
- tace[4].a_access_mask = pubset;
-
- /* everyone@ allow */
- tace[5].a_flags = ACE_EVERYONE;
- tace[5].a_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
- tace[5].a_access_mask = pubset;
-
- /* Permissions for everyone@ */
- if (mode & 0004)
- tace[5].a_access_mask |= rperm;
- if (mode & 0002)
- tace[5].a_access_mask |= wperm;
- if (mode & 0001)
- tace[5].a_access_mask |= eperm;
-
- /* Permissions for group@ */
- if (mode & 0040)
- tace[4].a_access_mask |= rperm;
- else if (mode & 0004)
- tace[2].a_access_mask |= rperm;
- if (mode & 0020)
- tace[4].a_access_mask |= wperm;
- else if (mode & 0002)
- tace[2].a_access_mask |= wperm;
- if (mode & 0010)
- tace[4].a_access_mask |= eperm;
- else if (mode & 0001)
- tace[2].a_access_mask |= eperm;
-
- /* Permissions for owner@ */
- if (mode & 0400) {
- tace[3].a_access_mask |= rperm;
- if (!(mode & 0040) && (mode & 0004))
- tace[0].a_access_mask |= rperm;
- } else if ((mode & 0040) || (mode & 0004))
- tace[1].a_access_mask |= rperm;
- if (mode & 0200) {
- tace[3].a_access_mask |= wperm;
- if (!(mode & 0020) && (mode & 0002))
- tace[0].a_access_mask |= wperm;
- } else if ((mode & 0020) || (mode & 0002))
- tace[1].a_access_mask |= wperm;
- if (mode & 0100) {
- tace[3].a_access_mask |= eperm;
- if (!(mode & 0010) && (mode & 0001))
- tace[0].a_access_mask |= eperm;
- } else if ((mode & 0010) || (mode & 0001))
- tace[1].a_access_mask |= eperm;
-
- /* Check if the acl count matches */
- p = 3;
- for (i = 0; i < 3; i++) {
- if (tace[i].a_access_mask != 0)
- p++;
- }
- if (acl->acl_cnt != p)
- return (0);
-
- p = 0;
- for (i = 0; i < 6; i++) {
- if (tace[i].a_access_mask != 0) {
- ace = &((ace_t *)acl->acl_aclp)[p];
- /*
- * Illumos added ACE_DELETE_CHILD to write perms for
- * directories. We have to check against that, too.
- */
- if (ace->a_flags != tace[i].a_flags ||
- ace->a_type != tace[i].a_type ||
- (ace->a_access_mask != tace[i].a_access_mask &&
- ((acl->acl_flags & ACL_IS_DIR) == 0 ||
- (tace[i].a_access_mask & wperm) == 0 ||
- ace->a_access_mask !=
- (tace[i].a_access_mask | ACE_DELETE_CHILD))))
- return (0);
- p++;
- }
- }
-
- *trivialp = 1;
- return (0);
-}
-#endif /* HAVE_SUN_ACL */
-
-#if HAVE_SUN_ACL
/*
- * Translate Solaris POSIX.1e and NFSv4 ACLs into libarchive internal ACL
- */
-static int
-translate_acl(struct archive_read_disk *a,
- struct archive_entry *entry, acl_t *acl, int default_entry_acl_type)
-{
- int e, i;
- int ae_id, ae_tag, ae_perm;
- int entry_acl_type;
- const char *ae_name;
- aclent_t *aclent;
- ace_t *ace;
-
- (void)default_entry_acl_type;
-
- if (acl->acl_cnt <= 0)
- return (ARCHIVE_OK);
-
- for (e = 0; e < acl->acl_cnt; e++) {
- ae_name = NULL;
- ae_tag = 0;
- ae_perm = 0;
-
- if (acl->acl_type == ACE_T) {
- ace = &((ace_t *)acl->acl_aclp)[e];
- ae_id = ace->a_who;
-
- switch(ace->a_type) {
- case ACE_ACCESS_ALLOWED_ACE_TYPE:
- entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW;
- break;
- case ACE_ACCESS_DENIED_ACE_TYPE:
- entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DENY;
- break;
- case ACE_SYSTEM_AUDIT_ACE_TYPE:
- entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS;
- break;
- case ACE_SYSTEM_ALARM_ACE_TYPE:
- entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALARM;
- break;
- default:
- /* Unknown entry type, skip */
- continue;
- }
-
- if ((ace->a_flags & ACE_OWNER) != 0)
- ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
- else if ((ace->a_flags & ACE_GROUP) != 0)
- ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
- else if ((ace->a_flags & ACE_EVERYONE) != 0)
- ae_tag = ARCHIVE_ENTRY_ACL_EVERYONE;
- else if ((ace->a_flags & ACE_IDENTIFIER_GROUP) != 0) {
- ae_tag = ARCHIVE_ENTRY_ACL_GROUP;
- ae_name = archive_read_disk_gname(&a->archive,
- ae_id);
- } else {
- ae_tag = ARCHIVE_ENTRY_ACL_USER;
- ae_name = archive_read_disk_uname(&a->archive,
- ae_id);
- }
-
- for (i = 0; i < (int)(sizeof(acl_inherit_map) /
- sizeof(acl_inherit_map[0])); ++i) {
- if ((ace->a_flags &
- acl_inherit_map[i].platform_inherit) != 0)
- ae_perm |=
- acl_inherit_map[i].archive_inherit;
- }
-
- for (i = 0; i < (int)(sizeof(acl_perm_map) /
- sizeof(acl_perm_map[0])); ++i) {
- if ((ace->a_access_mask &
- acl_perm_map[i].platform_perm) != 0)
- ae_perm |=
- acl_perm_map[i].archive_perm;
- }
- } else {
- aclent = &((aclent_t *)acl->acl_aclp)[e];
- if ((aclent->a_type & ACL_DEFAULT) != 0)
- entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT;
- else
- entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS;
- ae_id = aclent->a_id;
-
- switch(aclent->a_type) {
- case DEF_USER:
- case USER:
- ae_name = archive_read_disk_uname(&a->archive,
- ae_id);
- ae_tag = ARCHIVE_ENTRY_ACL_USER;
- break;
- case DEF_GROUP:
- case GROUP:
- ae_name = archive_read_disk_gname(&a->archive,
- ae_id);
- ae_tag = ARCHIVE_ENTRY_ACL_GROUP;
- break;
- case DEF_CLASS_OBJ:
- case CLASS_OBJ:
- ae_tag = ARCHIVE_ENTRY_ACL_MASK;
- break;
- case DEF_USER_OBJ:
- case USER_OBJ:
- ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
- break;
- case DEF_GROUP_OBJ:
- case GROUP_OBJ:
- ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
- break;
- case DEF_OTHER_OBJ:
- case OTHER_OBJ:
- ae_tag = ARCHIVE_ENTRY_ACL_OTHER;
- break;
- default:
- /* Unknown tag type, skip */
- continue;
- }
-
- if ((aclent->a_perm & 1) != 0)
- ae_perm |= ARCHIVE_ENTRY_ACL_EXECUTE;
- if ((aclent->a_perm & 2) != 0)
- ae_perm |= ARCHIVE_ENTRY_ACL_WRITE;
- if ((aclent->a_perm & 4) != 0)
- ae_perm |= ARCHIVE_ENTRY_ACL_READ;
- } /* default_entry_acl_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4 */
-
- archive_entry_acl_add_entry(entry, entry_acl_type,
- ae_perm, ae_tag, ae_id, ae_name);
- }
- return (ARCHIVE_OK);
-}
-#else /* !HAVE_SUN_ACL */
-/*
- * Translate POSIX.1e (Linux), FreeBSD (both POSIX.1e and NFSv4) and
- * MacOS (NFSv4 only) ACLs into libarchive internal structure
- */
-static int
-translate_acl(struct archive_read_disk *a,
- struct archive_entry *entry, acl_t acl, int default_entry_acl_type)
-{
- acl_tag_t acl_tag;
-#if HAVE_ACL_TYPE_NFS4
- acl_entry_type_t acl_type;
- int brand;
-#endif
-#if HAVE_ACL_TYPE_NFS4 || HAVE_DARWIN_ACL
- acl_flagset_t acl_flagset;
-#endif
- acl_entry_t acl_entry;
- acl_permset_t acl_permset;
- int i, entry_acl_type;
- int r, s, ae_id, ae_tag, ae_perm;
-#if !HAVE_DARWIN_ACL
- void *q;
-#endif
- const char *ae_name;
-
-#if HAVE_ACL_TYPE_NFS4
- // FreeBSD "brands" ACLs as POSIX.1e or NFSv4
- // Make sure the "brand" on this ACL is consistent
- // with the default_entry_acl_type bits provided.
- if (acl_get_brand_np(acl, &brand) != 0) {
- archive_set_error(&a->archive, errno,
- "Failed to read ACL brand");
- return (ARCHIVE_WARN);
- }
- switch (brand) {
- case ACL_BRAND_POSIX:
- switch (default_entry_acl_type) {
- case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
- case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
- break;
- default:
- archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
- "Invalid ACL entry type for POSIX.1e ACL");
- return (ARCHIVE_WARN);
- }
- break;
- case ACL_BRAND_NFS4:
- if (default_entry_acl_type & ~ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
- archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
- "Invalid ACL entry type for NFSv4 ACL");
- return (ARCHIVE_WARN);
- }
- break;
- default:
- archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
- "Unknown ACL brand");
- return (ARCHIVE_WARN);
- }
-#endif
-
- s = acl_get_entry(acl, ACL_FIRST_ENTRY, &acl_entry);
- if (s == -1) {
- archive_set_error(&a->archive, errno,
- "Failed to get first ACL entry");
- return (ARCHIVE_WARN);
- }
-
-#if HAVE_DARWIN_ACL
- while (s == 0)
-#else /* FreeBSD, Linux */
- while (s == 1)
-#endif
- {
- ae_id = -1;
- ae_name = NULL;
- ae_perm = 0;
-
- if (acl_get_tag_type(acl_entry, &acl_tag) != 0) {
- archive_set_error(&a->archive, errno,
- "Failed to get ACL tag type");
- return (ARCHIVE_WARN);
- }
- switch (acl_tag) {
-#if !HAVE_DARWIN_ACL /* FreeBSD, Linux */
- case ACL_USER:
- q = acl_get_qualifier(acl_entry);
- if (q != NULL) {
- ae_id = (int)*(uid_t *)q;
- acl_free(q);
- ae_name = archive_read_disk_uname(&a->archive,
- ae_id);
- }
- ae_tag = ARCHIVE_ENTRY_ACL_USER;
- break;
- case ACL_GROUP:
- q = acl_get_qualifier(acl_entry);
- if (q != NULL) {
- ae_id = (int)*(gid_t *)q;
- acl_free(q);
- ae_name = archive_read_disk_gname(&a->archive,
- ae_id);
- }
- ae_tag = ARCHIVE_ENTRY_ACL_GROUP;
- break;
- case ACL_MASK:
- ae_tag = ARCHIVE_ENTRY_ACL_MASK;
- break;
- case ACL_USER_OBJ:
- ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
- break;
- case ACL_GROUP_OBJ:
- ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
- break;
- case ACL_OTHER:
- ae_tag = ARCHIVE_ENTRY_ACL_OTHER;
- break;
-#if HAVE_ACL_TYPE_NFS4
- case ACL_EVERYONE:
- ae_tag = ARCHIVE_ENTRY_ACL_EVERYONE;
- break;
-#endif
-#else /* HAVE_DARWIN_ACL */
- case ACL_EXTENDED_ALLOW:
- entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW;
- r = translate_guid(&a->archive, acl_entry, &ae_id,
- &ae_tag, &ae_name);
- break;
- case ACL_EXTENDED_DENY:
- entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DENY;
- r = translate_guid(&a->archive, acl_entry, &ae_id,
- &ae_tag, &ae_name);
- break;
-#endif /* HAVE_DARWIN_ACL */
- default:
- /* Skip types that libarchive can't support. */
- s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry);
- continue;
- }
-
-#if HAVE_DARWIN_ACL
- /* Skip if translate_guid() above failed */
- if (r != 0) {
- s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry);
- continue;
- }
-#endif
-
-#if !HAVE_DARWIN_ACL
- // XXX acl_type maps to allow/deny/audit/YYYY bits
- entry_acl_type = default_entry_acl_type;
-#endif
-#if HAVE_ACL_TYPE_NFS4 || HAVE_DARWIN_ACL
- if (default_entry_acl_type & ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
-#if HAVE_ACL_TYPE_NFS4
- /*
- * acl_get_entry_type_np() fails with non-NFSv4 ACLs
- */
- if (acl_get_entry_type_np(acl_entry, &acl_type) != 0) {
- archive_set_error(&a->archive, errno, "Failed "
- "to get ACL type from a NFSv4 ACL entry");
- return (ARCHIVE_WARN);
- }
- switch (acl_type) {
- case ACL_ENTRY_TYPE_ALLOW:
- entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW;
- break;
- case ACL_ENTRY_TYPE_DENY:
- entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_DENY;
- break;
- case ACL_ENTRY_TYPE_AUDIT:
- entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT;
- break;
- case ACL_ENTRY_TYPE_ALARM:
- entry_acl_type = ARCHIVE_ENTRY_ACL_TYPE_ALARM;
- break;
- default:
- archive_set_error(&a->archive, errno,
- "Invalid NFSv4 ACL entry type");
- return (ARCHIVE_WARN);
- }
-#endif /* HAVE_ACL_TYPE_NFS4 */
-
- /*
- * Libarchive stores "flag" (NFSv4 inheritance bits)
- * in the ae_perm bitmap.
- *
- * acl_get_flagset_np() fails with non-NFSv4 ACLs
- */
- if (acl_get_flagset_np(acl_entry, &acl_flagset) != 0) {
- archive_set_error(&a->archive, errno,
- "Failed to get flagset from a NFSv4 ACL entry");
- return (ARCHIVE_WARN);
- }
- for (i = 0; i < (int)(sizeof(acl_inherit_map) / sizeof(acl_inherit_map[0])); ++i) {
- r = acl_get_flag_np(acl_flagset,
- acl_inherit_map[i].platform_inherit);
- if (r == -1) {
- archive_set_error(&a->archive, errno,
- "Failed to check flag in a NFSv4 "
- "ACL flagset");
- return (ARCHIVE_WARN);
- } else if (r)
- ae_perm |= acl_inherit_map[i].archive_inherit;
- }
- }
-#endif /* HAVE_ACL_TYPE_NFS4 || HAVE_DARWIN_ACL */
-
- if (acl_get_permset(acl_entry, &acl_permset) != 0) {
- archive_set_error(&a->archive, errno,
- "Failed to get ACL permission set");
- return (ARCHIVE_WARN);
- }
- for (i = 0; i < (int)(sizeof(acl_perm_map) / sizeof(acl_perm_map[0])); ++i) {
- /*
- * acl_get_perm() is spelled differently on different
- * platforms; see above.
- */
- r = ACL_GET_PERM(acl_permset, acl_perm_map[i].platform_perm);
- if (r == -1) {
- archive_set_error(&a->archive, errno,
- "Failed to check permission in an ACL permission set");
- return (ARCHIVE_WARN);
- } else if (r)
- ae_perm |= acl_perm_map[i].archive_perm;
- }
-
- archive_entry_acl_add_entry(entry, entry_acl_type,
- ae_perm, ae_tag,
- ae_id, ae_name);
-
- s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry);
-#if !HAVE_DARWIN_ACL
- if (s == -1) {
- archive_set_error(&a->archive, errno,
- "Failed to get next ACL entry");
- return (ARCHIVE_WARN);
- }
-#endif
- }
- return (ARCHIVE_OK);
-}
-#endif /* !HAVE_SUN_ACL */
-#else /* !HAVE_POSIX_ACL && !HAVE_NFS4_ACL */
-static int
-setup_acls(struct archive_read_disk *a,
- struct archive_entry *entry, int *fd)
-{
- (void)a; /* UNUSED */
- (void)entry; /* UNUSED */
- (void)fd; /* UNUSED */
- return (ARCHIVE_OK);
-}
-#endif /* !HAVE_POSIX_ACL && !HAVE_NFS4_ACL */
-
-#if (HAVE_FGETXATTR && HAVE_FLISTXATTR && HAVE_LISTXATTR && \
- HAVE_LLISTXATTR && HAVE_GETXATTR && HAVE_LGETXATTR) || \
- (HAVE_FGETEA && HAVE_FLISTEA && HAVE_LISTEA)
-
-/*
- * Linux and AIX extended attribute support.
+ * Linux, Darwin and AIX extended attribute support.
*
* TODO: By using a stack-allocated buffer for the first
* call to getxattr(), we might be able to avoid the second
@@ -1433,21 +444,32 @@ setup_xattr(struct archive_read_disk *a,
ssize_t size;
void *value = NULL;
-#if HAVE_FGETXATTR
- if (fd >= 0)
+
+ if (fd >= 0) {
+#if ARCHIVE_XATTR_LINUX
size = fgetxattr(fd, name, NULL, 0);
- else if (!a->follow_symlinks)
- size = lgetxattr(accpath, name, NULL, 0);
- else
- size = getxattr(accpath, name, NULL, 0);
-#elif HAVE_FGETEA
- if (fd >= 0)
+#elif ARCHIVE_XATTR_DARWIN
+ size = fgetxattr(fd, name, NULL, 0, 0, 0);
+#elif ARCHIVE_XATTR_AIX
size = fgetea(fd, name, NULL, 0);
- else if (!a->follow_symlinks)
+#endif
+ } else if (!a->follow_symlinks) {
+#if ARCHIVE_XATTR_LINUX
+ size = lgetxattr(accpath, name, NULL, 0);
+#elif ARCHIVE_XATTR_DARWIN
+ size = getxattr(accpath, name, NULL, 0, 0, XATTR_NOFOLLOW);
+#elif ARCHIVE_XATTR_AIX
size = lgetea(accpath, name, NULL, 0);
- else
+#endif
+ } else {
+#if ARCHIVE_XATTR_LINUX
+ size = getxattr(accpath, name, NULL, 0);
+#elif ARCHIVE_XATTR_DARWIN
+ size = getxattr(accpath, name, NULL, 0, 0, 0);
+#elif ARCHIVE_XATTR_AIX
size = getea(accpath, name, NULL, 0);
#endif
+ }
if (size == -1) {
archive_set_error(&a->archive, errno,
@@ -1460,21 +482,32 @@ setup_xattr(struct archive_read_disk *a,
return (ARCHIVE_FATAL);
}
-#if HAVE_FGETXATTR
- if (fd >= 0)
+
+ if (fd >= 0) {
+#if ARCHIVE_XATTR_LINUX
size = fgetxattr(fd, name, value, size);
- else if (!a->follow_symlinks)
- size = lgetxattr(accpath, name, value, size);
- else
- size = getxattr(accpath, name, value, size);
-#elif HAVE_FGETEA
- if (fd >= 0)
+#elif ARCHIVE_XATTR_DARWIN
+ size = fgetxattr(fd, name, value, size, 0, 0);
+#elif ARCHIVE_XATTR_AIX
size = fgetea(fd, name, value, size);
- else if (!a->follow_symlinks)
+#endif
+ } else if (!a->follow_symlinks) {
+#if ARCHIVE_XATTR_LINUX
+ size = lgetxattr(accpath, name, value, size);
+#elif ARCHIVE_XATTR_DARWIN
+ size = getxattr(accpath, name, value, size, 0, XATTR_NOFOLLOW);
+#elif ARCHIVE_XATTR_AIX
size = lgetea(accpath, name, value, size);
- else
+#endif
+ } else {
+#if ARCHIVE_XATTR_LINUX
+ size = getxattr(accpath, name, value, size);
+#elif ARCHIVE_XATTR_DARWIN
+ size = getxattr(accpath, name, value, size, 0, 0);
+#elif ARCHIVE_XATTR_AIX
size = getea(accpath, name, value, size);
#endif
+ }
if (size == -1) {
archive_set_error(&a->archive, errno,
@@ -1499,38 +532,36 @@ setup_xattrs(struct archive_read_disk *a,
path = NULL;
if (*fd < 0) {
- path = archive_entry_sourcepath(entry);
- if (path == NULL || (a->tree != NULL &&
- a->tree_enter_working_dir(a->tree) != 0))
- path = archive_entry_pathname(entry);
- if (path == NULL) {
- archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
- "Couldn't determine file path to read "
- "extended attributes");
+ path = archive_read_disk_entry_setup_path(a, entry, fd);
+ if (path == NULL)
return (ARCHIVE_WARN);
- }
- if (a->tree != NULL && (a->follow_symlinks ||
- archive_entry_filetype(entry) != AE_IFLNK)) {
- *fd = a->open_on_current_dir(a->tree,
- path, O_RDONLY | O_NONBLOCK);
- }
}
-#if HAVE_FLISTXATTR
- if (*fd >= 0)
+ if (*fd >= 0) {
+#if ARCHIVE_XATTR_LINUX
list_size = flistxattr(*fd, NULL, 0);
- else if (!a->follow_symlinks)
- list_size = llistxattr(path, NULL, 0);
- else
- list_size = listxattr(path, NULL, 0);
-#elif HAVE_FLISTEA
- if (*fd >= 0)
+#elif ARCHIVE_XATTR_DARWIN
+ list_size = flistxattr(*fd, NULL, 0, 0);
+#elif ARCHIVE_XATTR_AIX
list_size = flistea(*fd, NULL, 0);
- else if (!a->follow_symlinks)
+#endif
+ } else if (!a->follow_symlinks) {
+#if ARCHIVE_XATTR_LINUX
+ list_size = llistxattr(path, NULL, 0);
+#elif ARCHIVE_XATTR_DARWIN
+ list_size = listxattr(path, NULL, 0, XATTR_NOFOLLOW);
+#elif ARCHIVE_XATTR_AIX
list_size = llistea(path, NULL, 0);
- else
+#endif
+ } else {
+#if ARCHIVE_XATTR_LINUX
+ list_size = listxattr(path, NULL, 0);
+#elif ARCHIVE_XATTR_DARWIN
+ list_size = listxattr(path, NULL, 0, 0);
+#elif ARCHIVE_XATTR_AIX
list_size = listea(path, NULL, 0);
#endif
+ }
if (list_size == -1) {
if (errno == ENOTSUP || errno == ENOSYS)
@@ -1548,21 +579,31 @@ setup_xattrs(struct archive_read_disk *a,
return (ARCHIVE_FATAL);
}
-#if HAVE_FLISTXATTR
- if (*fd >= 0)
+ if (*fd >= 0) {
+#if ARCHIVE_XATTR_LINUX
list_size = flistxattr(*fd, list, list_size);
- else if (!a->follow_symlinks)
- list_size = llistxattr(path, list, list_size);
- else
- list_size = listxattr(path, list, list_size);
-#elif HAVE_FLISTEA
- if (*fd >= 0)
+#elif ARCHIVE_XATTR_DARWIN
+ list_size = flistxattr(*fd, list, list_size, 0);
+#elif ARCHIVE_XATTR_AIX
list_size = flistea(*fd, list, list_size);
- else if (!a->follow_symlinks)
+#endif
+ } else if (!a->follow_symlinks) {
+#if ARCHIVE_XATTR_LINUX
+ list_size = llistxattr(path, list, list_size);
+#elif ARCHIVE_XATTR_DARWIN
+ list_size = listxattr(path, list, list_size, XATTR_NOFOLLOW);
+#elif ARCHIVE_XATTR_AIX
list_size = llistea(path, list, list_size);
- else
+#endif
+ } else {
+#if ARCHIVE_XATTR_LINUX
+ list_size = listxattr(path, list, list_size);
+#elif ARCHIVE_XATTR_DARWIN
+ list_size = listxattr(path, list, list_size, 0);
+#elif ARCHIVE_XATTR_AIX
list_size = listea(path, list, list_size);
#endif
+ }
if (list_size == -1) {
archive_set_error(&a->archive, errno,
@@ -1572,9 +613,21 @@ setup_xattrs(struct archive_read_disk *a,
}
for (p = list; (p - list) < list_size; p += strlen(p) + 1) {
- if (strncmp(p, "system.", 7) == 0 ||
- strncmp(p, "xfsroot.", 8) == 0)
+#if ARCHIVE_XATTR_LINUX
+ /* Linux: skip POSIX.1e ACL extended attributes */
+ if (strncmp(p, "system.", 7) == 0 &&
+ (strcmp(p + 7, "posix_acl_access") == 0 ||
+ strcmp(p + 7, "posix_acl_default") == 0))
+ continue;
+ if (strncmp(p, "trusted.SGI_", 12) == 0 &&
+ (strcmp(p + 12, "ACL_DEFAULT") == 0 ||
+ strcmp(p + 12, "ACL_FILE") == 0))
+ continue;
+
+ /* Linux: xfsroot namespace is obsolete and unsupported */
+ if (strncmp(p, "xfsroot.", 8) == 0)
continue;
+#endif
setup_xattr(a, entry, p, *fd, path);
}
@@ -1582,8 +635,7 @@ setup_xattrs(struct archive_read_disk *a,
return (ARCHIVE_OK);
}
-#elif HAVE_EXTATTR_GET_FILE && HAVE_EXTATTR_LIST_FILE && \
- HAVE_DECL_EXTATTR_NAMESPACE_USER
+#elif ARCHIVE_XATTR_FREEBSD
/*
* FreeBSD extattr interface.
@@ -1658,21 +710,9 @@ setup_xattrs(struct archive_read_disk *a,
path = NULL;
if (*fd < 0) {
- path = archive_entry_sourcepath(entry);
- if (path == NULL || (a->tree != NULL &&
- a->tree_enter_working_dir(a->tree) != 0))
- path = archive_entry_pathname(entry);
- if (path == NULL) {
- archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
- "Couldn't determine file path to read "
- "extended attributes");
+ path = archive_read_disk_entry_setup_path(a, entry, fd);
+ if (path == NULL)
return (ARCHIVE_WARN);
- }
- if (a->tree != NULL && (a->follow_symlinks ||
- archive_entry_filetype(entry) != AE_IFLNK)) {
- *fd = a->open_on_current_dir(a->tree,
- path, O_RDONLY | O_NONBLOCK);
- }
}
if (*fd >= 0)
@@ -1773,6 +813,7 @@ setup_sparse_fiemap(struct archive_read_disk *a,
int64_t size;
int count, do_fiemap, iters;
int exit_sts = ARCHIVE_OK;
+ const char *path;
if (archive_entry_filetype(entry) != AE_IFREG
|| archive_entry_size(entry) <= 0
@@ -1780,11 +821,10 @@ setup_sparse_fiemap(struct archive_read_disk *a,
return (ARCHIVE_OK);
if (*fd < 0) {
- const char *path;
-
- path = archive_entry_sourcepath(entry);
+ path = archive_read_disk_entry_setup_path(a, entry, NULL);
if (path == NULL)
- path = archive_entry_pathname(entry);
+ return (ARCHIVE_FAILED);
+
if (a->tree != NULL)
*fd = a->open_on_current_dir(a->tree, path,
O_RDONLY | O_NONBLOCK | O_CLOEXEC);
@@ -1880,6 +920,7 @@ setup_sparse(struct archive_read_disk *a,
off_t off_s, off_e;
int exit_sts = ARCHIVE_OK;
int check_fully_sparse = 0;
+ const char *path;
if (archive_entry_filetype(entry) != AE_IFREG
|| archive_entry_size(entry) <= 0
@@ -1887,20 +928,10 @@ setup_sparse(struct archive_read_disk *a,
return (ARCHIVE_OK);
/* Does filesystem support the reporting of hole ? */
- if (*fd < 0 && a->tree != NULL) {
- const char *path;
-
- path = archive_entry_sourcepath(entry);
- if (path == NULL)
- path = archive_entry_pathname(entry);
- *fd = a->open_on_current_dir(a->tree, path,
- O_RDONLY | O_NONBLOCK);
- if (*fd < 0) {
- archive_set_error(&a->archive, errno,
- "Can't open `%s'", path);
- return (ARCHIVE_FAILED);
- }
- }
+ if (*fd < 0)
+ path = archive_read_disk_entry_setup_path(a, entry, fd);
+ else
+ path = NULL;
if (*fd >= 0) {
#ifdef _PC_MIN_HOLE_SIZE
@@ -1911,12 +942,8 @@ setup_sparse(struct archive_read_disk *a,
if (initial_off != 0)
lseek(*fd, 0, SEEK_SET);
} else {
- const char *path;
-
- path = archive_entry_sourcepath(entry);
if (path == NULL)
- path = archive_entry_pathname(entry);
-
+ return (ARCHIVE_FAILED);
#ifdef _PC_MIN_HOLE_SIZE
if (pathconf(path, _PC_MIN_HOLE_SIZE) <= 0)
return (ARCHIVE_OK);
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_disk_private.h b/Utilities/cmlibarchive/libarchive/archive_read_disk_private.h
index b5a8328b7..f03a0a9cc 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_disk_private.h
+++ b/Utilities/cmlibarchive/libarchive/archive_read_disk_private.h
@@ -33,6 +33,8 @@
#ifndef ARCHIVE_READ_DISK_PRIVATE_H_INCLUDED
#define ARCHIVE_READ_DISK_PRIVATE_H_INCLUDED
+#include "archive_platform_acl.h"
+
struct tree;
struct archive_entry;
@@ -86,4 +88,11 @@ struct archive_read_disk {
void *excluded_cb_data;
};
+const char *
+archive_read_disk_entry_setup_path(struct archive_read_disk *,
+ struct archive_entry *, int *);
+
+int
+archive_read_disk_entry_setup_acls(struct archive_read_disk *,
+ struct archive_entry *, int *);
#endif
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_format.3 b/Utilities/cmlibarchive/libarchive/archive_read_format.3
index 53b9a7e0e..91c5d2cfd 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_format.3
+++ b/Utilities/cmlibarchive/libarchive/archive_read_format.3
@@ -37,9 +37,9 @@
.Nm archive_read_support_format_empty ,
.Nm archive_read_support_format_iso9660 ,
.Nm archive_read_support_format_lha ,
-.Nm archive_read_support_format_mtree,
-.Nm archive_read_support_format_rar,
-.Nm archive_read_support_format_raw,
+.Nm archive_read_support_format_mtree ,
+.Nm archive_read_support_format_rar ,
+.Nm archive_read_support_format_raw ,
.Nm archive_read_support_format_tar ,
.Nm archive_read_support_format_xar ,
.Nm archive_read_support_format_zip
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_open.3 b/Utilities/cmlibarchive/libarchive/archive_read_open.3
index 4d8272cac..2278ebc33 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_open.3
+++ b/Utilities/cmlibarchive/libarchive/archive_read_open.3
@@ -33,7 +33,7 @@
.Nm archive_read_open_fd ,
.Nm archive_read_open_FILE ,
.Nm archive_read_open_filename ,
-.Nm archive_read_open_memory ,
+.Nm archive_read_open_memory
.Nd functions for reading streaming archives
.Sh LIBRARY
Streaming Archive Library (libarchive, -larchive)
@@ -67,7 +67,7 @@ Streaming Archive Library (libarchive, -larchive)
.Fa "size_t block_size"
.Fc
.Ft int
-.Fn archive_read_open_memory "struct archive *" "void *buff" "size_t size"
+.Fn archive_read_open_memory "struct archive *" "const void *buff" "size_t size"
.Sh DESCRIPTION
.Bl -tag -compact -width indent
.It Fn archive_read_open
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_filter_lz4.c b/Utilities/cmlibarchive/libarchive/archive_read_support_filter_lz4.c
index 663e2d3d6..147f5027f 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_filter_lz4.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_filter_lz4.c
@@ -494,7 +494,7 @@ lz4_filter_read_data_block(struct archive_read_filter *self, const void **p)
if (read_buf == NULL)
goto truncated_error;
compressed_size = archive_le32dec(read_buf);
- if ((compressed_size & ~(1 << 31)) > state->flags.block_maximum_size)
+ if ((compressed_size & 0x7fffffff) > state->flags.block_maximum_size)
goto malformed_error;
/* A compressed size == 0 means the end of stream blocks. */
if (compressed_size == 0) {
@@ -504,8 +504,8 @@ lz4_filter_read_data_block(struct archive_read_filter *self, const void **p)
checksum_size = state->flags.block_checksum;
/* Check if the block is uncompressed. */
- if (compressed_size & (1 << 31)) {
- compressed_size &= ~(1 << 31);
+ if (compressed_size & 0x80000000U) {
+ compressed_size &= 0x7fffffff;
uncompressed_size = compressed_size;
} else
uncompressed_size = 0;/* Unknown yet. */
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_cab.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_cab.c
index 20eb157f2..51f79fa6b 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_cab.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_cab.c
@@ -116,19 +116,11 @@ struct lzx_dec {
* coding tree, which is a binary tree. But a use of a large
* index table causes L1 cache read miss many times.
*/
-#define HTBL_BITS 10
int max_bits;
- int shift_bits;
int tbl_bits;
int tree_used;
- int tree_avail;
/* Direct access table. */
uint16_t *tbl;
- /* Binary tree table for extra bits over the direct access. */
- struct htree_t {
- uint16_t left;
- uint16_t right;
- } *tree;
} at, lt, mt, pt;
int loop;
@@ -187,7 +179,7 @@ struct lzx_stream {
#define CFDATA_cbData 4
#define CFDATA_cbUncomp 6
-static const char *compression_name[] = {
+static const char * const compression_name[] = {
"NONE",
"MSZIP",
"Quantum",
@@ -352,7 +344,6 @@ static int lzx_huffman_init(struct huffman *, size_t, int);
static void lzx_huffman_free(struct huffman *);
static int lzx_make_huffman_table(struct huffman *);
static inline int lzx_decode_huffman(struct huffman *, unsigned);
-static int lzx_decode_huffman_tree(struct huffman *, unsigned, int);
int
@@ -3127,7 +3118,6 @@ getdata:
static int
lzx_huffman_init(struct huffman *hf, size_t len_size, int tbl_bits)
{
- int bits;
if (hf->bitlen == NULL || hf->len_size != (int)len_size) {
free(hf->bitlen);
@@ -3138,21 +3128,11 @@ lzx_huffman_init(struct huffman *hf, size_t len_size, int tbl_bits)
} else
memset(hf->bitlen, 0, len_size * sizeof(hf->bitlen[0]));
if (hf->tbl == NULL) {
- if (tbl_bits < HTBL_BITS)
- bits = tbl_bits;
- else
- bits = HTBL_BITS;
- hf->tbl = malloc(((size_t)1 << bits) * sizeof(hf->tbl[0]));
+ hf->tbl = malloc(((size_t)1 << tbl_bits) * sizeof(hf->tbl[0]));
if (hf->tbl == NULL)
return (ARCHIVE_FATAL);
hf->tbl_bits = tbl_bits;
}
- if (hf->tree == NULL && tbl_bits > HTBL_BITS) {
- hf->tree_avail = 1 << (tbl_bits - HTBL_BITS + 4);
- hf->tree = malloc(hf->tree_avail * sizeof(hf->tree[0]));
- if (hf->tree == NULL)
- return (ARCHIVE_FATAL);
- }
return (ARCHIVE_OK);
}
@@ -3161,7 +3141,6 @@ lzx_huffman_free(struct huffman *hf)
{
free(hf->bitlen);
free(hf->tbl);
- free(hf->tree);
}
/*
@@ -3174,7 +3153,7 @@ lzx_make_huffman_table(struct huffman *hf)
const unsigned char *bitlen;
int bitptn[17], weight[17];
int i, maxbits = 0, ptn, tbl_size, w;
- int diffbits, len_avail;
+ int len_avail;
/*
* Initialize bit patterns.
@@ -3205,28 +3184,11 @@ lzx_make_huffman_table(struct huffman *hf)
weight[i] >>= ebits;
}
}
- if (maxbits > HTBL_BITS) {
- int htbl_max;
- uint16_t *p;
-
- diffbits = maxbits - HTBL_BITS;
- for (i = 1; i <= HTBL_BITS; i++) {
- bitptn[i] >>= diffbits;
- weight[i] >>= diffbits;
- }
- htbl_max = bitptn[HTBL_BITS] +
- weight[HTBL_BITS] * hf->freq[HTBL_BITS];
- p = &(hf->tbl[htbl_max]);
- while (p < &hf->tbl[1U<<HTBL_BITS])
- *p++ = 0;
- } else
- diffbits = 0;
- hf->shift_bits = diffbits;
/*
* Make the table.
*/
- tbl_size = 1 << HTBL_BITS;
+ tbl_size = 1 << hf->tbl_bits;
tbl = hf->tbl;
bitlen = hf->bitlen;
len_avail = hf->len_size;
@@ -3234,120 +3196,32 @@ lzx_make_huffman_table(struct huffman *hf)
for (i = 0; i < len_avail; i++) {
uint16_t *p;
int len, cnt;
- uint16_t bit;
- int extlen;
- struct htree_t *ht;
if (bitlen[i] == 0)
continue;
/* Get a bit pattern */
len = bitlen[i];
+ if (len > tbl_size)
+ return (0);
ptn = bitptn[len];
cnt = weight[len];
- if (len <= HTBL_BITS) {
- /* Calculate next bit pattern */
- if ((bitptn[len] = ptn + cnt) > tbl_size)
- return (0);/* Invalid */
- /* Update the table */
- p = &(tbl[ptn]);
- while (--cnt >= 0)
- p[cnt] = (uint16_t)i;
- continue;
- }
-
- /*
- * A bit length is too big to be housed to a direct table,
- * so we use a tree model for its extra bits.
- */
- bitptn[len] = ptn + cnt;
- bit = 1U << (diffbits -1);
- extlen = len - HTBL_BITS;
-
- p = &(tbl[ptn >> diffbits]);
- if (*p == 0) {
- *p = len_avail + hf->tree_used;
- ht = &(hf->tree[hf->tree_used++]);
- if (hf->tree_used > hf->tree_avail)
- return (0);/* Invalid */
- ht->left = 0;
- ht->right = 0;
- } else {
- if (*p < len_avail ||
- *p >= (len_avail + hf->tree_used))
- return (0);/* Invalid */
- ht = &(hf->tree[*p - len_avail]);
- }
- while (--extlen > 0) {
- if (ptn & bit) {
- if (ht->left < len_avail) {
- ht->left = len_avail + hf->tree_used;
- ht = &(hf->tree[hf->tree_used++]);
- if (hf->tree_used > hf->tree_avail)
- return (0);/* Invalid */
- ht->left = 0;
- ht->right = 0;
- } else {
- ht = &(hf->tree[ht->left - len_avail]);
- }
- } else {
- if (ht->right < len_avail) {
- ht->right = len_avail + hf->tree_used;
- ht = &(hf->tree[hf->tree_used++]);
- if (hf->tree_used > hf->tree_avail)
- return (0);/* Invalid */
- ht->left = 0;
- ht->right = 0;
- } else {
- ht = &(hf->tree[ht->right - len_avail]);
- }
- }
- bit >>= 1;
- }
- if (ptn & bit) {
- if (ht->left != 0)
- return (0);/* Invalid */
- ht->left = (uint16_t)i;
- } else {
- if (ht->right != 0)
- return (0);/* Invalid */
- ht->right = (uint16_t)i;
- }
+ /* Calculate next bit pattern */
+ if ((bitptn[len] = ptn + cnt) > tbl_size)
+ return (0);/* Invalid */
+ /* Update the table */
+ p = &(tbl[ptn]);
+ while (--cnt >= 0)
+ p[cnt] = (uint16_t)i;
}
return (1);
}
-static int
-lzx_decode_huffman_tree(struct huffman *hf, unsigned rbits, int c)
-{
- struct htree_t *ht;
- int extlen;
-
- ht = hf->tree;
- extlen = hf->shift_bits;
- while (c >= hf->len_size) {
- c -= hf->len_size;
- if (extlen-- <= 0 || c >= hf->tree_used)
- return (0);
- if (rbits & (1U << extlen))
- c = ht[c].left;
- else
- c = ht[c].right;
- }
- return (c);
-}
-
static inline int
lzx_decode_huffman(struct huffman *hf, unsigned rbits)
{
int c;
- /*
- * At first search an index table for a bit pattern.
- * If it fails, search a huffman tree for.
- */
- c = hf->tbl[rbits >> hf->shift_bits];
+ c = hf->tbl[rbits];
if (c < hf->len_size)
return (c);
- /* This bit pattern needs to be found out at a huffman tree. */
- return (lzx_decode_huffman_tree(hf, rbits, c));
+ return (0);
}
-
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_cpio.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_cpio.c
index ffd4a8580..ad9f782de 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_cpio.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_cpio.c
@@ -165,7 +165,7 @@ __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_cpio.c 20116
struct links_entry {
struct links_entry *next;
struct links_entry *previous;
- int links;
+ unsigned int links;
dev_t dev;
int64_t ino;
char *name;
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_iso9660.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_iso9660.c
index 354133005..4b436d1c4 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_iso9660.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_iso9660.c
@@ -3021,8 +3021,9 @@ heap_add_entry(struct archive_read *a, struct heap_queue *heap,
ENOMEM, "Out of memory");
return (ARCHIVE_FATAL);
}
- memcpy(new_pending_files, heap->files,
- heap->allocated * sizeof(new_pending_files[0]));
+ if (heap->allocated)
+ memcpy(new_pending_files, heap->files,
+ heap->allocated * sizeof(new_pending_files[0]));
if (heap->files != NULL)
free(heap->files);
heap->files = new_pending_files;
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_lha.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_lha.c
index ebd7f2ccb..1995e9c66 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_lha.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_lha.c
@@ -2480,7 +2480,7 @@ lzh_huffman_free(struct huffman *hf)
free(hf->tree);
}
-static char bitlen_tbl[0x400] = {
+static const char bitlen_tbl[0x400] = {
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_mtree.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_mtree.c
index 4231ff500..44b6083cb 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_mtree.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_mtree.c
@@ -130,9 +130,7 @@ static ssize_t readline(struct archive_read *, struct mtree *, char **, ssize_t)
static int skip(struct archive_read *a);
static int read_header(struct archive_read *,
struct archive_entry *);
-static int64_t mtree_atol10(char **);
-static int64_t mtree_atol8(char **);
-static int64_t mtree_atol(char **);
+static int64_t mtree_atol(char **, int base);
/*
* There's no standard for TIME_T_MAX/TIME_T_MIN. So we compute them
@@ -399,41 +397,41 @@ bid_keycmp(const char *p, const char *key, ssize_t len)
static int
bid_keyword(const char *p, ssize_t len)
{
- static const char *keys_c[] = {
+ static const char * const keys_c[] = {
"content", "contents", "cksum", NULL
};
- static const char *keys_df[] = {
+ static const char * const keys_df[] = {
"device", "flags", NULL
};
- static const char *keys_g[] = {
+ static const char * const keys_g[] = {
"gid", "gname", NULL
};
- static const char *keys_il[] = {
+ static const char * const keys_il[] = {
"ignore", "inode", "link", NULL
};
- static const char *keys_m[] = {
+ static const char * const keys_m[] = {
"md5", "md5digest", "mode", NULL
};
- static const char *keys_no[] = {
+ static const char * const keys_no[] = {
"nlink", "nochange", "optional", NULL
};
- static const char *keys_r[] = {
+ static const char * const keys_r[] = {
"resdevice", "rmd160", "rmd160digest", NULL
};
- static const char *keys_s[] = {
+ static const char * const keys_s[] = {
"sha1", "sha1digest",
"sha256", "sha256digest",
"sha384", "sha384digest",
"sha512", "sha512digest",
"size", NULL
};
- static const char *keys_t[] = {
+ static const char * const keys_t[] = {
"tags", "time", "type", NULL
};
- static const char *keys_u[] = {
+ static const char * const keys_u[] = {
"uid", "uname", NULL
};
- const char **keys;
+ const char * const *keys;
int i;
switch (*p) {
@@ -1418,7 +1416,7 @@ parse_device(dev_t *pdev, struct archive *a, char *val)
"Too many arguments");
return ARCHIVE_WARN;
}
- numbers[argc++] = (unsigned long)mtree_atol(&p);
+ numbers[argc++] = (unsigned long)mtree_atol(&p, 0);
}
if (argc < 2) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
@@ -1433,7 +1431,7 @@ parse_device(dev_t *pdev, struct archive *a, char *val)
}
} else {
/* file system raw value. */
- result = (dev_t)mtree_atol(&val);
+ result = (dev_t)mtree_atol(&val, 0);
}
*pdev = result;
return ARCHIVE_OK;
@@ -1513,7 +1511,7 @@ parse_keyword(struct archive_read *a, struct mtree *mtree,
case 'g':
if (strcmp(key, "gid") == 0) {
*parsed_kws |= MTREE_HAS_GID;
- archive_entry_set_gid(entry, mtree_atol10(&val));
+ archive_entry_set_gid(entry, mtree_atol(&val, 10));
break;
}
if (strcmp(key, "gname") == 0) {
@@ -1523,7 +1521,7 @@ parse_keyword(struct archive_read *a, struct mtree *mtree,
}
case 'i':
if (strcmp(key, "inode") == 0) {
- archive_entry_set_ino(entry, mtree_atol10(&val));
+ archive_entry_set_ino(entry, mtree_atol(&val, 10));
break;
}
case 'l':
@@ -1535,14 +1533,14 @@ parse_keyword(struct archive_read *a, struct mtree *mtree,
if (strcmp(key, "md5") == 0 || strcmp(key, "md5digest") == 0)
break;
if (strcmp(key, "mode") == 0) {
- if (val[0] >= '0' && val[0] <= '9') {
+ if (val[0] >= '0' && val[0] <= '7') {
*parsed_kws |= MTREE_HAS_PERM;
archive_entry_set_perm(entry,
- (mode_t)mtree_atol8(&val));
+ (mode_t)mtree_atol(&val, 8));
} else {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
- "Symbolic mode \"%s\" unsupported", val);
+ "Symbolic or non-octal mode \"%s\" unsupported", val);
return ARCHIVE_WARN;
}
break;
@@ -1551,7 +1549,7 @@ parse_keyword(struct archive_read *a, struct mtree *mtree,
if (strcmp(key, "nlink") == 0) {
*parsed_kws |= MTREE_HAS_NLINK;
archive_entry_set_nlink(entry,
- (unsigned int)mtree_atol10(&val));
+ (unsigned int)mtree_atol(&val, 10));
break;
}
case 'r':
@@ -1582,7 +1580,7 @@ parse_keyword(struct archive_read *a, struct mtree *mtree,
strcmp(key, "sha512digest") == 0)
break;
if (strcmp(key, "size") == 0) {
- archive_entry_set_size(entry, mtree_atol10(&val));
+ archive_entry_set_size(entry, mtree_atol(&val, 10));
break;
}
case 't':
@@ -1601,13 +1599,13 @@ parse_keyword(struct archive_read *a, struct mtree *mtree,
long ns = 0;
*parsed_kws |= MTREE_HAS_MTIME;
- m = mtree_atol10(&val);
+ m = mtree_atol(&val, 10);
/* Replicate an old mtree bug:
* 123456789.1 represents 123456789
* seconds and 1 nanosecond. */
if (*val == '.') {
++val;
- ns = (long)mtree_atol10(&val);
+ ns = (long)mtree_atol(&val, 10);
if (ns < 0)
ns = 0;
else if (ns > 999999999)
@@ -1670,7 +1668,7 @@ parse_keyword(struct archive_read *a, struct mtree *mtree,
case 'u':
if (strcmp(key, "uid") == 0) {
*parsed_kws |= MTREE_HAS_UID;
- archive_entry_set_uid(entry, mtree_atol10(&val));
+ archive_entry_set_uid(entry, mtree_atol(&val, 10));
break;
}
if (strcmp(key, "uname") == 0) {
@@ -1825,72 +1823,9 @@ parse_escapes(char *src, struct mtree_entry *mentry)
*dest = '\0';
}
-/*
- * Note that this implementation does not (and should not!) obey
- * locale settings; you cannot simply substitute strtol here, since
- * it does obey locale.
- */
-static int64_t
-mtree_atol8(char **p)
-{
- int64_t l, limit, last_digit_limit;
- int digit, base;
-
- base = 8;
- limit = INT64_MAX / base;
- last_digit_limit = INT64_MAX % base;
-
- l = 0;
- digit = **p - '0';
- while (digit >= 0 && digit < base) {
- if (l>limit || (l == limit && digit > last_digit_limit)) {
- l = INT64_MAX; /* Truncate on overflow. */
- break;
- }
- l = (l * base) + digit;
- digit = *++(*p) - '0';
- }
- return (l);
-}
-
-/*
- * Note that this implementation does not (and should not!) obey
- * locale settings; you cannot simply substitute strtol here, since
- * it does obey locale.
- */
-static int64_t
-mtree_atol10(char **p)
-{
- int64_t l, limit, last_digit_limit;
- int base, digit, sign;
-
- base = 10;
-
- if (**p == '-') {
- sign = -1;
- limit = ((uint64_t)(INT64_MAX) + 1) / base;
- last_digit_limit = ((uint64_t)(INT64_MAX) + 1) % base;
- ++(*p);
- } else {
- sign = 1;
- limit = INT64_MAX / base;
- last_digit_limit = INT64_MAX % base;
- }
-
- l = 0;
- digit = **p - '0';
- while (digit >= 0 && digit < base) {
- if (l > limit || (l == limit && digit > last_digit_limit))
- return (sign < 0) ? INT64_MIN : INT64_MAX;
- l = (l * base) + digit;
- digit = *++(*p) - '0';
- }
- return (sign < 0) ? -l : l;
-}
-
/* Parse a hex digit. */
static int
-parsehex(char c)
+parsedigit(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
@@ -1908,45 +1843,50 @@ parsehex(char c)
* it does obey locale.
*/
static int64_t
-mtree_atol16(char **p)
+mtree_atol(char **p, int base)
{
- int64_t l, limit, last_digit_limit;
- int base, digit, sign;
-
- base = 16;
+ int64_t l, limit;
+ int digit, last_digit_limit;
+
+ if (base == 0) {
+ if (**p != '0')
+ base = 10;
+ else if ((*p)[1] == 'x' || (*p)[1] == 'X') {
+ *p += 2;
+ base = 16;
+ } else {
+ base = 8;
+ }
+ }
if (**p == '-') {
- sign = -1;
- limit = ((uint64_t)(INT64_MAX) + 1) / base;
- last_digit_limit = ((uint64_t)(INT64_MAX) + 1) % base;
+ limit = INT64_MIN / base;
+ last_digit_limit = INT64_MIN % base;
++(*p);
+
+ l = 0;
+ digit = parsedigit(**p);
+ while (digit >= 0 && digit < base) {
+ if (l < limit || (l == limit && digit > last_digit_limit))
+ return INT64_MIN;
+ l = (l * base) - digit;
+ digit = parsedigit(*++(*p));
+ }
+ return l;
} else {
- sign = 1;
limit = INT64_MAX / base;
last_digit_limit = INT64_MAX % base;
- }
- l = 0;
- digit = parsehex(**p);
- while (digit >= 0 && digit < base) {
- if (l > limit || (l == limit && digit > last_digit_limit))
- return (sign < 0) ? INT64_MIN : INT64_MAX;
- l = (l * base) + digit;
- digit = parsehex(*++(*p));
- }
- return (sign < 0) ? -l : l;
-}
-
-static int64_t
-mtree_atol(char **p)
-{
- if (**p != '0')
- return mtree_atol10(p);
- if ((*p)[1] == 'x' || (*p)[1] == 'X') {
- *p += 2;
- return mtree_atol16(p);
+ l = 0;
+ digit = parsedigit(**p);
+ while (digit >= 0 && digit < base) {
+ if (l > limit || (l == limit && digit > last_digit_limit))
+ return INT64_MAX;
+ l = (l * base) + digit;
+ digit = parsedigit(*++(*p));
+ }
+ return l;
}
- return mtree_atol8(p);
}
/*
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c
index 658d49d50..a0e641e35 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c
@@ -1750,7 +1750,7 @@ read_exttime(const char *p, struct rar *rar, const char *endp)
return (-1);
for (j = 0; j < count; j++)
{
- rem = ((*p) << 16) | (rem >> 8);
+ rem = (((unsigned)(unsigned char)*p) << 16) | (rem >> 8);
p++;
}
tm = localtime(&t);
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_tar.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_tar.c
index bd7f13d52..30d5bc83c 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_tar.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_tar.c
@@ -155,6 +155,7 @@ struct tar {
int compat_2x;
int process_mac_extensions;
int read_concatenated_archives;
+ int realsize_override;
};
static int archive_block_is_null(const char *p);
@@ -527,6 +528,7 @@ archive_read_format_tar_read_header(struct archive_read *a,
tar->entry_offset = 0;
gnu_clear_sparse_list(tar);
tar->realsize = -1; /* Mark this as "unset" */
+ tar->realsize_override = 0;
/* Setup default string conversion. */
tar->sconv = tar->opt_sconv;
@@ -1894,6 +1896,7 @@ pax_attribute(struct archive_read *a, struct tar *tar,
if (strcmp(key, "GNU.sparse.size") == 0) {
tar->realsize = tar_atol10(value, strlen(value));
archive_entry_set_size(entry, tar->realsize);
+ tar->realsize_override = 1;
}
/* GNU "0.1" sparse pax format. */
@@ -1925,6 +1928,7 @@ pax_attribute(struct archive_read *a, struct tar *tar,
if (strcmp(key, "GNU.sparse.realsize") == 0) {
tar->realsize = tar_atol10(value, strlen(value));
archive_entry_set_size(entry, tar->realsize);
+ tar->realsize_override = 1;
}
break;
case 'L':
@@ -1977,6 +1981,7 @@ pax_attribute(struct archive_read *a, struct tar *tar,
tar_atol10(value, strlen(value)));
} else if (strcmp(key, "SCHILY.realsize") == 0) {
tar->realsize = tar_atol10(value, strlen(value));
+ tar->realsize_override = 1;
archive_entry_set_size(entry, tar->realsize);
} else if (strncmp(key, "SCHILY.xattr.", 13) == 0) {
pax_attribute_schily_xattr(entry, key, value,
@@ -2055,14 +2060,12 @@ pax_attribute(struct archive_read *a, struct tar *tar,
tar->entry_bytes_remaining
= tar_atol10(value, strlen(value));
/*
- * But, "size" is not necessarily the size of
- * the file on disk; if this is a sparse file,
- * the disk size may have already been set from
- * GNU.sparse.realsize or GNU.sparse.size or
- * an old GNU header field or SCHILY.realsize
- * or ....
+ * The "size" pax header keyword always overrides the
+ * "size" field in the tar header.
+ * GNU.sparse.realsize, GNU.sparse.size and
+ * SCHILY.realsize override this value.
*/
- if (tar->realsize < 0) {
+ if (!tar->realsize_override) {
archive_entry_set_size(entry,
tar->entry_bytes_remaining);
tar->realsize
@@ -2206,6 +2209,7 @@ header_gnutar(struct archive_read *a, struct tar *tar,
tar->realsize
= tar_atol(header->realsize, sizeof(header->realsize));
archive_entry_set_size(entry, tar->realsize);
+ tar->realsize_override = 1;
}
if (header->sparse[0].offset[0] != 0) {
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_warc.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_warc.c
index b16246514..e8753853f 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_warc.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_warc.c
@@ -600,9 +600,10 @@ _warc_rdver(const char *buf, size_t bsz)
/* looks good so far, read the version number for a laugh */
buf += sizeof(magic) - 1U;
- if (isdigit(buf[0U]) && (buf[1U] == '.') && isdigit(buf[2U])) {
+ if (isdigit((unsigned char)buf[0U]) && (buf[1U] == '.') &&
+ isdigit((unsigned char)buf[2U])) {
/* we support a maximum of 2 digits in the minor version */
- if (isdigit(buf[3U]))
+ if (isdigit((unsigned char)buf[3U]))
end = 1U;
/* set up major version */
ver = (buf[0U] - '0') * 10000U;
@@ -686,7 +687,7 @@ _warc_rduri(const char *buf, size_t bsz)
/* spaces inside uri are not allowed, CRLF should follow */
for (p = val; p < eol; p++) {
- if (isspace(*p))
+ if (isspace((unsigned char)*p))
return res;
}
@@ -736,7 +737,7 @@ _warc_rdlen(const char *buf, size_t bsz)
while (val < eol && (*val == ' ' || *val == '\t'))
val++;
/* there must be at least one digit */
- if (!isdigit(*val))
+ if (!isdigit((unsigned char)*val))
return -1;
len = strtol(val, &on, 10);
if (on != eol) {
diff --git a/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c b/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c
index e56bd63ac..ddd445833 100644
--- a/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c
+++ b/Utilities/cmlibarchive/libarchive/archive_read_support_format_zip.c
@@ -347,7 +347,7 @@ fake_crc32(unsigned long crc, const void *buff, size_t len)
return 0;
}
-static struct {
+static const struct {
int id;
const char * name;
} compression_methods[] = {
@@ -2407,7 +2407,7 @@ read_eocd(struct zip *zip, const char *p, int64_t current_offset)
* Examine Zip64 EOCD locator: If it's valid, store the information
* from it.
*/
-static void
+static int
read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
{
int64_t eocd64_offset;
@@ -2417,35 +2417,37 @@ read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
/* Central dir must be on first volume. */
if (archive_le32dec(p + 4) != 0)
- return;
+ return 0;
/* Must be only a single volume. */
if (archive_le32dec(p + 16) != 1)
- return;
+ return 0;
/* Find the Zip64 EOCD record. */
eocd64_offset = archive_le64dec(p + 8);
if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
- return;
+ return 0;
if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
- return;
+ return 0;
/* Make sure we can read all of it. */
eocd64_size = archive_le64dec(p + 4) + 12;
if (eocd64_size < 56 || eocd64_size > 16384)
- return;
+ return 0;
if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
- return;
+ return 0;
/* Sanity-check the EOCD64 */
if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
- return;
+ return 0;
if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
- return;
+ return 0;
/* CD can't be split. */
if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
- return;
+ return 0;
/* Save the central directory offset for later use. */
zip->central_directory_offset = archive_le64dec(p + 48);
+
+ return 32;
}
static int
@@ -2483,15 +2485,14 @@ archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
if (memcmp(p + i, "PK\005\006", 4) == 0) {
int ret = read_eocd(zip, p + i,
current_offset + i);
- if (ret > 0) {
- /* Zip64 EOCD locator precedes
- * regular EOCD if present. */
- if (i >= 20
- && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
- read_zip64_eocd(a, zip, p + i - 20);
- }
- return (ret);
+ /* Zip64 EOCD locator precedes
+ * regular EOCD if present. */
+ if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
+ int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
+ if (ret_zip64 > ret)
+ ret = ret_zip64;
}
+ return (ret);
}
i -= 4;
break;
diff --git a/Utilities/cmlibarchive/libarchive/archive_string.c b/Utilities/cmlibarchive/libarchive/archive_string.c
index 592ead2bd..5ae09b626 100644
--- a/Utilities/cmlibarchive/libarchive/archive_string.c
+++ b/Utilities/cmlibarchive/libarchive/archive_string.c
@@ -202,7 +202,8 @@ archive_string_append(struct archive_string *as, const char *p, size_t s)
{
if (archive_string_ensure(as, as->length + s + 1) == NULL)
return (NULL);
- memmove(as->s + as->length, p, s);
+ if (s)
+ memmove(as->s + as->length, p, s);
as->length += s;
as->s[as->length] = 0;
return (as);
diff --git a/Utilities/cmlibarchive/libarchive/archive_string_sprintf.c b/Utilities/cmlibarchive/libarchive/archive_string_sprintf.c
index 964ea2bea..969a5603a 100644
--- a/Utilities/cmlibarchive/libarchive/archive_string_sprintf.c
+++ b/Utilities/cmlibarchive/libarchive/archive_string_sprintf.c
@@ -53,7 +53,7 @@ __FBSDID("$FreeBSD: head/lib/libarchive/archive_string_sprintf.c 189435 2009-03-
static void
append_uint(struct archive_string *as, uintmax_t d, unsigned base)
{
- static const char *digits = "0123456789abcdef";
+ static const char digits[] = "0123456789abcdef";
if (d >= base)
append_uint(as, d/base, base);
archive_strappend_char(as, digits[d % base]);
diff --git a/Utilities/cmlibarchive/libarchive/archive_util.c b/Utilities/cmlibarchive/libarchive/archive_util.c
index f56ca332d..1e36ad7ee 100644
--- a/Utilities/cmlibarchive/libarchive/archive_util.c
+++ b/Utilities/cmlibarchive/libarchive/archive_util.c
@@ -89,88 +89,6 @@ archive_version_string(void)
return (ARCHIVE_VERSION_STRING);
}
-const char *
-archive_version_details(void)
-{
- static struct archive_string str;
- static int init = 0;
- const char *zlib = archive_zlib_version();
- const char *liblzma = archive_liblzma_version();
- const char *bzlib = archive_bzlib_version();
- const char *liblz4 = archive_liblz4_version();
-
- if (!init) {
- archive_string_init(&str);
-
- archive_strcat(&str, ARCHIVE_VERSION_STRING);
- if (zlib != NULL) {
- archive_strcat(&str, " zlib/");
- archive_strcat(&str, zlib);
- }
- if (liblzma) {
- archive_strcat(&str, " liblzma/");
- archive_strcat(&str, liblzma);
- }
- if (bzlib) {
- const char *p = bzlib;
- const char *sep = strchr(p, ',');
- if (sep == NULL)
- sep = p + strlen(p);
- archive_strcat(&str, " bz2lib/");
- archive_strncat(&str, p, sep - p);
- }
- if (liblz4) {
- archive_strcat(&str, " liblz4/");
- archive_strcat(&str, liblz4);
- }
- }
- return str.s;
-}
-
-const char *
-archive_zlib_version(void)
-{
-#ifdef HAVE_ZLIB_H
- return ZLIB_VERSION;
-#else
- return NULL;
-#endif
-}
-
-const char *
-archive_liblzma_version(void)
-{
-#ifdef HAVE_LZMA_H
- return LZMA_VERSION_STRING;
-#else
- return NULL;
-#endif
-}
-
-const char *
-archive_bzlib_version(void)
-{
-#ifdef HAVE_BZLIB_H
- return BZ2_bzlibVersion();
-#else
- return NULL;
-#endif
-}
-
-const char *
-archive_liblz4_version(void)
-{
-#if defined(HAVE_LZ4_H) && defined(HAVE_LIBLZ4)
-#define str(s) #s
-#define NUMBER(x) str(x)
- return NUMBER(LZ4_VERSION_MAJOR) "." NUMBER(LZ4_VERSION_MINOR) "." NUMBER(LZ4_VERSION_RELEASE);
-#undef NUMBER
-#undef str
-#else
- return NULL;
-#endif
-}
-
int
archive_errno(struct archive *a)
{
@@ -275,7 +193,7 @@ archive_copy_error(struct archive *dest, struct archive *src)
void
__archive_errx(int retvalue, const char *msg)
{
- static const char *msg1 = "Fatal Internal Error in libarchive: ";
+ static const char msg1[] = "Fatal Internal Error in libarchive: ";
size_t s;
s = write(2, msg1, strlen(msg1));
@@ -303,8 +221,8 @@ __archive_errx(int retvalue, const char *msg)
int
__archive_mktemp(const char *tmpdir)
{
- static const wchar_t *prefix = L"libarchive_";
- static const wchar_t *suffix = L"XXXXXXXXXX";
+ static const wchar_t prefix[] = L"libarchive_";
+ static const wchar_t suffix[] = L"XXXXXXXXXX";
static const wchar_t num[] = {
L'0', L'1', L'2', L'3', L'4', L'5', L'6', L'7',
L'8', L'9', L'A', L'B', L'C', L'D', L'E', L'F',
diff --git a/Utilities/cmlibarchive/libarchive/archive_version_details.c b/Utilities/cmlibarchive/libarchive/archive_version_details.c
new file mode 100644
index 000000000..9289bf1ac
--- /dev/null
+++ b/Utilities/cmlibarchive/libarchive/archive_version_details.c
@@ -0,0 +1,133 @@
+/*-
+ * Copyright (c) 2009-2012,2014 Michihiro NAKAJIMA
+ * Copyright (c) 2003-2007 Tim Kientzle
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "archive_platform.h"
+__FBSDID("$FreeBSD: head/lib/libarchive/archive_util.c 201098 2009-12-28 02:58:14Z kientzle $");
+
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+#ifdef HAVE_STRING_H
+#include <string.h>
+#endif
+#ifdef HAVE_ZLIB_H
+#include <cm_zlib.h>
+#endif
+#ifdef HAVE_LZMA_H
+#include <cm_lzma.h>
+#endif
+#ifdef HAVE_BZLIB_H
+#include <cm_bzlib.h>
+#endif
+#ifdef HAVE_LZ4_H
+#include <lz4.h>
+#endif
+
+#include "archive.h"
+#include "archive_private.h"
+#include "archive_string.h"
+
+const char *
+archive_version_details(void)
+{
+ static struct archive_string str;
+ static int init = 0;
+ const char *zlib = archive_zlib_version();
+ const char *liblzma = archive_liblzma_version();
+ const char *bzlib = archive_bzlib_version();
+ const char *liblz4 = archive_liblz4_version();
+
+ if (!init) {
+ archive_string_init(&str);
+
+ archive_strcat(&str, ARCHIVE_VERSION_STRING);
+ if (zlib != NULL) {
+ archive_strcat(&str, " zlib/");
+ archive_strcat(&str, zlib);
+ }
+ if (liblzma) {
+ archive_strcat(&str, " liblzma/");
+ archive_strcat(&str, liblzma);
+ }
+ if (bzlib) {
+ const char *p = bzlib;
+ const char *sep = strchr(p, ',');
+ if (sep == NULL)
+ sep = p + strlen(p);
+ archive_strcat(&str, " bz2lib/");
+ archive_strncat(&str, p, sep - p);
+ }
+ if (liblz4) {
+ archive_strcat(&str, " liblz4/");
+ archive_strcat(&str, liblz4);
+ }
+ }
+ return str.s;
+}
+
+const char *
+archive_zlib_version(void)
+{
+#ifdef HAVE_ZLIB_H
+ return ZLIB_VERSION;
+#else
+ return NULL;
+#endif
+}
+
+const char *
+archive_liblzma_version(void)
+{
+#ifdef HAVE_LZMA_H
+ return LZMA_VERSION_STRING;
+#else
+ return NULL;
+#endif
+}
+
+const char *
+archive_bzlib_version(void)
+{
+#ifdef HAVE_BZLIB_H
+ return BZ2_bzlibVersion();
+#else
+ return NULL;
+#endif
+}
+
+const char *
+archive_liblz4_version(void)
+{
+#if defined(HAVE_LZ4_H) && defined(HAVE_LIBLZ4)
+#define str(s) #s
+#define NUMBER(x) str(x)
+ return NUMBER(LZ4_VERSION_MAJOR) "." NUMBER(LZ4_VERSION_MINOR) "." NUMBER(LZ4_VERSION_RELEASE);
+#undef NUMBER
+#undef str
+#else
+ return NULL;
+#endif
+}
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_add_filter.c b/Utilities/cmlibarchive/libarchive/archive_write_add_filter.c
index ad5dc832f..08f518ade 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_add_filter.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_add_filter.c
@@ -38,7 +38,7 @@ __FBSDID("$FreeBSD$");
#include "archive_private.h"
/* A table that maps filter codes to functions. */
-static
+static const
struct { int code; int (*setter)(struct archive *); } codes[] =
{
{ ARCHIVE_FILTER_NONE, archive_write_add_filter_none },
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_by_name.c b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_by_name.c
index eac4011cb..85a8d4753 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_by_name.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_by_name.c
@@ -42,7 +42,7 @@ __FBSDID("$FreeBSD$");
#include "archive_private.h"
/* A table that maps names to functions. */
-static
+static const
struct { const char *name; int (*setter)(struct archive *); } names[] =
{
{ "b64encode", archive_write_add_filter_b64encode },
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_lz4.c b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_lz4.c
index e6551859c..15fd494a4 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_lz4.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_lz4.c
@@ -225,7 +225,7 @@ archive_filter_lz4_open(struct archive_write_filter *f)
struct private_data *data = (struct private_data *)f->data;
int ret;
size_t required_size;
- static size_t bkmap[] = { 64 * 1024, 256 * 1024, 1 * 1024 * 1024,
+ static size_t const bkmap[] = { 64 * 1024, 256 * 1024, 1 * 1024 * 1024,
4 * 1024 * 1024 };
size_t pre_block_size;
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_program.c b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_program.c
index 55b5e8ecd..660f693f2 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_add_filter_program.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_add_filter_program.c
@@ -92,7 +92,7 @@ archive_write_add_filter_program(struct archive *_a, const char *cmd)
{
struct archive_write_filter *f = __archive_write_allocate_filter(_a);
struct private_data *data;
- static const char *prefix = "Program: ";
+ static const char prefix[] = "Program: ";
archive_check_magic(_a, ARCHIVE_WRITE_MAGIC,
ARCHIVE_STATE_NEW, "archive_write_add_filter_program");
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_data.3 b/Utilities/cmlibarchive/libarchive/archive_write_data.3
index 0cdd25f1f..9c16cd9b4 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_data.3
+++ b/Utilities/cmlibarchive/libarchive/archive_write_data.3
@@ -24,11 +24,12 @@
.\"
.\" $FreeBSD$
.\"
-.Dd February 2, 2012
+.Dd February 28, 2017
.Dt ARCHIVE_WRITE_DATA 3
.Os
.Sh NAME
-.Nm archive_write_data
+.Nm archive_write_data ,
+.Nm archive_write_data_block
.Nd functions for creating archives
.Sh LIBRARY
Streaming Archive Library (libarchive, -larchive)
@@ -36,8 +37,27 @@ Streaming Archive Library (libarchive, -larchive)
.In archive.h
.Ft la_ssize_t
.Fn archive_write_data "struct archive *" "const void *" "size_t"
+.Ft la_ssize_t
+.Fn archive_write_data_block "struct archive *" "const void *" "size_t size" "int64_t offset"
.Sh DESCRIPTION
+.Bl -tag -width indent
+.It Fn archive_write_data
+Write data corresponding to the header just written.
+.It Fn archive_write_data_block
Write data corresponding to the header just written.
+This is like
+.Fn archive_write_data
+except that it performs a seek on the file being
+written to the specified offset before writing the data.
+This is useful when restoring sparse files from archive
+formats that support sparse files.
+Returns number of bytes written or -1 on error.
+(Note: This is currently not supported for
+.Tn archive_write
+handles, only for
+.Tn archive_write_disk
+handles.
+.El
.\" .Sh EXAMPLE
.\"
.Sh RETURN VALUES
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_disk.3 b/Utilities/cmlibarchive/libarchive/archive_write_disk.3
index ba6c9706e..949c9ef10 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_disk.3
+++ b/Utilities/cmlibarchive/libarchive/archive_write_disk.3
@@ -24,7 +24,7 @@
.\"
.\" $FreeBSD$
.\"
-.Dd February 2, 2012
+.Dd April 3, 2017
.Dt ARCHIVE_WRITE_DISK 3
.Os
.Sh NAME
@@ -33,14 +33,7 @@
.Nm archive_write_disk_set_skip_file ,
.Nm archive_write_disk_set_group_lookup ,
.Nm archive_write_disk_set_standard_lookup ,
-.Nm archive_write_disk_set_user_lookup ,
-.Nm archive_write_header ,
-.Nm archive_write_data ,
-.Nm archive_write_data_block ,
-.Nm archive_write_finish_entry ,
-.Nm archive_write_close ,
-.Nm archive_write_finish
-.Nm archive_write_free
+.Nm archive_write_disk_set_user_lookup
.Nd functions for creating objects on disk
.Sh LIBRARY
Streaming Archive Library (libarchive, -larchive)
@@ -68,20 +61,6 @@ Streaming Archive Library (libarchive, -larchive)
.Fa "uid_t (*)(void *, const char *uname, uid_t uid)"
.Fa "void (*cleanup)(void *)"
.Fc
-.Ft int
-.Fn archive_write_header "struct archive *" "struct archive_entry *"
-.Ft la_ssize_t
-.Fn archive_write_data "struct archive *" "const void *" "size_t"
-.Ft la_ssize_t
-.Fn archive_write_data_block "struct archive *" "const void *" "size_t size" "int64_t offset"
-.Ft int
-.Fn archive_write_finish_entry "struct archive *"
-.Ft int
-.Fn archive_write_close "struct archive *"
-.Ft int
-.Fn archive_write_finish "struct archive *"
-.Ft int
-.Fn archive_write_free "struct archive *"
.Sh DESCRIPTION
These functions provide a complete API for creating objects on
disk from
@@ -117,6 +96,33 @@ performance optimization in practice.
The options field consists of a bitwise OR of one or more of the
following values:
.Bl -tag -compact -width "indent"
+.It Cm ARCHIVE_EXTRACT_ACL
+Attempt to restore Access Control Lists.
+By default, extended ACLs are ignored.
+.It Cm ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS
+Before removing a file system object prior to replacing it, clear
+platform-specific file flags which might prevent its removal.
+.It Cm ARCHIVE_EXTRACT_FFLAGS
+Attempt to restore file attributes (file flags).
+By default, file attributes are ignored.
+See
+.Xr chattr 1
+.Pq Linux
+or
+.Xr chflags 1
+.Pq FreeBSD, Mac OS X
+for more information on file attributes.
+.It Cm ARCHIVE_EXTRACT_MAC_METADATA
+Mac OS X specific. Restore metadata using
+.Xr copyfile 3 .
+By default,
+.Xr copyfile 3
+metadata is ignored.
+.It Cm ARCHIVE_EXTRACT_NO_OVERWRITE
+Existing files on disk will not be overwritten.
+By default, existing regular files are truncated and overwritten;
+existing directories will have their permissions updated;
+other pre-existing objects are unlinked and recreated from scratch.
.It Cm ARCHIVE_EXTRACT_OWNER
The user and group IDs should be set on the restored file.
By default, the user and group IDs are not restored.
@@ -132,15 +138,37 @@ is not specified, then SUID and SGID bits will only be restored
if the default user and group IDs of newly-created objects on disk
happen to match those specified in the archive entry.
By default, only basic permissions are restored, and umask is obeyed.
+.It Cm ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS
+Refuse to extract an absolute path.
+The default is to not refuse such paths.
+.It Cm ARCHIVE_EXTRACT_SECURE_NODOTDOT
+Refuse to extract a path that contains a
+.Pa ..
+element anywhere within it.
+The default is to not refuse such paths.
+Note that paths ending in
+.Pa ..
+always cause an error, regardless of this flag.
+.It Cm ARCHIVE_EXTRACT_SECURE_SYMLINKS
+Refuse to extract any object whose final location would be altered
+by a symlink on disk.
+This is intended to help guard against a variety of mischief
+caused by archives that (deliberately or otherwise) extract
+files outside of the current directory.
+The default is not to perform this check.
+If
+.It Cm ARCHIVE_EXTRACT_SPARSE
+Scan data for blocks of NUL bytes and try to recreate them with holes.
+This results in sparse files, independent of whether the archive format
+supports or uses them.
+.Cm ARCHIVE_EXTRACT_UNLINK
+is specified together with this option, the library will
+remove any intermediate symlinks it finds and return an
+error only if such symlink could not be removed.
.It Cm ARCHIVE_EXTRACT_TIME
The timestamps (mtime, ctime, and atime) should be restored.
By default, they are ignored.
Note that restoring of atime is not currently supported.
-.It Cm ARCHIVE_EXTRACT_NO_OVERWRITE
-Existing files on disk will not be overwritten.
-By default, existing regular files are truncated and overwritten;
-existing directories will have their permissions updated;
-other pre-existing objects are unlinked and recreated from scratch.
.It Cm ARCHIVE_EXTRACT_UNLINK
Existing files on disk will be unlinked before any attempt to
create them.
@@ -148,45 +176,18 @@ In some cases, this can prove to be a significant performance improvement.
By default, existing files are truncated and rewritten, but
the file is not recreated.
In particular, the default behavior does not break existing hard links.
-.It Cm ARCHIVE_EXTRACT_ACL
-Attempt to restore ACLs.
-By default, extended ACLs are ignored.
-.It Cm ARCHIVE_EXTRACT_FFLAGS
-Attempt to restore extended file flags.
-By default, file flags are ignored.
.It Cm ARCHIVE_EXTRACT_XATTR
-Attempt to restore POSIX.1e extended attributes.
+Attempt to restore extended file attributes.
By default, they are ignored.
-.It Cm ARCHIVE_EXTRACT_SECURE_SYMLINKS
-Refuse to extract any object whose final location would be altered
-by a symlink on disk.
-This is intended to help guard against a variety of mischief
-caused by archives that (deliberately or otherwise) extract
-files outside of the current directory.
-The default is not to perform this check.
-If
-.Cm ARCHIVE_EXTRACT_UNLINK
-is specified together with this option, the library will
-remove any intermediate symlinks it finds and return an
-error only if such symlink could not be removed.
-.It Cm ARCHIVE_EXTRACT_SECURE_NODOTDOT
-Refuse to extract a path that contains a
-.Pa ..
-element anywhere within it.
-The default is to not refuse such paths.
-Note that paths ending in
-.Pa ..
-always cause an error, regardless of this flag.
-.It Cm ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS
-Refuse to extract an absolute path.
-The default is to not refuse such paths.
-.It Cm ARCHIVE_EXTRACT_SPARSE
-Scan data for blocks of NUL bytes and try to recreate them with holes.
-This results in sparse files, independent of whether the archive format
-supports or uses them.
-.It Cm ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS
-Before removing a file system object prior to replacing it, clear
-platform-specific file flags which might prevent its removal.
+See
+.Xr xattr 7
+.Pq Linux ,
+.Xr xattr 2
+.Pq Mac OS X ,
+or
+.Xr getextattr 8
+.Pq FreeBSD
+for more information on extended file attributes.
.El
.It Xo
.Fn archive_write_disk_set_group_lookup ,
@@ -223,60 +224,6 @@ the number of calls to
.Xr getpwnam 3
and
.Xr getgrnam 3 .
-.It Fn archive_write_header
-Build and write a header using the data in the provided
-.Tn struct archive_entry
-structure.
-See
-.Xr archive_entry 3
-for information on creating and populating
-.Tn struct archive_entry
-objects.
-.It Fn archive_write_data
-Write data corresponding to the header just written.
-Returns number of bytes written or -1 on error.
-.It Fn archive_write_data_block
-Write data corresponding to the header just written.
-This is like
-.Fn archive_write_data
-except that it performs a seek on the file being
-written to the specified offset before writing the data.
-This is useful when restoring sparse files from archive
-formats that support sparse files.
-Returns number of bytes written or -1 on error.
-(Note: This is currently not supported for
-.Tn archive_write
-handles, only for
-.Tn archive_write_disk
-handles.)
-.It Fn archive_write_finish_entry
-Close out the entry just written.
-Ordinarily, clients never need to call this, as it
-is called automatically by
-.Fn archive_write_next_header
-and
-.Fn archive_write_close
-as needed.
-However, some file attributes are written to disk only
-after the file is closed, so this can be necessary
-if you need to work with the file on disk right away.
-.It Fn archive_write_close
-Set any attributes that could not be set during the initial restore.
-For example, directory timestamps are not restored initially because
-restoring a subsequent file would alter that timestamp.
-Similarly, non-writable directories are initially created with
-write permissions (so that their contents can be restored).
-The
-.Nm
-library maintains a list of all such deferred attributes and
-sets them when this function is invoked.
-.It Fn archive_write_finish
-This is a deprecated synonym for
-.Fn archive_write_free .
-.It Fn archive_write_free
-Invokes
-.Fn archive_write_close
-if it was not invoked manually, then releases all resources.
.El
More information about the
.Va struct archive
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_disk_acl.c b/Utilities/cmlibarchive/libarchive/archive_write_disk_acl.c
deleted file mode 100644
index 144ab7e72..000000000
--- a/Utilities/cmlibarchive/libarchive/archive_write_disk_acl.c
+++ /dev/null
@@ -1,654 +0,0 @@
-/*-
- * Copyright (c) 2003-2010 Tim Kientzle
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer
- * in this position and unchanged.
- * 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: head/lib/libarchive/archive_write_disk.c 201159 2009-12-29 05:35:40Z kientzle $");
-
-#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif
-#ifdef HAVE_SYS_ACL_H
-#define _ACL_PRIVATE /* For debugging */
-#include <sys/acl.h>
-#endif
-#if HAVE_DARWIN_ACL
-#include <membership.h>
-#endif
-#ifdef HAVE_ERRNO_H
-#include <errno.h>
-#endif
-
-#include "archive.h"
-#include "archive_entry.h"
-#include "archive_acl_private.h"
-#include "archive_write_disk_private.h"
-
-#if !HAVE_POSIX_ACL && !HAVE_NFS4_ACL
-/* Default empty function body to satisfy mainline code. */
-int
-archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
- struct archive_acl *abstract_acl)
-{
- (void)a; /* UNUSED */
- (void)fd; /* UNUSED */
- (void)name; /* UNUSED */
- (void)abstract_acl; /* UNUSED */
- return (ARCHIVE_OK);
-}
-
-#else /* HAVE_POSIX_ACL || HAVE_NFS4_ACL */
-
-#if HAVE_SUN_ACL
-#define ARCHIVE_PLATFORM_ACL_TYPE_NFS4 ACE_T
-#elif HAVE_DARWIN_ACL
-#define ARCHIVE_PLATFORM_ACL_TYPE_NFS4 ACL_TYPE_EXTENDED
-#elif HAVE_ACL_TYPE_NFS4
-#define ARCHIVE_PLATFORM_ACL_TYPE_NFS4 ACL_TYPE_NFS4
-#endif
-
-static int set_acl(struct archive *, int fd, const char *,
- struct archive_acl *,
- acl_type_t, int archive_entry_acl_type, const char *tn);
-
-int
-archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
- struct archive_acl *abstract_acl)
-{
- int ret = ARCHIVE_OK;
-
-#if !HAVE_DARWIN_ACL
- if ((archive_acl_types(abstract_acl)
- & ARCHIVE_ENTRY_ACL_TYPE_POSIX1E) != 0) {
-#if HAVE_SUN_ACL
- /* Solaris writes POSIX.1e access and default ACLs together */
- ret = set_acl(a, fd, name, abstract_acl, ACLENT_T,
- ARCHIVE_ENTRY_ACL_TYPE_POSIX1E, "posix1e");
-#else /* HAVE_POSIX_ACL */
- if ((archive_acl_types(abstract_acl)
- & ARCHIVE_ENTRY_ACL_TYPE_ACCESS) != 0) {
- ret = set_acl(a, fd, name, abstract_acl,
- ACL_TYPE_ACCESS, ARCHIVE_ENTRY_ACL_TYPE_ACCESS,
- "access");
- if (ret != ARCHIVE_OK)
- return (ret);
- }
- if ((archive_acl_types(abstract_acl)
- & ARCHIVE_ENTRY_ACL_TYPE_DEFAULT) != 0)
- ret = set_acl(a, fd, name, abstract_acl,
- ACL_TYPE_DEFAULT, ARCHIVE_ENTRY_ACL_TYPE_DEFAULT,
- "default");
-#endif /* !HAVE_SUN_ACL */
- /* Simultaneous POSIX.1e and NFSv4 is not supported */
- return (ret);
- }
-#endif /* !HAVE_DARWIN_ACL */
-#if HAVE_NFS4_ACL
- if ((archive_acl_types(abstract_acl) &
- ARCHIVE_ENTRY_ACL_TYPE_NFS4) != 0) {
- ret = set_acl(a, fd, name, abstract_acl,
- ARCHIVE_PLATFORM_ACL_TYPE_NFS4,
- ARCHIVE_ENTRY_ACL_TYPE_NFS4, "nfs4");
- }
-#endif /* HAVE_NFS4_ACL */
- return (ret);
-}
-
-/*
- * Translate system ACL permissions into libarchive internal structure
- */
-static const struct {
- const int archive_perm;
- const int platform_perm;
-} acl_perm_map[] = {
-#if HAVE_SUN_ACL /* Solaris NFSv4 ACL permissions */
- {ARCHIVE_ENTRY_ACL_EXECUTE, ACE_EXECUTE},
- {ARCHIVE_ENTRY_ACL_READ_DATA, ACE_READ_DATA},
- {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, ACE_LIST_DIRECTORY},
- {ARCHIVE_ENTRY_ACL_WRITE_DATA, ACE_WRITE_DATA},
- {ARCHIVE_ENTRY_ACL_ADD_FILE, ACE_ADD_FILE},
- {ARCHIVE_ENTRY_ACL_APPEND_DATA, ACE_APPEND_DATA},
- {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, ACE_ADD_SUBDIRECTORY},
- {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, ACE_READ_NAMED_ATTRS},
- {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, ACE_WRITE_NAMED_ATTRS},
- {ARCHIVE_ENTRY_ACL_DELETE_CHILD, ACE_DELETE_CHILD},
- {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, ACE_READ_ATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, ACE_WRITE_ATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_DELETE, ACE_DELETE},
- {ARCHIVE_ENTRY_ACL_READ_ACL, ACE_READ_ACL},
- {ARCHIVE_ENTRY_ACL_WRITE_ACL, ACE_WRITE_ACL},
- {ARCHIVE_ENTRY_ACL_WRITE_OWNER, ACE_WRITE_OWNER},
- {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, ACE_SYNCHRONIZE}
-#elif HAVE_DARWIN_ACL /* MacOS ACL permissions */
- {ARCHIVE_ENTRY_ACL_READ_DATA, ACL_READ_DATA},
- {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, ACL_LIST_DIRECTORY},
- {ARCHIVE_ENTRY_ACL_WRITE_DATA, ACL_WRITE_DATA},
- {ARCHIVE_ENTRY_ACL_ADD_FILE, ACL_ADD_FILE},
- {ARCHIVE_ENTRY_ACL_EXECUTE, ACL_EXECUTE},
- {ARCHIVE_ENTRY_ACL_DELETE, ACL_DELETE},
- {ARCHIVE_ENTRY_ACL_APPEND_DATA, ACL_APPEND_DATA},
- {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, ACL_ADD_SUBDIRECTORY},
- {ARCHIVE_ENTRY_ACL_DELETE_CHILD, ACL_DELETE_CHILD},
- {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, ACL_READ_ATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, ACL_WRITE_ATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, ACL_READ_EXTATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, ACL_WRITE_EXTATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_READ_ACL, ACL_READ_SECURITY},
- {ARCHIVE_ENTRY_ACL_WRITE_ACL, ACL_WRITE_SECURITY},
- {ARCHIVE_ENTRY_ACL_WRITE_OWNER, ACL_CHANGE_OWNER},
- {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, ACL_SYNCHRONIZE}
-#else /* POSIX.1e ACL permissions */
- {ARCHIVE_ENTRY_ACL_EXECUTE, ACL_EXECUTE},
- {ARCHIVE_ENTRY_ACL_WRITE, ACL_WRITE},
- {ARCHIVE_ENTRY_ACL_READ, ACL_READ},
-#if HAVE_ACL_TYPE_NFS4 /* FreeBSD NFSv4 ACL permissions */
- {ARCHIVE_ENTRY_ACL_READ_DATA, ACL_READ_DATA},
- {ARCHIVE_ENTRY_ACL_LIST_DIRECTORY, ACL_LIST_DIRECTORY},
- {ARCHIVE_ENTRY_ACL_WRITE_DATA, ACL_WRITE_DATA},
- {ARCHIVE_ENTRY_ACL_ADD_FILE, ACL_ADD_FILE},
- {ARCHIVE_ENTRY_ACL_APPEND_DATA, ACL_APPEND_DATA},
- {ARCHIVE_ENTRY_ACL_ADD_SUBDIRECTORY, ACL_ADD_SUBDIRECTORY},
- {ARCHIVE_ENTRY_ACL_READ_NAMED_ATTRS, ACL_READ_NAMED_ATTRS},
- {ARCHIVE_ENTRY_ACL_WRITE_NAMED_ATTRS, ACL_WRITE_NAMED_ATTRS},
- {ARCHIVE_ENTRY_ACL_DELETE_CHILD, ACL_DELETE_CHILD},
- {ARCHIVE_ENTRY_ACL_READ_ATTRIBUTES, ACL_READ_ATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_WRITE_ATTRIBUTES, ACL_WRITE_ATTRIBUTES},
- {ARCHIVE_ENTRY_ACL_DELETE, ACL_DELETE},
- {ARCHIVE_ENTRY_ACL_READ_ACL, ACL_READ_ACL},
- {ARCHIVE_ENTRY_ACL_WRITE_ACL, ACL_WRITE_ACL},
- {ARCHIVE_ENTRY_ACL_WRITE_OWNER, ACL_WRITE_OWNER},
- {ARCHIVE_ENTRY_ACL_SYNCHRONIZE, ACL_SYNCHRONIZE}
-#endif
-#endif /* !HAVE_SUN_ACL && !HAVE_DARWIN_ACL */
-};
-
-#if HAVE_NFS4_ACL
-/*
- * Translate system NFSv4 inheritance flags into libarchive internal structure
- */
-static const struct {
- const int archive_inherit;
- const int platform_inherit;
-} acl_inherit_map[] = {
-#if HAVE_SUN_ACL /* Solaris NFSv4 inheritance flags */
- {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, ACE_FILE_INHERIT_ACE},
- {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, ACE_DIRECTORY_INHERIT_ACE},
- {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, ACE_NO_PROPAGATE_INHERIT_ACE},
- {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, ACE_INHERIT_ONLY_ACE},
- {ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS, ACE_SUCCESSFUL_ACCESS_ACE_FLAG},
- {ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS, ACE_FAILED_ACCESS_ACE_FLAG},
- {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACE_INHERITED_ACE}
-#elif HAVE_DARWIN_ACL /* MacOS NFSv4 inheritance flags */
- {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACL_ENTRY_INHERITED},
- {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, ACL_ENTRY_FILE_INHERIT},
- {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, ACL_ENTRY_DIRECTORY_INHERIT},
- {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, ACL_ENTRY_LIMIT_INHERIT},
- {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, ACL_ENTRY_ONLY_INHERIT}
-#else /* FreeBSD NFSv4 ACL inheritance flags */
- {ARCHIVE_ENTRY_ACL_ENTRY_FILE_INHERIT, ACL_ENTRY_FILE_INHERIT},
- {ARCHIVE_ENTRY_ACL_ENTRY_DIRECTORY_INHERIT, ACL_ENTRY_DIRECTORY_INHERIT},
- {ARCHIVE_ENTRY_ACL_ENTRY_NO_PROPAGATE_INHERIT, ACL_ENTRY_NO_PROPAGATE_INHERIT},
- {ARCHIVE_ENTRY_ACL_ENTRY_INHERIT_ONLY, ACL_ENTRY_INHERIT_ONLY},
- {ARCHIVE_ENTRY_ACL_ENTRY_SUCCESSFUL_ACCESS, ACL_ENTRY_SUCCESSFUL_ACCESS},
- {ARCHIVE_ENTRY_ACL_ENTRY_FAILED_ACCESS, ACL_ENTRY_FAILED_ACCESS},
- {ARCHIVE_ENTRY_ACL_ENTRY_INHERITED, ACL_ENTRY_INHERITED}
-#endif /* !HAVE_SUN_ACL && !HAVE_DARWIN_ACL */
-};
-#endif /* HAVE_NFS4_ACL */
-
-static int
-set_acl(struct archive *a, int fd, const char *name,
- struct archive_acl *abstract_acl,
- acl_type_t acl_type, int ae_requested_type, const char *tname)
-{
-#if HAVE_SUN_ACL
- aclent_t *aclent;
- ace_t *ace;
- int e, r;
- acl_t *acl;
-#else
- acl_t acl;
- acl_entry_t acl_entry;
- acl_permset_t acl_permset;
-#if HAVE_ACL_TYPE_NFS4 || HAVE_DARWIN_ACL
- acl_flagset_t acl_flagset;
-#endif
-#endif /* HAVE_SUN_ACL */
-#if HAVE_ACL_TYPE_NFS4
- int r;
-#endif
- int ret;
- int ae_type, ae_permset, ae_tag, ae_id;
-#if HAVE_DARWIN_ACL
- uuid_t ae_uuid;
-#endif
- uid_t ae_uid;
- gid_t ae_gid;
- const char *ae_name;
- int entries;
- int i;
-
- ret = ARCHIVE_OK;
- entries = archive_acl_reset(abstract_acl, ae_requested_type);
- if (entries == 0)
- return (ARCHIVE_OK);
-
-#if HAVE_SUN_ACL
- acl = NULL;
- acl = malloc(sizeof(acl_t));
- if (acl == NULL) {
- archive_set_error(a, ARCHIVE_ERRNO_MISC,
- "Invalid ACL type");
- return (ARCHIVE_FAILED);
- }
- if (acl_type == ACE_T)
- acl->acl_entry_size = sizeof(ace_t);
- else if (acl_type == ACLENT_T)
- acl->acl_entry_size = sizeof(aclent_t);
- else {
- archive_set_error(a, ARCHIVE_ERRNO_MISC,
- "Invalid ACL type");
- acl_free(acl);
- return (ARCHIVE_FAILED);
- }
- acl->acl_type = acl_type;
- acl->acl_cnt = entries;
-
- acl->acl_aclp = malloc(entries * acl->acl_entry_size);
- if (acl->acl_aclp == NULL) {
- archive_set_error(a, errno,
- "Can't allocate memory for acl buffer");
- acl_free(acl);
- return (ARCHIVE_FAILED);
- }
-#else /* !HAVE_SUN_ACL */
- acl = acl_init(entries);
- if (acl == (acl_t)NULL) {
- archive_set_error(a, errno,
- "Failed to initialize ACL working storage");
- return (ARCHIVE_FAILED);
- }
-#endif /* !HAVE_SUN_ACL */
-#if HAVE_SUN_ACL
- e = 0;
-#endif
- while (archive_acl_next(a, abstract_acl, ae_requested_type, &ae_type,
- &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
-#if HAVE_SUN_ACL
- ace = NULL;
- aclent = NULL;
- if (acl->acl_type == ACE_T) {
- ace = &((ace_t *)acl->acl_aclp)[e];
- ace->a_who = -1;
- ace->a_access_mask = 0;
- ace->a_flags = 0;
- } else {
- aclent = &((aclent_t *)acl->acl_aclp)[e];
- aclent->a_id = -1;
- aclent->a_type = 0;
- aclent->a_perm = 0;
- }
-#else /* !HAVE_SUN_ACL */
-#if HAVE_DARWIN_ACL
- /*
- * Mac OS doesn't support NFSv4 ACLs for
- * owner@, group@ and everyone@.
- * We skip any of these ACLs found.
- */
- if (ae_tag == ARCHIVE_ENTRY_ACL_USER_OBJ ||
- ae_tag == ARCHIVE_ENTRY_ACL_GROUP_OBJ ||
- ae_tag == ARCHIVE_ENTRY_ACL_EVERYONE)
- continue;
-#endif
- if (acl_create_entry(&acl, &acl_entry) != 0) {
- archive_set_error(a, errno,
- "Failed to create a new ACL entry");
- ret = ARCHIVE_FAILED;
- goto exit_free;
- }
-#endif /* !HAVE_SUN_ACL */
-#if HAVE_DARWIN_ACL
- switch (ae_type) {
- case ARCHIVE_ENTRY_ACL_TYPE_ALLOW:
- acl_set_tag_type(acl_entry, ACL_EXTENDED_ALLOW);
- break;
- case ARCHIVE_ENTRY_ACL_TYPE_DENY:
- acl_set_tag_type(acl_entry, ACL_EXTENDED_DENY);
- break;
- default:
- /* We don't support any other types on MacOS */
- continue;
- }
-#endif
- switch (ae_tag) {
-#if HAVE_SUN_ACL
- case ARCHIVE_ENTRY_ACL_USER:
- ae_uid = archive_write_disk_uid(a, ae_name, ae_id);
- if (acl->acl_type == ACE_T)
- ace->a_who = ae_uid;
- else {
- aclent->a_id = ae_uid;
- aclent->a_type |= USER;
- }
- break;
- case ARCHIVE_ENTRY_ACL_GROUP:
- ae_gid = archive_write_disk_gid(a, ae_name, ae_id);
- if (acl->acl_type == ACE_T) {
- ace->a_who = ae_gid;
- ace->a_flags |= ACE_IDENTIFIER_GROUP;
- } else {
- aclent->a_id = ae_gid;
- aclent->a_type |= GROUP;
- }
- break;
- case ARCHIVE_ENTRY_ACL_USER_OBJ:
- if (acl->acl_type == ACE_T)
- ace->a_flags |= ACE_OWNER;
- else
- aclent->a_type |= USER_OBJ;
- break;
- case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
- if (acl->acl_type == ACE_T) {
- ace->a_flags |= ACE_GROUP;
- ace->a_flags |= ACE_IDENTIFIER_GROUP;
- } else
- aclent->a_type |= GROUP_OBJ;
- break;
- case ARCHIVE_ENTRY_ACL_MASK:
- aclent->a_type |= CLASS_OBJ;
- break;
- case ARCHIVE_ENTRY_ACL_OTHER:
- aclent->a_type |= OTHER_OBJ;
- break;
- case ARCHIVE_ENTRY_ACL_EVERYONE:
- ace->a_flags |= ACE_EVERYONE;
- break;
-#else /* !HAVE_SUN_ACL */
- case ARCHIVE_ENTRY_ACL_USER:
- ae_uid = archive_write_disk_uid(a, ae_name, ae_id);
-#if !HAVE_DARWIN_ACL /* FreeBSD, Linux */
- acl_set_tag_type(acl_entry, ACL_USER);
- acl_set_qualifier(acl_entry, &ae_uid);
-#else /* MacOS */
- if (mbr_identifier_to_uuid(ID_TYPE_UID, &ae_uid,
- sizeof(uid_t), ae_uuid) != 0)
- continue;
- if (acl_set_qualifier(acl_entry, &ae_uuid) != 0)
- continue;
-#endif /* HAVE_DARWIN_ACL */
- break;
- case ARCHIVE_ENTRY_ACL_GROUP:
- ae_gid = archive_write_disk_gid(a, ae_name, ae_id);
-#if !HAVE_DARWIN_ACL /* FreeBSD, Linux */
- acl_set_tag_type(acl_entry, ACL_GROUP);
- acl_set_qualifier(acl_entry, &ae_gid);
-#else /* MacOS */
- if (mbr_identifier_to_uuid(ID_TYPE_GID, &ae_gid,
- sizeof(gid_t), ae_uuid) != 0)
- continue;
- if (acl_set_qualifier(acl_entry, &ae_uuid) != 0)
- continue;
-#endif /* HAVE_DARWIN_ACL */
- break;
-#if !HAVE_DARWIN_ACL /* FreeBSD, Linux */
- case ARCHIVE_ENTRY_ACL_USER_OBJ:
- acl_set_tag_type(acl_entry, ACL_USER_OBJ);
- break;
- case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
- acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
- break;
- case ARCHIVE_ENTRY_ACL_MASK:
- acl_set_tag_type(acl_entry, ACL_MASK);
- break;
- case ARCHIVE_ENTRY_ACL_OTHER:
- acl_set_tag_type(acl_entry, ACL_OTHER);
- break;
-#if HAVE_ACL_TYPE_NFS4 /* FreeBSD only */
- case ARCHIVE_ENTRY_ACL_EVERYONE:
- acl_set_tag_type(acl_entry, ACL_EVERYONE);
- break;
-#endif
-#endif /* !HAVE_DARWIN_ACL */
-#endif /* !HAVE_SUN_ACL */
- default:
- archive_set_error(a, ARCHIVE_ERRNO_MISC,
- "Unknown ACL tag");
- ret = ARCHIVE_FAILED;
- goto exit_free;
- }
-
-#if HAVE_ACL_TYPE_NFS4 || HAVE_SUN_ACL
- r = 0;
- switch (ae_type) {
-#if HAVE_SUN_ACL
- case ARCHIVE_ENTRY_ACL_TYPE_ALLOW:
- if (ace != NULL)
- ace->a_type = ACE_ACCESS_ALLOWED_ACE_TYPE;
- else
- r = -1;
- break;
- case ARCHIVE_ENTRY_ACL_TYPE_DENY:
- if (ace != NULL)
- ace->a_type = ACE_ACCESS_DENIED_ACE_TYPE;
- else
- r = -1;
- break;
- case ARCHIVE_ENTRY_ACL_TYPE_AUDIT:
- if (ace != NULL)
- ace->a_type = ACE_SYSTEM_AUDIT_ACE_TYPE;
- else
- r = -1;
- break;
- case ARCHIVE_ENTRY_ACL_TYPE_ALARM:
- if (ace != NULL)
- ace->a_type = ACE_SYSTEM_ALARM_ACE_TYPE;
- else
- r = -1;
- break;
- case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
- if (aclent == NULL)
- r = -1;
- break;
- case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
- if (aclent != NULL)
- aclent->a_type |= ACL_DEFAULT;
- else
- r = -1;
- break;
-#else /* !HAVE_SUN_ACL */
- case ARCHIVE_ENTRY_ACL_TYPE_ALLOW:
- r = acl_set_entry_type_np(acl_entry, ACL_ENTRY_TYPE_ALLOW);
- break;
- case ARCHIVE_ENTRY_ACL_TYPE_DENY:
- r = acl_set_entry_type_np(acl_entry, ACL_ENTRY_TYPE_DENY);
- break;
- case ARCHIVE_ENTRY_ACL_TYPE_AUDIT:
- r = acl_set_entry_type_np(acl_entry, ACL_ENTRY_TYPE_AUDIT);
- break;
- case ARCHIVE_ENTRY_ACL_TYPE_ALARM:
- r = acl_set_entry_type_np(acl_entry, ACL_ENTRY_TYPE_ALARM);
- break;
- case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
- case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
- // These don't translate directly into the system ACL.
- break;
-#endif /* !HAVE_SUN_ACL */
- default:
- archive_set_error(a, ARCHIVE_ERRNO_MISC,
- "Unknown ACL entry type");
- ret = ARCHIVE_FAILED;
- goto exit_free;
- }
-
- if (r != 0) {
-#if HAVE_SUN_ACL
- errno = EINVAL;
-#endif
- archive_set_error(a, errno,
- "Failed to set ACL entry type");
- ret = ARCHIVE_FAILED;
- goto exit_free;
- }
-#endif /* HAVE_ACL_TYPE_NFS4 || HAVE_SUN_ACL */
-
-#if HAVE_SUN_ACL
- if (acl->acl_type == ACLENT_T) {
- if (ae_permset & ARCHIVE_ENTRY_ACL_EXECUTE)
- aclent->a_perm |= 1;
- if (ae_permset & ARCHIVE_ENTRY_ACL_WRITE)
- aclent->a_perm |= 2;
- if (ae_permset & ARCHIVE_ENTRY_ACL_READ)
- aclent->a_perm |= 4;
- } else
-#else
- if (acl_get_permset(acl_entry, &acl_permset) != 0) {
- archive_set_error(a, errno,
- "Failed to get ACL permission set");
- ret = ARCHIVE_FAILED;
- goto exit_free;
- }
- if (acl_clear_perms(acl_permset) != 0) {
- archive_set_error(a, errno,
- "Failed to clear ACL permissions");
- ret = ARCHIVE_FAILED;
- goto exit_free;
- }
-#endif /* !HAVE_SUN_ACL */
- for (i = 0; i < (int)(sizeof(acl_perm_map) / sizeof(acl_perm_map[0])); ++i) {
- if (ae_permset & acl_perm_map[i].archive_perm) {
-#if HAVE_SUN_ACL
- ace->a_access_mask |=
- acl_perm_map[i].platform_perm;
-#else
- if (acl_add_perm(acl_permset,
- acl_perm_map[i].platform_perm) != 0) {
- archive_set_error(a, errno,
- "Failed to add ACL permission");
- ret = ARCHIVE_FAILED;
- goto exit_free;
- }
-#endif
- }
- }
-
-#if HAVE_NFS4_ACL
-#if HAVE_SUN_ACL
- if (acl_type == ACE_T)
-#elif HAVE_DARWIN_ACL
- if (acl_type == ACL_TYPE_EXTENDED)
-#else /* FreeBSD */
- if (acl_type == ACL_TYPE_NFS4)
-#endif
- {
-#if HAVE_POSIX_ACL || HAVE_DARWIN_ACL
- /*
- * acl_get_flagset_np() fails with non-NFSv4 ACLs
- */
- if (acl_get_flagset_np(acl_entry, &acl_flagset) != 0) {
- archive_set_error(a, errno,
- "Failed to get flagset from an NFSv4 ACL entry");
- ret = ARCHIVE_FAILED;
- goto exit_free;
- }
- if (acl_clear_flags_np(acl_flagset) != 0) {
- archive_set_error(a, errno,
- "Failed to clear flags from an NFSv4 ACL flagset");
- ret = ARCHIVE_FAILED;
- goto exit_free;
- }
-#endif /* HAVE_POSIX_ACL || HAVE_DARWIN_ACL */
- for (i = 0; i < (int)(sizeof(acl_inherit_map) /sizeof(acl_inherit_map[0])); ++i) {
- if (ae_permset & acl_inherit_map[i].archive_inherit) {
-#if HAVE_SUN_ACL
- ace->a_flags |=
- acl_inherit_map[i].platform_inherit;
-#else /* !HAVE_SUN_ACL */
- if (acl_add_flag_np(acl_flagset,
- acl_inherit_map[i].platform_inherit) != 0) {
- archive_set_error(a, errno,
- "Failed to add flag to NFSv4 ACL flagset");
- ret = ARCHIVE_FAILED;
- goto exit_free;
- }
-#endif /* HAVE_SUN_ACL */
- }
- }
- }
-#endif /* HAVE_NFS4_ACL */
-#if HAVE_SUN_ACL
- e++;
-#endif
- }
-
-#if HAVE_ACL_SET_FD_NP || HAVE_ACL_SET_FD || HAVE_SUN_ACL
- /* Try restoring the ACL through 'fd' if we can. */
-#if HAVE_SUN_ACL || HAVE_ACL_SET_FD_NP
- if (fd >= 0)
-#else /* !HAVE_SUN_ACL && !HAVE_ACL_SET_FD_NP */
- if (fd >= 0 && acl_type == ACL_TYPE_ACCESS)
-#endif
- {
-#if HAVE_SUN_ACL
- if (facl_set(fd, acl) == 0)
-#elif HAVE_ACL_SET_FD_NP
- if (acl_set_fd_np(fd, acl, acl_type) == 0)
-#else /* !HAVE_SUN_ACL && !HAVE_ACL_SET_FD_NP */
- if (acl_set_fd(fd, acl) == 0)
-#endif
- ret = ARCHIVE_OK;
- else {
- if (errno == EOPNOTSUPP) {
- /* Filesystem doesn't support ACLs */
- ret = ARCHIVE_OK;
- } else {
- archive_set_error(a, errno,
- "Failed to set %s acl on fd", tname);
- }
- }
- } else
-#endif /* HAVE_ACL_SET_FD_NP || HAVE_ACL_SET_FD || HAVE_SUN_ACL */
-#if HAVE_SUN_ACL
- if (acl_set(name, acl) != 0)
-#elif HAVE_ACL_SET_LINK_NP
- if (acl_set_link_np(name, acl_type, acl) != 0)
-#else
- /* TODO: Skip this if 'name' is a symlink. */
- if (acl_set_file(name, acl_type, acl) != 0)
-#endif
- {
- if (errno == EOPNOTSUPP) {
- /* Filesystem doesn't support ACLs */
- ret = ARCHIVE_OK;
- } else {
- archive_set_error(a, errno, "Failed to set %s acl",
- tname);
- ret = ARCHIVE_WARN;
- }
- }
-exit_free:
- acl_free(acl);
- return (ret);
-}
-#endif /* HAVE_POSIX_ACL || HAVE_NFS4_ACL */
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c b/Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c
index a5f30671a..4a42a3beb 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_disk_posix.c
@@ -39,9 +39,9 @@ __FBSDID("$FreeBSD$");
#ifdef HAVE_SYS_EXTATTR_H
#include <sys/extattr.h>
#endif
-#if defined(HAVE_SYS_XATTR_H)
+#if HAVE_SYS_XATTR_H
#include <sys/xattr.h>
-#elif defined(HAVE_ATTR_XATTR_H)
+#elif HAVE_ATTR_XATTR_H
#include <attr/xattr.h>
#endif
#ifdef HAVE_SYS_EA_H
@@ -575,10 +575,55 @@ _archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
if (a->flags & ARCHIVE_EXTRACT_TIME)
a->todo |= TODO_TIMES;
if (a->flags & ARCHIVE_EXTRACT_ACL) {
+#if ARCHIVE_ACL_DARWIN
+ /*
+ * On MacOS, platform ACLs get stored in mac_metadata, too.
+ * If we intend to extract mac_metadata and it is present
+ * we skip extracting libarchive NFSv4 ACLs.
+ */
+ size_t metadata_size;
+
+ if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
+ archive_entry_mac_metadata(a->entry,
+ &metadata_size) == NULL || metadata_size == 0)
+#endif
+#if ARCHIVE_ACL_LIBRICHACL
+ /*
+ * RichACLs are stored in an extended attribute.
+ * If we intend to extract extended attributes and have this
+ * attribute we skip extracting libarchive NFSv4 ACLs.
+ */
+ short extract_acls = 1;
+ if (a->flags & ARCHIVE_EXTRACT_XATTR && (
+ archive_entry_acl_types(a->entry) &
+ ARCHIVE_ENTRY_ACL_TYPE_NFS4)) {
+ const char *attr_name;
+ const void *attr_value;
+ size_t attr_size;
+ int i = archive_entry_xattr_reset(a->entry);
+ while (i--) {
+ archive_entry_xattr_next(a->entry, &attr_name,
+ &attr_value, &attr_size);
+ if (attr_name != NULL && attr_value != NULL &&
+ attr_size > 0 && strcmp(attr_name,
+ "trusted.richacl") == 0) {
+ extract_acls = 0;
+ break;
+ }
+ }
+ }
+ if (extract_acls)
+#endif
+#if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
+ {
+#endif
if (archive_entry_filetype(a->entry) == AE_IFDIR)
a->deferred |= TODO_ACLS;
else
a->todo |= TODO_ACLS;
+#if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
+ }
+#endif
}
if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) {
if (archive_entry_filetype(a->entry) == AE_IFDIR)
@@ -619,8 +664,21 @@ _archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
}
#endif
- if (a->flags & ARCHIVE_EXTRACT_XATTR)
+ if (a->flags & ARCHIVE_EXTRACT_XATTR) {
+#if ARCHIVE_XATTR_DARWIN
+ /*
+ * On MacOS, extended attributes get stored in mac_metadata,
+ * too. If we intend to extract mac_metadata and it is present
+ * we skip extracting extended attributes.
+ */
+ size_t metadata_size;
+
+ if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
+ archive_entry_mac_metadata(a->entry,
+ &metadata_size) == NULL || metadata_size == 0)
+#endif
a->todo |= TODO_XATTR;
+ }
if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
a->todo |= TODO_FFLAGS;
if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
@@ -1703,25 +1761,11 @@ _archive_write_disk_finish_entry(struct archive *_a)
*/
if (a->todo & TODO_ACLS) {
int r2;
-#ifdef HAVE_DARWIN_ACL
- /*
- * On Mac OS, platform ACLs are stored also in mac_metadata by
- * the operating system. If mac_metadata is present it takes
- * precedence and we skip extracting libarchive NFSv4 ACLs
- */
- const void *metadata;
- size_t metadata_size;
- metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
- if ((a->todo & TODO_MAC_METADATA) == 0 ||
- metadata == NULL || metadata_size == 0) {
-#endif
r2 = archive_write_disk_set_acls(&a->archive, a->fd,
archive_entry_pathname(a->entry),
- archive_entry_acl(a->entry));
+ archive_entry_acl(a->entry),
+ archive_entry_mode(a->entry));
if (r2 < ret) ret = r2;
-#ifdef HAVE_DARWIN_ACL
- }
-#endif
}
finish_metadata:
@@ -2293,13 +2337,8 @@ _archive_write_disk_close(struct archive *_a)
if (p->fixup & TODO_MODE_BASE)
chmod(p->name, p->mode);
if (p->fixup & TODO_ACLS)
-#ifdef HAVE_DARWIN_ACL
- if ((p->fixup & TODO_MAC_METADATA) == 0 ||
- p->mac_metadata == NULL ||
- p->mac_metadata_size == 0)
-#endif
- archive_write_disk_set_acls(&a->archive,
- -1, p->name, &p->acl);
+ archive_write_disk_set_acls(&a->archive, -1, p->name,
+ &p->acl, p->mode);
if (p->fixup & TODO_FFLAGS)
set_fflags_platform(a, -1, p->name,
p->mode, p->fflags_set, 0);
@@ -2467,7 +2506,7 @@ fsobj_error(int *a_eno, struct archive_string *a_estr,
if (a_eno)
*a_eno = err;
if (a_estr)
- archive_string_sprintf(a_estr, errstr, path);
+ archive_string_sprintf(a_estr, "%s%s", errstr, path);
}
/*
@@ -2573,7 +2612,7 @@ check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
* with the deep-directory editing.
*/
fsobj_error(a_eno, a_estr, errno,
- "Could not stat %s", path);
+ "Could not stat ", path);
res = ARCHIVE_FAILED;
break;
}
@@ -2582,7 +2621,7 @@ check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
if (chdir(head) != 0) {
tail[0] = c;
fsobj_error(a_eno, a_estr, errno,
- "Could not chdir %s", path);
+ "Could not chdir ", path);
res = (ARCHIVE_FATAL);
break;
}
@@ -2599,7 +2638,7 @@ check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
if (unlink(head)) {
tail[0] = c;
fsobj_error(a_eno, a_estr, errno,
- "Could not remove symlink %s",
+ "Could not remove symlink ",
path);
res = ARCHIVE_FAILED;
break;
@@ -2618,7 +2657,7 @@ check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
/*
if (!S_ISLNK(path)) {
fsobj_error(a_eno, a_estr, 0,
- "Removing symlink %s", path);
+ "Removing symlink ", path);
}
*/
/* Symlink gone. No more problem! */
@@ -2630,7 +2669,7 @@ check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
tail[0] = c;
fsobj_error(a_eno, a_estr, 0,
"Cannot remove intervening "
- "symlink %s", path);
+ "symlink ", path);
res = ARCHIVE_FAILED;
break;
}
@@ -2652,7 +2691,7 @@ check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
} else {
fsobj_error(a_eno, a_estr,
errno,
- "Could not stat %s", path);
+ "Could not stat ", path);
res = (ARCHIVE_FAILED);
break;
}
@@ -2661,7 +2700,7 @@ check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
tail[0] = c;
fsobj_error(a_eno, a_estr,
errno,
- "Could not chdir %s", path);
+ "Could not chdir ", path);
res = (ARCHIVE_FATAL);
break;
}
@@ -2674,14 +2713,14 @@ check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
tail[0] = c;
fsobj_error(a_eno, a_estr, 0,
"Cannot extract through "
- "symlink %s", path);
+ "symlink ", path);
res = ARCHIVE_FAILED;
break;
}
} else {
tail[0] = c;
fsobj_error(a_eno, a_estr, 0,
- "Cannot extract through symlink %s", path);
+ "Cannot extract through symlink ", path);
res = ARCHIVE_FAILED;
break;
}
@@ -4044,71 +4083,98 @@ skip_appledouble:
}
#endif
-#if HAVE_LSETXATTR || HAVE_LSETEA
+#if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX
/*
- * Restore extended attributes - Linux and AIX implementations:
+ * Restore extended attributes - Linux, Darwin and AIX implementations:
* AIX' ea interface is syntaxwise identical to the Linux xattr interface.
*/
static int
set_xattrs(struct archive_write_disk *a)
{
struct archive_entry *entry = a->entry;
- static int warning_done = 0;
+ struct archive_string errlist;
int ret = ARCHIVE_OK;
int i = archive_entry_xattr_reset(entry);
+ short fail = 0;
+
+ archive_string_init(&errlist);
while (i--) {
const char *name;
const void *value;
size_t size;
+ int e;
+
archive_entry_xattr_next(entry, &name, &value, &size);
- if (name != NULL &&
- strncmp(name, "xfsroot.", 8) != 0 &&
- strncmp(name, "system.", 7) != 0) {
- int e;
-#if HAVE_FSETXATTR
- if (a->fd >= 0)
- e = fsetxattr(a->fd, name, value, size, 0);
- else
-#elif HAVE_FSETEA
- if (a->fd >= 0)
- e = fsetea(a->fd, name, value, size, 0);
- else
+
+ if (name == NULL)
+ continue;
+#if ARCHIVE_XATTR_LINUX
+ /* Linux: quietly skip POSIX.1e ACL extended attributes */
+ if (strncmp(name, "system.", 7) == 0 &&
+ (strcmp(name + 7, "posix_acl_access") == 0 ||
+ strcmp(name + 7, "posix_acl_default") == 0))
+ continue;
+ if (strncmp(name, "trusted.SGI_", 12) == 0 &&
+ (strcmp(name + 12, "ACL_DEFAULT") == 0 ||
+ strcmp(name + 12, "ACL_FILE") == 0))
+ continue;
+
+ /* Linux: xfsroot namespace is obsolete and unsupported */
+ if (strncmp(name, "xfsroot.", 8) == 0) {
+ fail = 1;
+ archive_strcat(&errlist, name);
+ archive_strappend_char(&errlist, ' ');
+ continue;
+ }
#endif
- {
-#if HAVE_LSETXATTR
- e = lsetxattr(archive_entry_pathname(entry),
- name, value, size, 0);
-#elif HAVE_LSETEA
- e = lsetea(archive_entry_pathname(entry),
- name, value, size, 0);
+
+ if (a->fd >= 0) {
+#if ARCHIVE_XATTR_LINUX
+ e = fsetxattr(a->fd, name, value, size, 0);
+#elif ARCHIVE_XATTR_DARWIN
+ e = fsetxattr(a->fd, name, value, size, 0, 0);
+#elif ARCHIVE_XATTR_AIX
+ e = fsetea(a->fd, name, value, size, 0);
#endif
- }
- if (e == -1) {
- if (errno == ENOTSUP || errno == ENOSYS) {
- if (!warning_done) {
- warning_done = 1;
- archive_set_error(&a->archive,
- errno,
- "Cannot restore extended "
- "attributes on this file "
- "system");
- }
- } else
- archive_set_error(&a->archive, errno,
- "Failed to set extended attribute");
- ret = ARCHIVE_WARN;
- }
} else {
- archive_set_error(&a->archive,
- ARCHIVE_ERRNO_FILE_FORMAT,
- "Invalid extended attribute encountered");
+#if ARCHIVE_XATTR_LINUX
+ e = lsetxattr(archive_entry_pathname(entry),
+ name, value, size, 0);
+#elif ARCHIVE_XATTR_DARWIN
+ e = setxattr(archive_entry_pathname(entry),
+ name, value, size, 0, XATTR_NOFOLLOW);
+#elif ARCHIVE_XATTR_AIX
+ e = lsetea(archive_entry_pathname(entry),
+ name, value, size, 0);
+#endif
+ }
+ if (e == -1) {
ret = ARCHIVE_WARN;
+ archive_strcat(&errlist, name);
+ archive_strappend_char(&errlist, ' ');
+ if (errno != ENOTSUP && errno != ENOSYS)
+ fail = 1;
}
}
+
+ if (ret == ARCHIVE_WARN) {
+ if (fail && errlist.length > 0) {
+ errlist.length--;
+ errlist.s[errlist.length] = '\0';
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
+ "Cannot restore extended attributes: %s",
+ errlist.s);
+ } else
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
+ "Cannot restore extended "
+ "attributes on this file system.");
+ }
+
+ archive_string_free(&errlist);
return (ret);
}
-#elif HAVE_EXTATTR_SET_FILE && HAVE_DECL_EXTATTR_NAMESPACE_USER
+#elif ARCHIVE_XATTR_FREEBSD
/*
* Restore extended attributes - FreeBSD implementation
*/
@@ -4116,9 +4182,12 @@ static int
set_xattrs(struct archive_write_disk *a)
{
struct archive_entry *entry = a->entry;
- static int warning_done = 0;
+ struct archive_string errlist;
int ret = ARCHIVE_OK;
int i = archive_entry_xattr_reset(entry);
+ short fail = 0;
+
+ archive_string_init(&errlist);
while (i--) {
const char *name;
@@ -4134,46 +4203,47 @@ set_xattrs(struct archive_write_disk *a)
name += 5;
namespace = EXTATTR_NAMESPACE_USER;
} else {
- /* Warn about other extended attributes. */
- archive_set_error(&a->archive,
- ARCHIVE_ERRNO_FILE_FORMAT,
- "Can't restore extended attribute ``%s''",
- name);
+ /* Other namespaces are unsupported */
+ archive_strcat(&errlist, name);
+ archive_strappend_char(&errlist, ' ');
+ fail = 1;
ret = ARCHIVE_WARN;
continue;
}
- errno = 0;
-#if HAVE_EXTATTR_SET_FD
- if (a->fd >= 0)
+
+ if (a->fd >= 0) {
e = extattr_set_fd(a->fd, namespace, name,
value, size);
- else
-#endif
- /* TODO: should we use extattr_set_link() instead? */
- {
- e = extattr_set_file(
+ } else {
+ e = extattr_set_link(
archive_entry_pathname(entry), namespace,
name, value, size);
}
if (e != (int)size) {
- if (errno == ENOTSUP || errno == ENOSYS) {
- if (!warning_done) {
- warning_done = 1;
- archive_set_error(&a->archive,
- errno,
- "Cannot restore extended "
- "attributes on this file "
- "system");
- }
- } else {
- archive_set_error(&a->archive, errno,
- "Failed to set extended attribute");
- }
-
+ archive_strcat(&errlist, name);
+ archive_strappend_char(&errlist, ' ');
ret = ARCHIVE_WARN;
+ if (errno != ENOTSUP && errno != ENOSYS)
+ fail = 1;
}
}
}
+
+ if (ret == ARCHIVE_WARN) {
+ if (fail && errlist.length > 0) {
+ errlist.length--;
+ errlist.s[errlist.length] = '\0';
+
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
+ "Cannot restore extended attributes: %s",
+ errlist.s);
+ } else
+ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
+ "Cannot restore extended "
+ "attributes on this file system.");
+ }
+
+ archive_string_free(&errlist);
return (ret);
}
#else
@@ -4239,5 +4309,19 @@ older(struct stat *st, struct archive_entry *entry)
return (0);
}
+#ifndef ARCHIVE_ACL_SUPPORT
+int
+archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
+ struct archive_acl *abstract_acl, __LA_MODE_T mode)
+{
+ (void)a; /* UNUSED */
+ (void)fd; /* UNUSED */
+ (void)name; /* UNUSED */
+ (void)abstract_acl; /* UNUSED */
+ (void)mode; /* UNUSED */
+ return (ARCHIVE_OK);
+}
+#endif
+
#endif /* !_WIN32 || __CYGWIN__ */
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_disk_private.h b/Utilities/cmlibarchive/libarchive/archive_write_disk_private.h
index d84e7e1cd..b655dea2b 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_disk_private.h
+++ b/Utilities/cmlibarchive/libarchive/archive_write_disk_private.h
@@ -33,11 +33,13 @@
#ifndef ARCHIVE_WRITE_DISK_PRIVATE_H_INCLUDED
#define ARCHIVE_WRITE_DISK_PRIVATE_H_INCLUDED
+#include "archive_platform_acl.h"
#include "archive_acl_private.h"
+#include "archive_entry.h"
struct archive_write_disk;
-int
-archive_write_disk_set_acls(struct archive *, int /* fd */, const char * /* pathname */, struct archive_acl *);
+int archive_write_disk_set_acls(struct archive *, int, const char *,
+ struct archive_acl *, __LA_MODE_T);
#endif
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_finish_entry.3 b/Utilities/cmlibarchive/libarchive/archive_write_finish_entry.3
index c5ef69ebc..dc1b94b82 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_finish_entry.3
+++ b/Utilities/cmlibarchive/libarchive/archive_write_finish_entry.3
@@ -24,7 +24,7 @@
.\"
.\" $FreeBSD$
.\"
-.Dd February 2, 2012
+.Dd February 28, 2017
.Dt ARCHIVE_WRITE_FINISH_ENTRY 3
.Os
.Sh NAME
@@ -45,6 +45,9 @@ is called automatically by
and
.Fn archive_write_close
as needed.
+For
+.Tn archive_write_disk
+handles, this flushes pending file attribute changes like modification time.
.\" .Sh EXAMPLE
.Sh RETURN VALUES
This function returns
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_format.3 b/Utilities/cmlibarchive/libarchive/archive_write_format.3
index d4ba6abff..aaafb0a86 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_format.3
+++ b/Utilities/cmlibarchive/libarchive/archive_write_format.3
@@ -108,7 +108,6 @@ Streaming Archive Library (libarchive, -larchive)
These functions set the format that will be used for the archive.
.Pp
The library can write a variety of common archive formats.
-
.Bl -tag -width indent
.It Fn archive_write_set_format
Sets the format based on the format code (see
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format.c
index 744302d06..0f706231a 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format.c
@@ -38,7 +38,7 @@ __FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format.c 201168 2009-1
#include "archive_private.h"
/* A table that maps format codes to functions. */
-static
+static const
struct { int code; int (*setter)(struct archive *); } codes[] =
{
{ ARCHIVE_FORMAT_7ZIP, archive_write_set_format_7zip },
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_by_name.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_by_name.c
index a2ce7c6cd..86e8621ef 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_by_name.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_by_name.c
@@ -41,7 +41,7 @@ __FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_by_name.c 20116
#include "archive_private.h"
/* A table that maps names to functions. */
-static
+static const
struct { const char *name; int (*setter)(struct archive *); } names[] =
{
{ "7zip", archive_write_set_format_7zip },
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_filter_by_ext.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_filter_by_ext.c
index adec9b265..9fe21e454 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_filter_by_ext.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_filter_by_ext.c
@@ -42,7 +42,7 @@ __FBSDID("$FreeBSD: head/lib/libarchive/archive_write_set_format_by_name.c 20116
#include "archive_private.h"
/* A table that maps names to functions. */
-static
+static const
struct { const char *name; int (*format)(struct archive *); int (*filter)(struct archive *); } names[] =
{
{ ".7z", archive_write_set_format_7zip, archive_write_add_filter_none},
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_pax.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_pax.c
index 6a301ac2d..0eaf733cd 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_pax.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_pax.c
@@ -1196,8 +1196,12 @@ archive_write_pax_header(struct archive_write *a,
"GNU.sparse.major", 1);
add_pax_attr_int(&(pax->pax_header),
"GNU.sparse.minor", 0);
+ /*
+ * Make sure to store the original path, since
+ * truncation to ustar limit happened already.
+ */
add_pax_attr(&(pax->pax_header),
- "GNU.sparse.name", entry_name.s);
+ "GNU.sparse.name", path);
add_pax_attr_int(&(pax->pax_header),
"GNU.sparse.realsize",
archive_entry_size(entry_main));
@@ -1650,13 +1654,14 @@ build_pax_attribute_name(char *dest, const char *src)
* GNU PAX Format 1.0 requires the special name, which pattern is:
* <dir>/GNUSparseFile.<pid>/<original file name>
*
+ * Since reproducable archives are more important, use 0 as pid.
+ *
* This function is used for only Sparse file, a file type of which
* is regular file.
*/
static char *
build_gnu_sparse_name(char *dest, const char *src)
{
- char buff[64];
const char *p;
/* Handle the null filename case. */
@@ -1682,15 +1687,9 @@ build_gnu_sparse_name(char *dest, const char *src)
break;
}
-#if HAVE_GETPID && 0 /* Disable this as pax attribute name. */
- sprintf(buff, "GNUSparseFile.%d", getpid());
-#else
- /* If the platform can't fetch the pid, don't include it. */
- strcpy(buff, "GNUSparseFile");
-#endif
/* General case: build a ustar-compatible name adding
* "/GNUSparseFile/". */
- build_ustar_entry_name(dest, src, p - src, buff);
+ build_ustar_entry_name(dest, src, p - src, "GNUSparseFile.0");
return (dest);
}
diff --git a/Utilities/cmlibarchive/libarchive/archive_write_set_format_warc.c b/Utilities/cmlibarchive/libarchive/archive_write_set_format_warc.c
index 8b6daf942..edad072cf 100644
--- a/Utilities/cmlibarchive/libarchive/archive_write_set_format_warc.c
+++ b/Utilities/cmlibarchive/libarchive/archive_write_set_format_warc.c
@@ -354,7 +354,7 @@ static ssize_t
_popul_ehdr(struct archive_string *tgt, size_t tsz, warc_essential_hdr_t hdr)
{
static const char _ver[] = "WARC/1.0\r\n";
- static const char *_typ[LAST_WT] = {
+ static const char * const _typ[LAST_WT] = {
NULL, "warcinfo", "metadata", "resource", NULL
};
char std_uuid[48U];
diff --git a/Utilities/cmlibarchive/libarchive/config_freebsd.h b/Utilities/cmlibarchive/libarchive/config_freebsd.h
index 215e886be..be25258f9 100644
--- a/Utilities/cmlibarchive/libarchive/config_freebsd.h
+++ b/Utilities/cmlibarchive/libarchive/config_freebsd.h
@@ -22,141 +22,238 @@
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
- * $FreeBSD: head/lib/libarchive/config_freebsd.h 201079 2009-12-28 02:01:42Z kientzle $
+ * $FreeBSD$
*/
-/* FreeBSD 5.0 and later have ACL and extattr support. */
+#include <osreldate.h>
+
+/* FreeBSD 5.0 and later has ACL and extattr support. */
#if __FreeBSD__ > 4
-#define HAVE_ACL_CREATE_ENTRY 1
-#define HAVE_ACL_GET_FD_NP 1
-#define HAVE_ACL_GET_LINK_NP 1
-#define HAVE_ACL_GET_PERM_NP 1
-#define HAVE_ACL_INIT 1
-#define HAVE_ACL_SET_FD 1
-#define HAVE_ACL_SET_FD_NP 1
-#define HAVE_ACL_SET_FILE 1
-#define HAVE_ACL_USER 1
-#define HAVE_EXTATTR_GET_FILE 1
-#define HAVE_EXTATTR_LIST_FILE 1
-#define HAVE_EXTATTR_SET_FD 1
-#define HAVE_EXTATTR_SET_FILE 1
-#define HAVE_STRUCT_XVFSCONF 1
-#define HAVE_SYS_ACL_H 1
-#define HAVE_SYS_EXTATTR_H 1
-#endif
+#define ARCHIVE_ACL_FREEBSD 1
+#define HAVE_ACL_GET_PERM_NP 1
+#define HAVE_ARC4RANDOM_BUF 1
+#define HAVE_EXTATTR_GET_FILE 1
+#define HAVE_EXTATTR_LIST_FILE 1
+#define HAVE_EXTATTR_SET_FD 1
+#define HAVE_EXTATTR_SET_FILE 1
+#define HAVE_STRUCT_XVFSCONF 1
+#define HAVE_SYS_ACL_H 1
+#define HAVE_SYS_EXTATTR_H 1
+#if __FreeBSD__ > 7
+/* FreeBSD 8.0 and later has NFSv4 ACL support */
+#define ARCHIVE_ACL_FREEBSD_NFS4 1
+#define HAVE_ACL_GET_LINK_NP 1
+#define HAVE_ACL_IS_TRIVIAL_NP 1
+#define HAVE_ACL_SET_LINK_NP 1
+#endif /* __FreeBSD__ > 7 */
+#endif /* __FreeBSD__ > 4 */
#ifdef WITH_OPENSSL
-#define HAVE_OPENSSL_MD5_H 1
-#define HAVE_OPENSSL_RIPEMD_H 1
-#define HAVE_OPENSSL_SHA_H 1
-#define HAVE_SHA384 1
-#define HAVE_SHA512 1
+#define HAVE_LIBCRYPTO 1
+#define HAVE_OPENSSL_EVP_H 1
+#define HAVE_OPENSSL_MD5_H 1
+#define HAVE_OPENSSL_RIPEMD_H 1
+#define HAVE_OPENSSL_SHA_H 1
+#define HAVE_OPENSSL_SHA256_INIT 1
+#define HAVE_OPENSSL_SHA384_INIT 1
+#define HAVE_OPENSSL_SHA512_INIT 1
+#define HAVE_PKCS5_PBKDF2_HMAC_SHA1 1
+#define HAVE_SHA256 1
+#define HAVE_SHA384 1
+#define HAVE_SHA512 1
+#else
+#define HAVE_LIBMD 1
+#define HAVE_MD5_H 1
+#define HAVE_MD5INIT 1
+#define HAVE_RIPEMD_H 1
+#define HAVE_SHA_H 1
+#define HAVE_SHA1 1
+#define HAVE_SHA1_INIT 1
+#define HAVE_SHA256 1
+#define HAVE_SHA256_H 1
+#define HAVE_SHA256_INIT 1
+#define HAVE_SHA512 1
+#define HAVE_SHA512_H 1
+#define HAVE_SHA512_INIT 1
#endif
-#define HAVE_BSDXML_H 1
-#define HAVE_BZLIB_H 1
-#define HAVE_CHFLAGS 1
-#define HAVE_CHOWN 1
-#define HAVE_DECL_INT64_MAX 1
-#define HAVE_DECL_INT64_MIN 1
-#define HAVE_DECL_SIZE_MAX 1
-#define HAVE_DECL_SSIZE_MAX 1
-#define HAVE_DECL_STRERROR_R 1
-#define HAVE_DECL_UINT32_MAX 1
-#define HAVE_DECL_UINT64_MAX 1
-#define HAVE_DIRENT_H 1
-#define HAVE_EFTYPE 1
-#define HAVE_EILSEQ 1
-#define HAVE_ERRNO_H 1
-#define HAVE_FCHDIR 1
-#define HAVE_FCHFLAGS 1
-#define HAVE_FCHMOD 1
-#define HAVE_FCHOWN 1
-#define HAVE_FCNTL 1
-#define HAVE_FCNTL_H 1
-#define HAVE_FSEEKO 1
-#define HAVE_FSTAT 1
-#define HAVE_FTRUNCATE 1
-#define HAVE_FUTIMES 1
-#define HAVE_GETEUID 1
-#define HAVE_GETGRGID_R 1
-#define HAVE_GETPID 1
-#define HAVE_GETPWUID_R 1
-#define HAVE_GRP_H 1
-#define HAVE_INTTYPES_H 1
-#define HAVE_LCHFLAGS 1
-#define HAVE_LCHMOD 1
-#define HAVE_LCHOWN 1
-#define HAVE_LIMITS_H 1
-#define HAVE_LINK 1
-#define HAVE_LSTAT 1
-#define HAVE_LUTIMES 1
-#define HAVE_MALLOC 1
-#define HAVE_MD5 1
-#define HAVE_MD5_H 1
-#define HAVE_MEMMOVE 1
-#define HAVE_MKDIR 1
-#define HAVE_MKFIFO 1
-#define HAVE_MKNOD 1
-#define HAVE_PIPE 1
-#define HAVE_POLL 1
-#define HAVE_POLL_H 1
-#define HAVE_PWD_H 1
-#define HAVE_READLINK 1
-#define HAVE_RMD160 1
-#define HAVE_SELECT 1
-#define HAVE_SETENV 1
-#define HAVE_SHA_H 1
-#define HAVE_SHA1 1
-#define HAVE_SHA256 1
-#define HAVE_SHA256_H 1
-#define HAVE_SIGNAL_H 1
-#define HAVE_STDINT_H 1
-#define HAVE_STDLIB_H 1
-#define HAVE_STRCHR 1
-#define HAVE_STRDUP 1
-#define HAVE_STRERROR 1
-#define HAVE_STRERROR_R 1
-#define HAVE_STRINGS_H 1
-#define HAVE_STRING_H 1
-#define HAVE_STRRCHR 1
-#define HAVE_STRUCT_STAT_ST_BLKSIZE 1
-#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1
-#define HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC 1
-#define HAVE_STRUCT_STAT_ST_FLAGS 1
-#define HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC 1
-#define HAVE_STRUCT_TM_TM_GMTOFF 1
-#define HAVE_SYMLINK 1
-#define HAVE_SYS_CDEFS_H 1
-#define HAVE_SYS_IOCTL_H 1
-#define HAVE_SYS_MOUNT_H 1
-#define HAVE_SYS_PARAM_H 1
-#define HAVE_SYS_SELECT_H 1
-#define HAVE_SYS_STAT_H 1
-#define HAVE_SYS_TIME_H 1
-#define HAVE_SYS_TYPES_H 1
-#undef HAVE_SYS_UTIME_H
-#define HAVE_SYS_UTSNAME_H 1
-#define HAVE_SYS_WAIT_H 1
-#define HAVE_TIMEGM 1
-#define HAVE_TZSET 1
-#define HAVE_UNISTD_H 1
-#define HAVE_UNSETENV 1
-#define HAVE_UTIME 1
-#define HAVE_UTIMES 1
-#define HAVE_UTIME_H 1
-#define HAVE_VFORK 1
-#define HAVE_WCHAR_H 1
-#define HAVE_WCSCPY 1
-#define HAVE_WCSLEN 1
-#define HAVE_WCTOMB 1
-#define HAVE_WMEMCMP 1
-#define HAVE_WMEMCPY 1
-#define HAVE_ZLIB_H 1
-#define TIME_WITH_SYS_TIME 1
+#define HAVE_BSDXML_H 1
+#define HAVE_BZLIB_H 1
+#define HAVE_CHFLAGS 1
+#define HAVE_CHOWN 1
+#define HAVE_CHROOT 1
+#define HAVE_CTIME_R 1
+#define HAVE_CTYPE_H 1
+#define HAVE_DECL_EXTATTR_NAMESPACE_USER 1
+#define HAVE_DECL_INT32_MAX 1
+#define HAVE_DECL_INT32_MIN 1
+#define HAVE_DECL_INT64_MAX 1
+#define HAVE_DECL_INT64_MIN 1
+#define HAVE_DECL_INTMAX_MAX 1
+#define HAVE_DECL_INTMAX_MIN 1
+#define HAVE_DECL_SIZE_MAX 1
+#define HAVE_DECL_SSIZE_MAX 1
+#define HAVE_DECL_STRERROR_R 1
+#define HAVE_DECL_UINT32_MAX 1
+#define HAVE_DECL_UINT64_MAX 1
+#define HAVE_DECL_UINTMAX_MAX 1
+#define HAVE_DIRENT_H 1
+#define HAVE_DLFCN_H 1
+#define HAVE_D_MD_ORDER 1
+#define HAVE_EFTYPE 1
+#define HAVE_EILSEQ 1
+#define HAVE_ERRNO_H 1
+#define HAVE_FCHDIR 1
+#define HAVE_FCHFLAGS 1
+#define HAVE_FCHMOD 1
+#define HAVE_FCHOWN 1
+#define HAVE_FCNTL 1
+#define HAVE_FCNTL_H 1
+#define HAVE_FDOPENDIR 1
+#define HAVE_FORK 1
+#define HAVE_FSEEKO 1
+#define HAVE_FSTAT 1
+#define HAVE_FSTATAT 1
+#define HAVE_FSTATFS 1
+#define HAVE_FSTATVFS 1
+#define HAVE_FTRUNCATE 1
+#define HAVE_FUTIMES 1
+#define HAVE_FUTIMESAT 1
+#define HAVE_GETEUID 1
+#define HAVE_GETGRGID_R 1
+#define HAVE_GETGRNAM_R 1
+#define HAVE_GETPID 1
+#define HAVE_GETPWNAM_R 1
+#define HAVE_GETPWUID_R 1
+#define HAVE_GETVFSBYNAME 1
+#define HAVE_GMTIME_R 1
+#define HAVE_GRP_H 1
+#define HAVE_INTMAX_T 1
+#define HAVE_INTTYPES_H 1
+#define HAVE_LANGINFO_H 1
+#define HAVE_LCHFLAGS 1
+#define HAVE_LCHMOD 1
+#define HAVE_LCHOWN 1
+#define HAVE_LIBZ 1
+#define HAVE_LIMITS_H 1
+#define HAVE_LINK 1
+#define HAVE_LOCALE_H 1
+#define HAVE_LOCALTIME_R 1
+#define HAVE_LONG_LONG_INT 1
+#define HAVE_LSTAT 1
+#define HAVE_LUTIMES 1
+#define HAVE_MBRTOWC 1
+#define HAVE_MEMMOVE 1
+#define HAVE_MEMORY_H 1
+#define HAVE_MEMSET 1
+#define HAVE_MKDIR 1
+#define HAVE_MKFIFO 1
+#define HAVE_MKNOD 1
+#define HAVE_MKSTEMP 1
+#define HAVE_NL_LANGINFO 1
+#define HAVE_OPENAT 1
+#define HAVE_PATHS_H 1
+#define HAVE_PIPE 1
+#define HAVE_POLL 1
+#define HAVE_POLL_H 1
+#define HAVE_POSIX_SPAWNP 1
+#define HAVE_PTHREAD_H 1
+#define HAVE_PWD_H 1
+#define HAVE_READDIR_R 1
+#define HAVE_READLINK 1
+#define HAVE_READLINKAT 1
+#define HAVE_READPASSPHRASE 1
+#define HAVE_READPASSPHRASE_H 1
+#define HAVE_REGEX_H 1
+#define HAVE_SELECT 1
+#define HAVE_SETENV 1
+#define HAVE_SETLOCALE 1
+#define HAVE_SIGACTION 1
+#define HAVE_SIGNAL_H 1
+#define HAVE_SPAWN_H 1
+#define HAVE_STATFS 1
+#define HAVE_STATVFS 1
+#define HAVE_STDARG_H 1
+#define HAVE_STDINT_H 1
+#define HAVE_STDLIB_H 1
+#define HAVE_STRCHR 1
+#define HAVE_STRDUP 1
+#define HAVE_STRERROR 1
+#define HAVE_STRERROR_R 1
+#define HAVE_STRFTIME 1
+#define HAVE_STRINGS_H 1
+#define HAVE_STRING_H 1
+#define HAVE_STRRCHR 1
+#define HAVE_STRUCT_STATFS_F_NAMEMAX 1
+#define HAVE_STRUCT_STAT_ST_BIRTHTIME 1
+#define HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC_TV_NSEC 1
+#define HAVE_STRUCT_STAT_ST_BLKSIZE 1
+#define HAVE_STRUCT_STAT_ST_FLAGS 1
+#define HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC 1
+#define HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC 1
+#define HAVE_STRUCT_TM_TM_GMTOFF 1
+#define HAVE_SYMLINK 1
+#define HAVE_SYS_CDEFS_H 1
+#define HAVE_SYS_IOCTL_H 1
+#define HAVE_SYS_MOUNT_H 1
+#define HAVE_SYS_PARAM_H 1
+#define HAVE_SYS_POLL_H 1
+#define HAVE_SYS_SELECT_H 1
+#define HAVE_SYS_STATVFS_H 1
+#define HAVE_SYS_STAT_H 1
+#define HAVE_SYS_TIME_H 1
+#define HAVE_SYS_TYPES_H 1
+#define HAVE_SYS_UTSNAME_H 1
+#define HAVE_SYS_WAIT_H 1
+#define HAVE_TIMEGM 1
+#define HAVE_TIME_H 1
+#define HAVE_TZSET 1
+#define HAVE_UINTMAX_T 1
+#define HAVE_UNISTD_H 1
+#define HAVE_UNSETENV 1
+#define HAVE_UNSIGNED_LONG_LONG 1
+#define HAVE_UNSIGNED_LONG_LONG_INT 1
+#define HAVE_UTIME 1
+#define HAVE_UTIMES 1
+#define HAVE_UTIME_H 1
+#define HAVE_VFORK 1
+#define HAVE_VPRINTF 1
+#define HAVE_WCHAR_H 1
+#define HAVE_WCHAR_T 1
+#define HAVE_WCRTOMB 1
+#define HAVE_WCSCMP 1
+#define HAVE_WCSCPY 1
+#define HAVE_WCSLEN 1
+#define HAVE_WCTOMB 1
+#define HAVE_WCTYPE_H 1
+#define HAVE_WMEMCMP 1
+#define HAVE_WMEMCPY 1
+#define HAVE_WMEMMOVE 1
+#define HAVE_ZLIB_H 1
+#define TIME_WITH_SYS_TIME 1
+
+#if __FreeBSD_version >= 1100056
+#define HAVE_FUTIMENS 1
+#define HAVE_UTIMENSAT 1
+#endif
/* FreeBSD 4 and earlier lack intmax_t/uintmax_t */
#if __FreeBSD__ < 5
-#define intmax_t int64_t
-#define uintmax_t uint64_t
+#define intmax_t int64_t
+#define uintmax_t uint64_t
+#endif
+
+/* FreeBSD defines for archive_hash.h */
+#ifdef WITH_OPENSSL
+#define ARCHIVE_CRYPTO_MD5_OPENSSL 1
+#define ARCHIVE_CRYPTO_RMD160_OPENSSL 1
+#define ARCHIVE_CRYPTO_SHA1_OPENSSL
+#define ARCHIVE_CRYPTO_SHA256_OPENSSL 1
+#define ARCHIVE_CRYPTO_SHA384_OPENSSL 1
+#define ARCHIVE_CRYPTO_SHA512_OPENSSL 1
+#else
+#define ARCHIVE_CRYPTO_MD5_LIBMD 1
+#define ARCHIVE_CRYPTO_SHA1_LIBMD 1
+#define ARCHIVE_CRYPTO_SHA256_LIBMD 1
+#define ARCHIVE_CRYPTO_SHA512_LIBMD 1
#endif
diff --git a/Utilities/cmlibarchive/libarchive/libarchive_changes.3 b/Utilities/cmlibarchive/libarchive/libarchive_changes.3
index 881a67cdd..adc87febd 100644
--- a/Utilities/cmlibarchive/libarchive/libarchive_changes.3
+++ b/Utilities/cmlibarchive/libarchive/libarchive_changes.3
@@ -28,6 +28,7 @@
.Dt LIBARCHIVE_CHANGES 3
.Os
.Sh NAME
+.Nm libarchive_changes
.Nd changes in libarchive interface
.\"
.Sh CHANGES IN LIBARCHIVE 3
diff --git a/Utilities/cmlibarchive/libarchive/mtree.5 b/Utilities/cmlibarchive/libarchive/mtree.5
index 16c8abec4..e607e4a81 100644
--- a/Utilities/cmlibarchive/libarchive/mtree.5
+++ b/Utilities/cmlibarchive/libarchive/mtree.5
@@ -48,7 +48,7 @@ Leading whitespace is always ignored.
.Pp
When encoding file or pathnames, any backslash character or
character outside of the 95 printable ASCII characters must be
-encoded as a a backslash followed by three
+encoded as a backslash followed by three
octal digits.
When reading mtree files, any appearance of a backslash
followed by three octal digits should be converted into the
diff --git a/Utilities/cmlibarchive/libarchive/xxhash.c b/Utilities/cmlibarchive/libarchive/xxhash.c
index 6f5ba52fa..70750bae0 100644
--- a/Utilities/cmlibarchive/libarchive/xxhash.c
+++ b/Utilities/cmlibarchive/libarchive/xxhash.c
@@ -141,13 +141,19 @@ typedef struct _U32_S { U32 v; } _PACKED U32_S;
# pragma pack(pop)
#endif
-#define A32(x) (((const U32_S *)(x))->v)
-
/****************************************
** Compiler-specific Functions and Macros
*****************************************/
-#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+#define GCC_VERSION ((__GNUC__-0) * 100 + (__GNUC_MINOR__ - 0))
+
+#if GCC_VERSION >= 409
+__attribute__((__no_sanitize_undefined__))
+#endif
+static inline U32 A32(const void * x)
+{
+ return (((const U32_S *)(x))->v);
+}
/* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */
#if defined(_MSC_VER)
diff --git a/Utilities/cmliblzma/.gitattributes b/Utilities/cmliblzma/.gitattributes
deleted file mode 100644
index 562b12e16..000000000
--- a/Utilities/cmliblzma/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -whitespace
diff --git a/Utilities/cmlibrhash/.gitattributes b/Utilities/cmlibrhash/.gitattributes
deleted file mode 100644
index 562b12e16..000000000
--- a/Utilities/cmlibrhash/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -whitespace
diff --git a/Utilities/cmlibuv/.gitattributes b/Utilities/cmlibuv/.gitattributes
deleted file mode 100644
index 562b12e16..000000000
--- a/Utilities/cmlibuv/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -whitespace
diff --git a/Utilities/cmlibuv/include/uv-unix.h b/Utilities/cmlibuv/include/uv-unix.h
index d7754509b..ff59bcba0 100644
--- a/Utilities/cmlibuv/include/uv-unix.h
+++ b/Utilities/cmlibuv/include/uv-unix.h
@@ -44,7 +44,9 @@
#include "uv-threadpool.h"
-#if defined(__linux__)
+#ifdef CMAKE_BOOTSTRAP
+# include "uv-posix.h"
+#elif defined(__linux__)
# include "uv-linux.h"
#elif defined (__MVS__)
# include "uv-os390.h"
@@ -124,6 +126,17 @@ typedef int uv_file;
typedef int uv_os_sock_t;
typedef int uv_os_fd_t;
+#ifdef CMAKE_BOOTSTRAP
+#define UV_ONCE_INIT 0
+typedef int uv_once_t;
+typedef int uv_thread_t;
+typedef int uv_mutex_t;
+typedef int uv_rwlock_t;
+typedef int uv_sem_t;
+typedef int uv_cond_t;
+typedef int uv_key_t;
+typedef int uv_barrier_t;
+#else
#define UV_ONCE_INIT PTHREAD_ONCE_INIT
typedef pthread_once_t uv_once_t;
@@ -134,6 +147,7 @@ typedef UV_PLATFORM_SEM_T uv_sem_t;
typedef pthread_cond_t uv_cond_t;
typedef pthread_key_t uv_key_t;
typedef pthread_barrier_t uv_barrier_t;
+#endif
/* Platform-specific definitions for uv_spawn support. */
diff --git a/Utilities/cmlibuv/src/unix/cmake-bootstrap.c b/Utilities/cmlibuv/src/unix/cmake-bootstrap.c
new file mode 100644
index 000000000..4f32d03bc
--- /dev/null
+++ b/Utilities/cmlibuv/src/unix/cmake-bootstrap.c
@@ -0,0 +1,139 @@
+#include "uv.h"
+#include "internal.h"
+
+int uv__tcp_nodelay(int fd, int on) {
+ errno = EINVAL;
+ return -1;
+}
+
+int uv__tcp_keepalive(int fd, int on, unsigned int delay) {
+ errno = EINVAL;
+ return -1;
+}
+
+int uv_tcp_listen(uv_tcp_t* tcp, int backlog, uv_connection_cb cb) {
+ return -EINVAL;
+}
+
+int uv_udp_open(uv_udp_t* handle, uv_os_sock_t sock) {
+ return -EINVAL;
+}
+
+void uv__tcp_close(uv_tcp_t* handle) {
+}
+
+void uv__udp_close(uv_udp_t* handle) {
+}
+
+void uv__udp_finish_close(uv_udp_t* handle) {
+}
+
+void uv__fs_poll_close(uv_fs_poll_t* handle) {
+}
+
+int uv_async_init(uv_loop_t* loop, uv_async_t* handle, uv_async_cb async_cb) {
+ return 0;
+}
+
+void uv__async_close(uv_async_t* handle) {
+}
+
+int uv__async_fork(uv_loop_t* loop) {
+ return 0;
+}
+
+void uv__async_stop(uv_loop_t* loop) {
+}
+
+void uv__work_submit(uv_loop_t* loop, struct uv__work* w,
+ void (*work)(struct uv__work* w),
+ void (*done)(struct uv__work* w, int status)) {
+ abort();
+}
+
+void uv__work_done(uv_async_t* handle) {
+}
+
+int uv__pthread_atfork(void (*prepare)(void), void (*parent)(void),
+ void (*child)(void)) {
+ return 0;
+}
+
+int uv__pthread_sigmask(int how, const sigset_t* set, sigset_t* oset) {
+ return 0;
+}
+
+int uv_mutex_init(uv_mutex_t* mutex) {
+ return 0;
+}
+
+void uv_mutex_destroy(uv_mutex_t* mutex) {
+}
+
+void uv_mutex_lock(uv_mutex_t* mutex) {
+}
+
+void uv_mutex_unlock(uv_mutex_t* mutex) {
+}
+
+int uv_rwlock_init(uv_rwlock_t* rwlock) {
+ return 0;
+}
+
+void uv_rwlock_destroy(uv_rwlock_t* rwlock) {
+}
+
+void uv_rwlock_wrlock(uv_rwlock_t* rwlock) {
+}
+
+void uv_rwlock_wrunlock(uv_rwlock_t* rwlock) {
+}
+
+void uv_rwlock_rdlock(uv_rwlock_t* rwlock) {
+}
+
+void uv_rwlock_rdunlock(uv_rwlock_t* rwlock) {
+}
+
+void uv_once(uv_once_t* guard, void (*callback)(void)) {
+ if (*guard) {
+ return;
+ }
+ *guard = 1;
+ callback();
+}
+
+#if defined(__linux__)
+int uv__accept4(int fd, struct sockaddr* addr, socklen_t* addrlen, int flags) {
+ errno = ENOSYS;
+ return -1;
+}
+
+int uv__dup3(int oldfd, int newfd, int flags) {
+ errno = ENOSYS;
+ return -1;
+}
+
+int uv__pipe2(int pipefd[2], int flags) {
+ errno = ENOSYS;
+ return -1;
+}
+
+ssize_t uv__preadv(int fd, const struct iovec *iov, int iovcnt,
+ int64_t offset) {
+ errno = ENOSYS;
+ return -1;
+}
+
+ssize_t uv__pwritev(int fd, const struct iovec *iov, int iovcnt,
+ int64_t offset) {
+ errno = ENOSYS;
+ return -1;
+}
+
+int uv__utimesat(int dirfd, const char* path, const struct timespec times[2],
+ int flags) {
+ errno = ENOSYS;
+ return -1;
+}
+#endif
diff --git a/Utilities/cmlibuv/src/unix/fs.c b/Utilities/cmlibuv/src/unix/fs.c
index 8a4ba7a2f..82c91efb2 100644
--- a/Utilities/cmlibuv/src/unix/fs.c
+++ b/Utilities/cmlibuv/src/unix/fs.c
@@ -244,7 +244,7 @@ skip:
#endif
}
-#if defined(__sun) && _XOPEN_SOURCE < 600
+#if defined(__sun) && (_XOPEN_SOURCE < 600 || defined(CMAKE_BOOTSTRAP))
static char* uv__mkdtemp(char *template)
{
if (!mktemp(template) || mkdir(template, 0700))
diff --git a/Utilities/cmlibuv/src/unix/internal.h b/Utilities/cmlibuv/src/unix/internal.h
index 2e3afa6c8..e9f790850 100644
--- a/Utilities/cmlibuv/src/unix/internal.h
+++ b/Utilities/cmlibuv/src/unix/internal.h
@@ -59,7 +59,17 @@
# include <AvailabilityMacros.h>
#endif
-#if defined(__ANDROID__)
+#if defined(CMAKE_BOOTSTRAP)
+# undef pthread_atfork
+# define pthread_atfork(prepare, parent, child) \
+ uv__pthread_atfork(prepare, parent, child)
+int uv__pthread_atfork(void (*prepare)(void), void (*parent)(void),
+ void (*child)(void));
+# undef pthread_sigmask
+# define pthread_sigmask(how, set, oldset) \
+ uv__pthread_sigmask(how, set, oldset)
+int uv__pthread_sigmask(int how, const sigset_t* set, sigset_t* oset);
+#elif defined(__ANDROID__)
int uv__pthread_sigmask(int how, const sigset_t* set, sigset_t* oset);
# ifdef pthread_sigmask
# undef pthread_sigmask
@@ -261,7 +271,7 @@ FILE* uv__open_file(const char* path);
int uv__getpwuid_r(uv_passwd_t* pwd);
-#if defined(__APPLE__)
+#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP)
int uv___stream_fd(const uv_stream_t* handle);
#define uv__stream_fd(handle) (uv___stream_fd((const uv_stream_t*) (handle)))
#else
diff --git a/Utilities/cmlibuv/src/unix/pipe.c b/Utilities/cmlibuv/src/unix/pipe.c
index 7ba1bf879..e3d436d7c 100644
--- a/Utilities/cmlibuv/src/unix/pipe.c
+++ b/Utilities/cmlibuv/src/unix/pipe.c
@@ -136,7 +136,7 @@ int uv_pipe_open(uv_pipe_t* handle, uv_file fd) {
if (err)
return err;
-#if defined(__APPLE__)
+#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP)
err = uv__stream_try_select((uv_stream_t*) handle, &fd);
if (err)
return err;
diff --git a/Utilities/cmlibuv/src/unix/posix-hrtime.c b/Utilities/cmlibuv/src/unix/posix-hrtime.c
index 323dfc203..a2642500e 100644
--- a/Utilities/cmlibuv/src/unix/posix-hrtime.c
+++ b/Utilities/cmlibuv/src/unix/posix-hrtime.c
@@ -22,6 +22,29 @@
#include "uv.h"
#include "internal.h"
+#if defined(__APPLE__)
+/* Special case for CMake bootstrap: no clock_gettime on macOS < 10.12 */
+
+#ifndef CMAKE_BOOTSTRAP
+#error "This code path meant only for use during CMake bootstrap."
+#endif
+
+#include <mach/mach.h>
+#include <mach/mach_time.h>
+
+uint64_t uv__hrtime(uv_clocktype_t type) {
+ static mach_timebase_info_data_t info;
+
+ if ((ACCESS_ONCE(uint32_t, info.numer) == 0 ||
+ ACCESS_ONCE(uint32_t, info.denom) == 0) &&
+ mach_timebase_info(&info) != KERN_SUCCESS)
+ abort();
+
+ return mach_absolute_time() * info.numer / info.denom;
+}
+
+#else
+
#include <stdint.h>
#include <time.h>
@@ -33,3 +56,5 @@ uint64_t uv__hrtime(uv_clocktype_t type) {
clock_gettime(CLOCK_MONOTONIC, &ts);
return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec);
}
+
+#endif
diff --git a/Utilities/cmlibuv/src/unix/stream.c b/Utilities/cmlibuv/src/unix/stream.c
index 7b23d16ec..3857bc875 100644
--- a/Utilities/cmlibuv/src/unix/stream.c
+++ b/Utilities/cmlibuv/src/unix/stream.c
@@ -98,7 +98,7 @@ void uv__stream_init(uv_loop_t* loop,
loop->emfile_fd = err;
}
-#if defined(__APPLE__)
+#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP)
stream->select = NULL;
#endif /* defined(__APPLE_) */
@@ -107,7 +107,7 @@ void uv__stream_init(uv_loop_t* loop,
static void uv__stream_osx_interrupt_select(uv_stream_t* stream) {
-#if defined(__APPLE__)
+#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP)
/* Notify select() thread about state change */
uv__stream_select_t* s;
int r;
@@ -131,7 +131,7 @@ static void uv__stream_osx_interrupt_select(uv_stream_t* stream) {
}
-#if defined(__APPLE__)
+#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP)
static void uv__stream_osx_select(void* arg) {
uv_stream_t* stream;
uv__stream_select_t* s;
@@ -1598,7 +1598,7 @@ int uv_is_writable(const uv_stream_t* stream) {
}
-#if defined(__APPLE__)
+#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP)
int uv___stream_fd(const uv_stream_t* handle) {
const uv__stream_select_t* s;
@@ -1619,7 +1619,7 @@ void uv__stream_close(uv_stream_t* handle) {
unsigned int i;
uv__stream_queued_fds_t* queued_fds;
-#if defined(__APPLE__)
+#if defined(__APPLE__) && !defined(CMAKE_BOOTSTRAP)
/* Terminate select loop first */
if (handle->select != NULL) {
uv__stream_select_t* s;
diff --git a/Utilities/cmlibuv/src/uv-common.c b/Utilities/cmlibuv/src/uv-common.c
index bc7d1379d..fcb910f5f 100644
--- a/Utilities/cmlibuv/src/uv-common.c
+++ b/Utilities/cmlibuv/src/uv-common.c
@@ -175,6 +175,7 @@ const char* uv_strerror(int err) {
}
#undef UV_STRERROR_GEN
+#if !defined(CMAKE_BOOTSTRAP) || defined(_WIN32)
int uv_ip4_addr(const char* ip, int port, struct sockaddr_in* addr) {
memset(addr, 0, sizeof(*addr));
@@ -343,6 +344,7 @@ int uv_udp_recv_stop(uv_udp_t* handle) {
return uv__udp_recv_stop(handle);
}
+#endif
void uv_walk(uv_loop_t* loop, uv_walk_cb walk_cb, void* arg) {
QUEUE queue;
diff --git a/Utilities/cmvssetup/.gitattributes b/Utilities/cmvssetup/.gitattributes
deleted file mode 100644
index 562b12e16..000000000
--- a/Utilities/cmvssetup/.gitattributes
+++ /dev/null
@@ -1 +0,0 @@
-* -whitespace
diff --git a/bootstrap b/bootstrap
index 767413082..47f7e769f 100755
--- a/bootstrap
+++ b/bootstrap
@@ -9,26 +9,22 @@ die() {
# Compile flag extraction function.
cmake_extract_standard_flags()
{
- cd "${cmake_source_dir}/Modules/Compiler/"
- for file in ${1:-*}-${2}.cmake; do
- cat "${file}" \
- | sed -n "s/ *set *( *CMAKE_${2}${3}_EXTENSION_COMPILE_OPTION *\"\{0,1\}\([^\")]*\).*/\1/p" \
- | tr ';' ' '
- done
+ sed -n "s/ *set *( *CMAKE_${2}${3}_EXTENSION_COMPILE_OPTION *\"\{0,1\}\([^\")]*\).*/\1/p" \
+ "${cmake_source_dir}/Modules/Compiler/"${1:-*}-${2}.cmake 2>/dev/null | tr ';' ' '
}
# Version number extraction function.
cmake_version_component()
{
- cat "${cmake_source_dir}/Source/CMakeVersion.cmake" | sed -n "
+ sed -n "
/^set(CMake_VERSION_${1}/ {s/set(CMake_VERSION_${1} *\([0-9]*\))/\1/;p;}
-"
+" "${cmake_source_dir}/Source/CMakeVersion.cmake"
}
# Install destination extraction function.
cmake_install_dest_default()
{
- cat "${cmake_source_dir}/Source/CMakeInstallDestinations.cmake" | sed -n '
+ sed -n '
/^ *set(CMAKE_'"${1}"'_DIR_DEFAULT.*) # '"${2}"'$/ {
s/^ *set(CMAKE_'"${1}"'_DIR_DEFAULT *"\([^"]*\)").*$/\1/
s/${CMake_VERSION_MAJOR}/'"${cmake_version_major}"'/
@@ -37,12 +33,12 @@ cmake_install_dest_default()
p
q
}
-'
+' "${cmake_source_dir}/Source/CMakeInstallDestinations.cmake"
}
cmake_toupper()
{
- echo "$1" | sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/'
+ echo "$1" | tr '[:lower:]' '[:upper:]'
}
# Detect system and directory information.
@@ -76,7 +72,6 @@ cmake_init_file=""
cmake_bootstrap_system_libs=""
cmake_bootstrap_qt_gui=""
cmake_bootstrap_qt_qmake=""
-cmake_bootstrap_server=""
cmake_sphinx_man=""
cmake_sphinx_html=""
cmake_sphinx_qthelp=""
@@ -133,6 +128,11 @@ fi
# Determine whether this is HP-UX
if echo "${cmake_system}" | grep HP-UX >/dev/null 2>&1; then
+ die 'CMake no longer compiles on HP-UX. See
+
+ https://gitlab.kitware.com/cmake/cmake/issues/17137
+
+Use CMake 3.9 or lower instead.'
cmake_system_hpux=true
else
cmake_system_hpux=false
@@ -334,6 +334,7 @@ CMAKE_CXX_SOURCES="\
cmHexFileConverter \
cmIfCommand \
cmIncludeCommand \
+ cmIncludeGuardCommand \
cmIncludeDirectoryCommand \
cmIncludeRegularExpressionCommand \
cmInstallCommand \
@@ -401,8 +402,14 @@ CMAKE_CXX_SOURCES="\
cmSubdirCommand \
cmSystemTools \
cmTarget \
+ cmTargetCompileDefinitionsCommand \
+ cmTargetCompileFeaturesCommand \
+ cmTargetCompileOptionsCommand \
+ cmTargetIncludeDirectoriesCommand \
cmTargetLinkLibrariesCommand \
+ cmTargetPropCommandBase \
cmTargetPropertyComputer \
+ cmTargetSourcesCommand \
cmTest \
cmTestGenerator \
cmTimestamp \
@@ -473,6 +480,59 @@ KWSYS_FILES="\
SystemTools.hxx \
Terminal.h"
+if ${cmake_system_mingw}; then
+ LIBUV_C_SOURCES="\
+ src/fs-poll.c \
+ src/inet.c \
+ src/threadpool.c \
+ src/uv-common.c \
+ src/win/async.c \
+ src/win/core.c \
+ src/win/detect-wakeup.c \
+ src/win/dl.c \
+ src/win/error.c \
+ src/win/fs-event.c \
+ src/win/fs.c \
+ src/win/getaddrinfo.c \
+ src/win/getnameinfo.c \
+ src/win/handle.c \
+ src/win/loop-watcher.c \
+ src/win/pipe.c \
+ src/win/poll.c \
+ src/win/process-stdio.c \
+ src/win/process.c \
+ src/win/req.c \
+ src/win/signal.c \
+ src/win/stream.c \
+ src/win/tcp.c \
+ src/win/thread.c \
+ src/win/timer.c \
+ src/win/tty.c \
+ src/win/udp.c \
+ src/win/util.c \
+ src/win/winapi.c \
+ src/win/winsock.c \
+ "
+else
+ LIBUV_C_SOURCES="\
+ src/uv-common.c \
+ src/unix/cmake-bootstrap.c \
+ src/unix/core.c \
+ src/unix/fs.c \
+ src/unix/loop.c \
+ src/unix/loop-watcher.c \
+ src/unix/no-fsevents.c \
+ src/unix/pipe.c \
+ src/unix/poll.c \
+ src/unix/posix-hrtime.c \
+ src/unix/posix-poll.c \
+ src/unix/process.c \
+ src/unix/signal.c \
+ src/unix/stream.c \
+ src/unix/timer.c \
+ "
+fi
+
# Display CMake bootstrap usage
cmake_usage()
{
@@ -512,9 +572,6 @@ Configuration:
--no-qt-gui do not build the Qt-based GUI (default)
--qt-qmake=<qmake> use <qmake> as the qmake executable to find Qt
- --server enable the server mode (default if supported)
- --no-server disable the server mode
-
--sphinx-man build man pages with Sphinx
--sphinx-html build html help with Sphinx
--sphinx-qthelp build qch help with Sphinx
@@ -581,8 +638,7 @@ cmake_replace_string ()
SEARCHFOR="$3"
REPLACEWITH="$4"
if [ -f "${INFILE}" ] || ${cmake_system_openvms}; then
- cat "${INFILE}" |
- sed "s/\@${SEARCHFOR}\@/${REPLACEWITH}/g" > "${OUTFILE}${_tmp}"
+ sed "s/\@${SEARCHFOR}\@/${REPLACEWITH}/g" "${INFILE}" > "${OUTFILE}${_tmp}"
if [ -f "${OUTFILE}${_tmp}" ]; then
if "${_diff}" "${OUTFILE}" "${OUTFILE}${_tmp}" > /dev/null 2> /dev/null ; then
#echo "Files are the same"
@@ -604,15 +660,14 @@ cmake_kwsys_config_replace_string ()
APPEND="$*"
if [ -f "${INFILE}" ] || ${cmake_system_openvms}; then
echo "${APPEND}" > "${OUTFILE}${_tmp}"
- cat "${INFILE}" |
- sed "/./ {s/\@KWSYS_NAMESPACE\@/cmsys/g;
- s/@KWSYS_BUILD_SHARED@/${KWSYS_BUILD_SHARED}/g;
- s/@KWSYS_LFS_AVAILABLE@/${KWSYS_LFS_AVAILABLE}/g;
- s/@KWSYS_LFS_REQUESTED@/${KWSYS_LFS_REQUESTED}/g;
- s/@KWSYS_NAME_IS_KWSYS@/${KWSYS_NAME_IS_KWSYS}/g;
- s/@KWSYS_STL_HAS_WSTRING@/${KWSYS_STL_HAS_WSTRING}/g;
- s/@KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H@/${KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H}/g;
- }" >> "${OUTFILE}${_tmp}"
+ sed "/./ {s/\@KWSYS_NAMESPACE\@/cmsys/g;
+ s/@KWSYS_BUILD_SHARED@/${KWSYS_BUILD_SHARED}/g;
+ s/@KWSYS_LFS_AVAILABLE@/${KWSYS_LFS_AVAILABLE}/g;
+ s/@KWSYS_LFS_REQUESTED@/${KWSYS_LFS_REQUESTED}/g;
+ s/@KWSYS_NAME_IS_KWSYS@/${KWSYS_NAME_IS_KWSYS}/g;
+ s/@KWSYS_STL_HAS_WSTRING@/${KWSYS_STL_HAS_WSTRING}/g;
+ s/@KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H@/${KWSYS_CXX_HAS_EXT_STDIO_FILEBUF_H}/g;
+ }" "${INFILE}" >> "${OUTFILE}${_tmp}"
if [ -f "${OUTFILE}${_tmp}" ]; then
if "${_diff}" "${OUTFILE}" "${OUTFILE}${_tmp}" > /dev/null 2> /dev/null ; then
#echo "Files are the same"
@@ -639,6 +694,12 @@ cmake_escape ()
echo $1 | sed "s/ /\\\\ /g"
}
+# Encode object file names.
+cmake_obj ()
+{
+ echo $1 | sed 's/\//-/g' | sed 's/$/\.o/'
+}
+
# Strip prefix from argument
cmake_arg ()
{
@@ -749,8 +810,6 @@ while test $# != 0; do
--qt-gui) cmake_bootstrap_qt_gui="1" ;;
--no-qt-gui) cmake_bootstrap_qt_gui="0" ;;
--qt-qmake=*) cmake_bootstrap_qt_qmake=`cmake_arg "$1"` ;;
- --server) cmake_bootstrap_server="1" ;;
- --no-server) cmake_bootstrap_server="0" ;;
--sphinx-man) cmake_sphinx_man="1" ;;
--sphinx-html) cmake_sphinx_html="1" ;;
--sphinx-qthelp) cmake_sphinx_qthelp="1" ;;
@@ -861,16 +920,6 @@ if ${cmake_system_haiku}; then
cmake_ld_flags="${LDFLAGS} -lroot -lbe"
fi
-# Workaround for short jump tables on PA-RISC
-if ${cmake_machine_parisc}; then
- if ${cmake_c_compiler_is_gnu}; then
- cmake_c_flags="${CFLAGS} -mlong-calls"
- fi
- if ${cmake_cxx_compiler_is_gnu}; then
- cmake_cxx_flags="${CXXFLAGS} -mlong-calls"
- fi
-fi
-
#-----------------------------------------------------------------------------
# Detect known toolchains on some platforms.
cmake_toolchains=''
@@ -951,35 +1000,30 @@ echo '
# error "The CMAKE_C_COMPILER is set to a C++ compiler"
#endif
-#include<stdio.h>
+#if defined(__sun) && __STDC_VERSION__ < 199901L
+#error "On Solaris we need C99."
+#endif
+
+#include <stdio.h>
-#if defined(__CLASSIC_C__)
-int main(argc, argv)
- int argc;
- char* argv[];
-#else
int main(int argc, char* argv[])
-#endif
{
printf("%d%c", (argv != 0), (char)0x0a);
- return argc-1;
+ return argc - 1;
}
' > "${TMPFILE}.c"
-for a in ${cmake_c_compilers}; do
- if [ -z "${cmake_c_compiler}" ] && \
- cmake_try_run "${a}" "${cmake_c_flags}" "${TMPFILE}.c" >> cmake_bootstrap.log 2>&1; then
- cmake_c_compiler="${a}"
- fi
-done
for std in 11 99 90; do
try_flags="`cmake_extract_standard_flags \"${cmake_toolchain}\" C \"${std}\"`"
- for flag in $try_flags; do
- echo "Checking whether ${cmake_c_compiler} supports ${flag}" >> cmake_bootstrap.log 2>&1
- if cmake_try_run "${cmake_c_compiler}" "${cmake_c_flags} ${flag}" \
- "${TMPFILE}.c" >> cmake_bootstrap.log 2>&1; then
- cmake_c_flags="${cmake_c_flags} ${flag}"
- break 2
- fi
+ for compiler in ${cmake_c_compilers}; do
+ for flag in '' $try_flags; do
+ echo "Checking whether '${compiler} ${cmake_c_flags} ${flag}' works." >> cmake_bootstrap.log 2>&1
+ if cmake_try_run "${compiler}" "${cmake_c_flags} ${flag}" \
+ "${TMPFILE}.c" >> cmake_bootstrap.log 2>&1; then
+ cmake_c_compiler="${compiler}"
+ cmake_c_flags="${cmake_c_flags} ${flag}"
+ break 3
+ fi
+ done
done
done
rm -f "${TMPFILE}.c"
@@ -1010,58 +1054,49 @@ fi
# Check if C++ compiler works
TMPFILE=`cmake_tmp_file`
echo '
-#if defined(TEST1)
-# include <iostream>
-#else
-# include <iostream.h>
+#include <iostream>
+#include <memory>
+
+#if __cplusplus < 201103L
+#error "Compiler is not in a mode aware of C++11."
#endif
-#if __cplusplus >= 201103L && defined(__SUNPRO_CC) && __SUNPRO_CC < 0x5140
-#error "SunPro <= 5.13 C++ 11 mode not supported due to bug in move semantics."
+#if defined(__SUNPRO_CC) && __SUNPRO_CC < 0x5140
+#error "SunPro <= 5.13 mode not supported due to bug in move semantics."
#endif
-class NeedCXX
+class Class
{
public:
- NeedCXX() { this->Foo = 1; }
- int GetFoo() { return this->Foo; }
+ int Get() const { return this->Member; }
private:
- int Foo;
+ int Member = 1;
};
int main()
{
- NeedCXX c;
-#ifdef TEST3
- cout << c.GetFoo() << endl;
-#else
- std::cout << c.GetFoo() << std::endl;
-#endif
+ auto const c = std::unique_ptr<Class>(new Class);
+ std::cout << c->Get() << std::endl;
return 0;
}
' > "${TMPFILE}.cxx"
-for a in ${cmake_cxx_compilers}; do
- for b in 1 2 3; do
- if [ -z "${cmake_cxx_compiler}" ] && \
- cmake_try_run "${a}" "${cmake_cxx_flags} -DTEST${b}" "${TMPFILE}.cxx" >> cmake_bootstrap.log 2>&1; then
- cmake_cxx_compiler="${a}"
- fi
- done
-done
-for std in 14 11 98; do
+for std in 17 14 11; do
try_flags="`cmake_extract_standard_flags \"${cmake_toolchain}\" CXX \"${std}\"`"
- for flag in $try_flags; do
- echo "Checking for wheter ${cmake_cxx_flags} supports ${flag}" >> cmake_bootstrap.log 2>&1
- if cmake_try_run "${cmake_cxx_compiler}" "${cmake_cxx_flags} ${flag} -DTEST1" \
- "${TMPFILE}.cxx" >> cmake_bootstrap.log 2>&1; then
- cmake_cxx_flags="${cmake_cxx_flags} ${flag} "
- break 2
- fi
+ for compiler in ${cmake_cxx_compilers}; do
+ for flag in '' $try_flags; do
+ echo "Checking whether '${compiler} ${cmake_cxx_flags} ${flag}' works." >> cmake_bootstrap.log 2>&1
+ if cmake_try_run "${compiler}" "${cmake_cxx_flags} ${flag}" \
+ "${TMPFILE}.cxx" >> cmake_bootstrap.log 2>&1; then
+ cmake_cxx_compiler="${compiler}"
+ cmake_cxx_flags="${cmake_cxx_flags} ${flag} "
+ break 3
+ fi
+ done
done
done
rm -f "${TMPFILE}.cxx"
if [ -z "${cmake_cxx_compiler}" ]; then
- cmake_error 7 "Cannot find appropriate C++ compiler on this system.
+cmake_error 7 "Cannot find a C++ compiler supporting C++11 on this system.
Please specify one using environment variable CXX.
See cmake_bootstrap.log for compilers attempted."
fi
@@ -1126,85 +1161,6 @@ if [ "x${cmake_full_make_flags}" != "x${cmake_make_flags}" ]; then
echo "---------------------------------------------"
fi
-# Ok, we have CC, CXX, and MAKE.
-
-# Test C++ compiler features
-
-# Are we GCC?
-
-TMPFILE=`cmake_tmp_file`
-echo '
-#if defined(__GNUC__) && !defined(__INTEL_COMPILER)
-#include <iostream>
-int main() { std::cout << "This is GNU" << std::endl; return 0;}
-#endif
-' > ${TMPFILE}.cxx
-cmake_cxx_compiler_is_gnu=0
-if cmake_try_run "${cmake_cxx_compiler}" \
- "${cmake_cxx_flags}" "${TMPFILE}.cxx" >> cmake_bootstrap.log 2>&1; then
- cmake_cxx_compiler_is_gnu=1
-fi
-if [ "x${cmake_cxx_compiler_is_gnu}" = "x1" ]; then
- echo "${cmake_cxx_compiler} is GNU compiler"
-else
- echo "${cmake_cxx_compiler} is not GNU compiler"
-fi
-rm -f "${TMPFILE}.cxx"
-
-if [ "x${cmake_cxx_compiler_is_gnu}" != "x1" ]; then
- # Check for non-GNU compiler flags
-
- # If we are on HP-UX, check for -Ae for the C compiler.
- if [ "x${cmake_system}" = "xHP-UX" ]; then
- cmake_test_flags="-Ae"
- TMPFILE=`cmake_tmp_file`
- echo '
- int main(int argc, char** argv) { (void)argc; (void)argv; return 0; }
-' > ${TMPFILE}.c
- cmake_need_Ae=0
- if cmake_try_run "${cmake_c_compiler}" "${cmake_c_flags}" "${TMPFILE}.c" >> cmake_bootstrap.log 2>&1; then
- :
- else
- if cmake_try_run "${cmake_c_compiler}" \
- "${cmake_c_flags} ${cmake_test_flags}" "${TMPFILE}.c" >> cmake_bootstrap.log 2>&1; then
- cmake_need_Ae=1
- fi
- fi
- if [ "x${cmake_need_Ae}" = "x1" ]; then
- cmake_c_flags="${cmake_c_flags} ${cmake_test_flags}"
- echo "${cmake_c_compiler} needs ${cmake_test_flags}"
- else
- echo "${cmake_c_compiler} does not need ${cmake_test_flags}"
- fi
- rm -f "${TMPFILE}.c"
- echo '
- #include <iostream>
- int main(int argc, char** argv) {
- for(int i=0; i < 1; ++i);
- for(int i=0; i < 1; ++i);
- (void)argc; (void)argv; return 0; }
-' > ${TMPFILE}.cxx
- cmake_need_AAstd98=0
- cmake_test_flags="-AA +hpxstd98"
- if cmake_try_run "${cmake_cxx_compiler}" "${cmake_cxx_flags}" "${TMPFILE}.cxx" >> cmake_bootstrap.log 2>&1; then
- :
- else
- if cmake_try_run "${cmake_cxx_compiler}" \
- "${cmake_cxx_flags} ${cmake_test_flags}" "${TMPFILE}.cxx" >> cmake_bootstrap.log 2>&1; then
- cmake_need_AAstd98=1
- fi
- fi
- if [ "x${cmake_need_AAstd98}" = "x1" ]; then
- cmake_cxx_flags="${cmake_cxx_flags} ${cmake_test_flags}"
- echo "${cmake_cxx_compiler} needs ${cmake_test_flags}"
- else
- echo "${cmake_cxx_compiler} does not need ${cmake_test_flags}"
- fi
- fi
- cmake_test_flags=
-fi
-
-
# Test for kwsys features
KWSYS_NAME_IS_KWSYS=0
KWSYS_BUILD_SHARED=0
@@ -1287,6 +1243,8 @@ cmake_compiler_settings_comment="/*
* ${LexerParser_CXX_SOURCES} ${LexerParser_C_SOURCES}
* kwSys Sources:
* ${KWSYS_CXX_SOURCES} ${KWSYS_C_SOURCES}
+ * libuv Sources:
+ * ${LIBUV_C_SOURCES}
*/
"
@@ -1312,10 +1270,7 @@ cmake_report cmConfigure.h${_tmp} "#define CMAKE_BOOTSTRAP_BINARY_DIR \"${CMAKE_
cmake_report cmConfigure.h${_tmp} "#define CMAKE_BIN_DIR \"/bootstrap-not-insalled\""
cmake_report cmConfigure.h${_tmp} "#define CMAKE_DATA_DIR \"/bootstrap-not-insalled\""
cmake_report cmConfigure.h${_tmp} "#define CMAKE_BOOTSTRAP"
-cmake_report cmConfigure.h${_tmp} "#define CM_EQ_DELETE"
cmake_report cmConfigure.h${_tmp} "#define CM_FALLTHROUGH"
-cmake_report cmConfigure.h${_tmp} "#define CM_NULLPTR 0"
-cmake_report cmConfigure.h${_tmp} "#define CM_OVERRIDE"
cmake_report cmConfigure.h${_tmp} "#define CM_DISABLE_COPY(Class)"
# Regenerate configured headers
@@ -1350,6 +1305,48 @@ objs=""
for a in ${CMAKE_CXX_SOURCES} ${CMAKE_C_SOURCES} ${LexerParser_CXX_SOURCES} ${LexerParser_C_SOURCES} ${KWSYS_CXX_SOURCES} ${KWSYS_C_SOURCES}; do
objs="${objs} ${a}.o"
done
+for a in ${LIBUV_C_SOURCES}; do
+ objs="${objs} uv-`cmake_obj ${a}`"
+done
+
+libs=""
+
+uv_c_flags=""
+if ${cmake_system_mingw}; then
+ uv_c_flags="${uv_c_flags} -DWIN32_LEAN_AND_MEAN -D_WIN32_WINNT=0x0600"
+ libs="${libs} -lws2_32 -lpsapi -liphlpapi -lshell32 -luserenv"
+else
+ uv_c_flags="${uv_c_flags} -DCMAKE_BOOTSTRAP"
+ case "${cmake_system}" in
+ *AIX*)
+ uv_c_flags="${uv_c_flags} -D_ALL_SOURCE -D_XOPEN_SOURCE=500 -D_LINUX_SOURCE_COMPAT -D_THREAD_SAFE"
+ libs="${libs} -lperfstat"
+ ;;
+ *Darwin*)
+ uv_c_flags="${uv_c_flags} -D_DARWIN_USE_64_BIT_INODE=1 -D_DARWIN_UNLIMITED_SELECT=1"
+ ;;
+ *Linux*)
+ uv_c_flags="${uv_c_flags} -D_GNU_SOURCE"
+ libs="${libs} -ldl -lrt"
+ ;;
+ *BSD*)
+ libs="${libs} -lkvm"
+ ;;
+ *SunOS*)
+ # Normally libuv uses '-D_XOPEN_SOURCE=500 -std=c90' on Solaris 5.10,
+ # but we do not need to do that because we bootstrap using POSIX APIs.
+ uv_c_flags="${uv_c_flags} -D__EXTENSIONS__ -D_XOPEN_SOURCE=600"
+ libs="${libs} -lkstat -lnsl -lsendfile -lsocket -lrt"
+ ;;
+ esac
+fi
+uv_c_flags="${uv_c_flags} `cmake_escape "-I${cmake_source_dir}/Utilities/cmlibuv/include"`"
+if ${cmake_system_mingw}; then
+ uv_c_flags="${uv_c_flags} `cmake_escape "-I${cmake_source_dir}/Utilities/cmlibuv/src/win"`"
+else
+ uv_c_flags="${uv_c_flags} `cmake_escape "-I${cmake_source_dir}/Utilities/cmlibuv/src/unix"`"
+fi
+uv_c_flags="${uv_c_flags} `cmake_escape "-I${cmake_source_dir}/Utilities/cmlibuv/src"`"
if [ "x${cmake_ansi_cxx_flags}" != "x" ]; then
cmake_cxx_flags="${cmake_ansi_cxx_flags} ${cmake_cxx_flags}"
@@ -1387,7 +1384,7 @@ cmake_cxx_flags="${cmake_cxx_flags} \
-I`cmake_escape \"${cmake_source_dir}/Source/LexerParser\"` \
-I`cmake_escape \"${cmake_source_dir}/Utilities\"`"
echo "cmake: ${objs}" > "${cmake_bootstrap_dir}/Makefile"
-echo " ${cmake_cxx_compiler} ${cmake_ld_flags} ${cmake_cxx_flags} ${objs} -o cmake" >> "${cmake_bootstrap_dir}/Makefile"
+echo " ${cmake_cxx_compiler} ${cmake_ld_flags} ${cmake_cxx_flags} ${objs} ${libs} -o cmake" >> "${cmake_bootstrap_dir}/Makefile"
for a in ${CMAKE_CXX_SOURCES}; do
src=`cmake_escape "${cmake_source_dir}/Source/${a}.cxx"`
src_flags=`eval echo \\${cmake_cxx_flags_\${a}}`
@@ -1422,6 +1419,11 @@ for a in ${KWSYS_CXX_SOURCES}; do
echo "${a}.o : ${src} ${dep}" >> "${cmake_bootstrap_dir}/Makefile"
echo " ${cmake_cxx_compiler} ${cmake_cxx_flags} -DKWSYS_NAMESPACE=cmsys ${src_flags} -c ${src} -o ${a}.o" >> "${cmake_bootstrap_dir}/Makefile"
done
+for a in ${LIBUV_C_SOURCES}; do
+ src=`cmake_escape "${cmake_source_dir}/Utilities/cmlibuv/${a}"`
+ echo "uv-`cmake_obj ${a}` : ${src} ${dep}" >> "${cmake_bootstrap_dir}/Makefile"
+ echo " ${cmake_c_compiler} ${cmake_c_flags} ${uv_c_flags} -c ${src} -o uv-`cmake_obj ${a}`" >> "${cmake_bootstrap_dir}/Makefile"
+done
echo '
rebuild_cache:
cd "${cmake_binary_dir}" && "${cmake_source_dir}/bootstrap"
@@ -1450,11 +1452,6 @@ if [ "x${cmake_bootstrap_qt_qmake}" != "x" ]; then
set (QT_QMAKE_EXECUTABLE "'"${cmake_bootstrap_qt_qmake}"'" CACHE FILEPATH "Location of Qt qmake" FORCE)
' >> "${cmake_bootstrap_dir}/InitialCacheFlags.cmake"
fi
-if [ "x${cmake_bootstrap_server}" != "x" ]; then
- echo '
-set (CMake_ENABLE_SERVER_MODE '"${cmake_bootstrap_server}"' CACHE BOOL "Enable server mode" FORCE)
-' >> "${cmake_bootstrap_dir}/InitialCacheFlags.cmake"
-fi
if [ "x${cmake_sphinx_man}" != "x" ]; then
echo '
set (SPHINX_MAN "'"${cmake_sphinx_man}"'" CACHE BOOL "Build man pages with Sphinx" FORCE)